blob: bcca7c8fb053c051c82c3f1d3f722e6683338e68 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
Logan Chiend557d762018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
Daniel Rosenberg65f99c92018-08-28 01:58:49 -070027#include "Checkpoint.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070029#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080030#include "Keymaster.h"
31#include "Process.h"
32#include "ScryptParameters.h"
Paul Crowleycfe39722018-10-30 15:59:24 -070033#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080034#include "VoldUtil.h"
35#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080036
Eric Biggersed45ec32019-01-25 10:47:55 -080037#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080039#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080040#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070043#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070045#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070046#include <fscrypt/fscrypt.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080047#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080048#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080049#include <logwrap/logwrap.h>
50#include <openssl/evp.h>
51#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080052#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080053
54#include <ctype.h>
55#include <errno.h>
56#include <fcntl.h>
57#include <inttypes.h>
58#include <libgen.h>
59#include <linux/dm-ioctl.h>
60#include <linux/kdev_t.h>
61#include <math.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <sys/ioctl.h>
66#include <sys/mount.h>
67#include <sys/param.h>
68#include <sys/stat.h>
69#include <sys/types.h>
70#include <sys/wait.h>
71#include <time.h>
72#include <unistd.h>
73
AnilKumar Chimataedac9df2018-05-11 00:25:09 +053074#ifdef CONFIG_HW_DISK_ENCRYPTION
75#include <cryptfs_hw.h>
76#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080077extern "C" {
78#include <crypto_scrypt.h>
79}
Mark Salyzyn3e971272014-01-21 13:27:04 -080080
Eric Biggersed45ec32019-01-25 10:47:55 -080081using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080082using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080083using android::fs_mgr::GetEntryForMountPoint;
Paul Crowleycfe39722018-10-30 15:59:24 -070084using namespace std::chrono_literals;
85
Mark Salyzyn5eecc442014-02-12 14:16:14 -080086#define UNUSED __attribute__((unused))
87
Ken Sumrall8f869aa2010-12-03 03:47:09 -080088#define DM_CRYPT_BUF_SIZE 4096
89
Jason parks70a4b3f2011-01-28 10:10:47 -060090#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080091
92constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
93constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070094constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080095
96// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070097static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060098
Paul Crowley14c8c072018-09-18 13:30:21 -070099#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700100
AnilKumar Chimataedac9df2018-05-11 00:25:09 +0530101#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700102#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800103
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800104#define CRYPTO_BLOCK_DEVICE "userdata"
105
106#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
107
Ken Sumrall29d8da82011-05-18 17:20:07 -0700108#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700109#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700110
Ken Sumralle919efe2012-09-29 17:07:41 -0700111#define TABLE_LOAD_RETRIES 10
112
Shawn Willden47ba10d2014-09-03 17:07:06 -0600113#define RSA_KEY_SIZE 2048
114#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
115#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600116#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimataedac9df2018-05-11 00:25:09 +0530117#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700118
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700119#define RETRY_MOUNT_ATTEMPTS 10
120#define RETRY_MOUNT_DELAY_SECONDS 1
121
Paul Crowley5afbc622017-11-27 09:42:17 -0800122#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
123
Paul Crowley73473332017-11-21 15:43:51 -0800124static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
125
Greg Kaiser59ad0182018-02-16 13:01:36 -0800126static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700127static char* saved_mount_point;
128static int master_key_saved = 0;
129static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800130
AnilKumar Chimataedac9df2018-05-11 00:25:09 +0530131static int previous_type;
132
133#ifdef CONFIG_HW_DISK_ENCRYPTION
134static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
135 unsigned char *ikey, void *params);
136static void convert_key_to_hex_ascii(const unsigned char *master_key,
137 unsigned int keysize, char *master_key_ascii);
138static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
139static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
140 const char *passwd, const char *mount_point, const char *label);
141int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
142 const char *newpw);
143int cryptfs_check_passwd_hw(char *passwd);
144int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
145 unsigned char* master_key);
146
147static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
148 unsigned int keysize, char *master_key_ascii)
149{
150 unsigned int i, a;
151 unsigned char nibble;
152
153 for (i = 0, a = 0; i < keysize; i++, a += 2) {
154 /* For each byte, write out two ascii hex digits */
155 nibble = (master_key[i] >> 4) & 0xf;
156 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
157
158 nibble = master_key[i] & 0xf;
159 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
160 }
161
162 /* Add the null termination */
163 master_key_ascii[a] = '\0';
164}
165
166static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
167 unsigned char* salt,
168 const struct crypt_mnt_ftr *ftr)
169{
170 /* if newpw updated, return 0
171 * if newpw not updated return -1
172 */
173 int rc = -1;
174
175 if (should_use_keymaster()) {
176 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
177 SLOGE("scrypt failed");
178 } else {
179 rc = 0;
180 }
181 }
182
183 return rc;
184}
185
186static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
187{
188 unsigned char newpw[32] = {0};
189 int key_index;
190 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
191 key_index = set_hw_device_encryption_key(passwd,
192 (char*) crypt_ftr->crypto_type_name);
193 else
194 key_index = set_hw_device_encryption_key((const char*)newpw,
195 (char*) crypt_ftr->crypto_type_name);
196 return key_index;
197}
198
199static int verify_and_update_hw_fde_passwd(const char *passwd,
200 struct crypt_mnt_ftr* crypt_ftr)
201{
202 char* new_passwd = NULL;
203 unsigned char newpw[32] = {0};
204 int key_index = -1;
205 int passwd_updated = -1;
206 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
207
208 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
209 if (key_index < 0) {
210 ++crypt_ftr->failed_decrypt_count;
211
212 if (ascii_passwd_updated) {
213 SLOGI("Ascii password was updated");
214 } else {
215 /* Code in else part would execute only once:
216 * When device is upgraded from L->M release.
217 * Once upgraded, code flow should never come here.
218 * L release passed actual password in hex, so try with hex
219 * Each nible of passwd was encoded as a byte, so allocate memory
220 * twice of password len plus one more byte for null termination
221 */
222 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
223 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
224 if (new_passwd == NULL) {
225 SLOGE("System out of memory. Password verification incomplete");
226 goto out;
227 }
228 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
229 } else {
230 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
231 if (new_passwd == NULL) {
232 SLOGE("System out of memory. Password verification incomplete");
233 goto out;
234 }
235 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
236 strlen(passwd), new_passwd);
237 }
238 key_index = set_hw_device_encryption_key((const char*)new_passwd,
239 (char*) crypt_ftr->crypto_type_name);
240 if (key_index >=0) {
241 crypt_ftr->failed_decrypt_count = 0;
242 SLOGI("Hex password verified...will try to update with Ascii value");
243 /* Before updating password, tie that with keymaster to tie with ROT */
244
245 if (get_keymaster_hw_fde_passwd(passwd, newpw,
246 crypt_ftr->salt, crypt_ftr)) {
247 passwd_updated = update_hw_device_encryption_key(new_passwd,
248 passwd, (char*)crypt_ftr->crypto_type_name);
249 } else {
250 passwd_updated = update_hw_device_encryption_key(new_passwd,
251 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
252 }
253
254 if (passwd_updated >= 0) {
255 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
256 SLOGI("Ascii password recorded and updated");
257 } else {
258 SLOGI("Passwd verified, could not update...Will try next time");
259 }
260 } else {
261 ++crypt_ftr->failed_decrypt_count;
262 }
263 free(new_passwd);
264 }
265 } else {
266 if (!ascii_passwd_updated)
267 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
268 }
269out:
270 // update footer before leaving
271 put_crypt_ftr_and_key(crypt_ftr);
272 return key_index;
273}
274#endif
275
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700276/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700277static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000278 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700279}
280
281/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700282static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800283 if (ftr->keymaster_blob_size) {
284 SLOGI("Already have key");
285 return 0;
286 }
287
Paul Crowley14c8c072018-09-18 13:30:21 -0700288 int rc = keymaster_create_key_for_cryptfs_scrypt(
289 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
290 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000291 if (rc) {
292 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800293 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000294 ftr->keymaster_blob_size = 0;
295 }
296 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700297 return -1;
298 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000299 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700300}
301
Shawn Willdene17a9c42014-09-08 13:04:08 -0600302/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700303static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
304 const size_t object_size, unsigned char** signature,
305 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600306 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600307 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600308 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600309
Shawn Willdene17a9c42014-09-08 13:04:08 -0600310 // To sign a message with RSA, the message must satisfy two
311 // constraints:
312 //
313 // 1. The message, when interpreted as a big-endian numeric value, must
314 // be strictly less than the public modulus of the RSA key. Note
315 // that because the most significant bit of the public modulus is
316 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
317 // key), an n-bit message with most significant bit 0 always
318 // satisfies this requirement.
319 //
320 // 2. The message must have the same length in bits as the public
321 // modulus of the RSA key. This requirement isn't mathematically
322 // necessary, but is necessary to ensure consistency in
323 // implementations.
324 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600325 case KDF_SCRYPT_KEYMASTER:
326 // This ensures the most significant byte of the signed message
327 // is zero. We could have zero-padded to the left instead, but
328 // this approach is slightly more robust against changes in
329 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600330 // so) because we really should be using a proper deterministic
331 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800332 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600333 SLOGI("Signing safely-padded object");
334 break;
335 default:
336 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000337 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600338 }
Paul Crowley73473332017-11-21 15:43:51 -0800339 for (;;) {
340 auto result = keymaster_sign_object_for_cryptfs_scrypt(
341 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
342 to_sign_size, signature, signature_size);
343 switch (result) {
344 case KeymasterSignResult::ok:
345 return 0;
346 case KeymasterSignResult::upgrade:
347 break;
348 default:
349 return -1;
350 }
351 SLOGD("Upgrading key");
352 if (keymaster_upgrade_key_for_cryptfs_scrypt(
353 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
354 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
355 &ftr->keymaster_blob_size) != 0) {
356 SLOGE("Failed to upgrade key");
357 return -1;
358 }
359 if (put_crypt_ftr_and_key(ftr) != 0) {
360 SLOGE("Failed to write upgraded key to disk");
361 }
362 SLOGD("Key upgraded successfully");
363 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600364}
365
Paul Lawrence399317e2014-03-10 13:20:50 -0700366/* Store password when userdata is successfully decrypted and mounted.
367 * Cleared by cryptfs_clear_password
368 *
369 * To avoid a double prompt at boot, we need to store the CryptKeeper
370 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
371 * Since the entire framework is torn down and rebuilt after encryption,
372 * we have to use a daemon or similar to store the password. Since vold
373 * is secured against IPC except from system processes, it seems a reasonable
374 * place to store this.
375 *
376 * password should be cleared once it has been used.
377 *
378 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800379 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700380static char* password = 0;
381static int password_expiry_time = 0;
382static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800383
Paul Crowley14c8c072018-09-18 13:30:21 -0700384enum class RebootType { reboot, recovery, shutdown };
385static void cryptfs_reboot(RebootType rt) {
386 switch (rt) {
387 case RebootType::reboot:
388 property_set(ANDROID_RB_PROPERTY, "reboot");
389 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800390
Paul Crowley14c8c072018-09-18 13:30:21 -0700391 case RebootType::recovery:
392 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
393 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800394
Paul Crowley14c8c072018-09-18 13:30:21 -0700395 case RebootType::shutdown:
396 property_set(ANDROID_RB_PROPERTY, "shutdown");
397 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700398 }
Paul Lawrence87999172014-02-20 12:21:31 -0800399
Ken Sumralladfba362013-06-04 16:37:52 -0700400 sleep(20);
401
402 /* Shouldn't get here, reboot should happen before sleep times out */
403 return;
404}
405
Paul Crowley14c8c072018-09-18 13:30:21 -0700406static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800407 memset(io, 0, dataSize);
408 io->data_size = dataSize;
409 io->data_start = sizeof(struct dm_ioctl);
410 io->version[0] = 4;
411 io->version[1] = 0;
412 io->version[2] = 0;
413 io->flags = flags;
414 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100415 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800416 }
417}
418
Greg Kaiser38723f22018-02-16 13:35:35 -0800419namespace {
420
421struct CryptoType;
422
423// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700424const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800425
426struct CryptoType {
427 // We should only be constructing CryptoTypes as part of
428 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
429 // which isn't pure or fully protected as a concession to being able to
430 // do it all at compile time. Add new CryptoTypes in
431 // supported_crypto_types[] below.
432 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
433 constexpr CryptoType set_keysize(uint32_t size) const {
434 return CryptoType(this->property_name, this->crypto_name, size);
435 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700436 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800437 return CryptoType(property, this->crypto_name, this->keysize);
438 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700439 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800440 return CryptoType(this->property_name, crypto, this->keysize);
441 }
442
Paul Crowley14c8c072018-09-18 13:30:21 -0700443 constexpr const char* get_property_name() const { return property_name; }
444 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800445 constexpr uint32_t get_keysize() const { return keysize; }
446
Paul Crowley14c8c072018-09-18 13:30:21 -0700447 private:
448 const char* property_name;
449 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800450 uint32_t keysize;
451
Paul Crowley14c8c072018-09-18 13:30:21 -0700452 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800453 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700454 friend const CryptoType& get_crypto_type();
455 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800456};
457
458// We only want to parse this read-only property once. But we need to wait
459// until the system is initialized before we can read it. So we use a static
460// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700461const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800462 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
463 return crypto_type;
464}
465
466constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700467 .set_property_name("AES-128-CBC")
468 .set_crypto_name("aes-cbc-essiv:sha256")
469 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800470
471constexpr CryptoType supported_crypto_types[] = {
472 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800473 CryptoType()
474 .set_property_name("adiantum")
475 .set_crypto_name("xchacha12,aes-adiantum-plain64")
476 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800477 // Add new CryptoTypes here. Order is not important.
478};
479
Greg Kaiser38723f22018-02-16 13:35:35 -0800480// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
481// We confirm all supported_crypto_types have a small enough keysize and
482// had both set_property_name() and set_crypto_name() called.
483
484template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700485constexpr size_t array_length(T (&)[N]) {
486 return N;
487}
Greg Kaiser38723f22018-02-16 13:35:35 -0800488
489constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
490 return (index >= array_length(supported_crypto_types));
491}
492
Paul Crowley14c8c072018-09-18 13:30:21 -0700493constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800494 return ((crypto_type.get_property_name() != nullptr) &&
495 (crypto_type.get_crypto_name() != nullptr) &&
496 (crypto_type.get_keysize() <= MAX_KEY_LEN));
497}
498
499// Note in C++11 that constexpr functions can only have a single line.
500// So our code is a bit convoluted (using recursion instead of a loop),
501// but it's asserting at compile time that all of our key lengths are valid.
502constexpr bool validateSupportedCryptoTypes(size_t index) {
503 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700504 (isValidCryptoType(supported_crypto_types[index]) &&
505 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800506}
507
508static_assert(validateSupportedCryptoTypes(0),
509 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
510 "incompletely constructed.");
511// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
512
Greg Kaiser38723f22018-02-16 13:35:35 -0800513// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700514const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800515 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
516 char paramstr[PROPERTY_VALUE_MAX];
517
Paul Crowley14c8c072018-09-18 13:30:21 -0700518 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
519 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800520 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
521 return ctype;
522 }
523 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700524 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
525 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800526 return default_crypto_type;
527}
528
529} // namespace
530
Kenny Rootc4c70f12013-06-14 12:11:38 -0700531/**
532 * Gets the default device scrypt parameters for key derivation time tuning.
533 * The parameters should lead to about one second derivation time for the
534 * given device.
535 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700536static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700537 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000538 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700539
Paul Crowley63c18d32016-02-10 14:02:47 +0000540 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
541 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
542 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
543 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700544 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000545 ftr->N_factor = Nf;
546 ftr->r_factor = rf;
547 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700548}
549
Greg Kaiser57f9af62018-02-16 13:13:58 -0800550uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800551 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800552}
553
Paul Crowley14c8c072018-09-18 13:30:21 -0700554const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800555 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800556}
557
Tom Cherry4c5bde22019-01-29 14:34:01 -0800558static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800559 int fd, block_size;
560 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200561 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800562
Paul Crowley14c8c072018-09-18 13:30:21 -0700563 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800564 SLOGE("Cannot open device to get filesystem size ");
565 return 0;
566 }
567
568 if (lseek64(fd, 1024, SEEK_SET) < 0) {
569 SLOGE("Cannot seek to superblock");
570 return 0;
571 }
572
573 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
574 SLOGE("Cannot read superblock");
575 return 0;
576 }
577
578 close(fd);
579
Daniel Rosenberge82df162014-08-15 22:19:23 +0000580 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
581 SLOGE("Not a valid ext4 superblock");
582 return 0;
583 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800584 block_size = 1024 << sb.s_log_block_size;
585 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200586 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800587
588 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200589 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800590}
591
Tom Cherry4c5bde22019-01-29 14:34:01 -0800592static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
593 for (const auto& entry : fstab_default) {
594 if (!entry.fs_mgr_flags.vold_managed &&
595 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
596 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
597 if (key_loc != nullptr) {
598 *key_loc = entry.key_loc;
599 }
600 if (real_blk_device != nullptr) {
601 *real_blk_device = entry.blk_device;
602 }
603 return;
604 }
605 }
606}
607
Paul Crowley14c8c072018-09-18 13:30:21 -0700608static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
609 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200610 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700611 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700612 char key_loc[PROPERTY_VALUE_MAX];
613 char real_blkdev[PROPERTY_VALUE_MAX];
614 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700615
Paul Crowley14c8c072018-09-18 13:30:21 -0700616 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800617 std::string key_loc;
618 std::string real_blkdev;
619 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620
Tom Cherry4c5bde22019-01-29 14:34:01 -0800621 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200622 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700623 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
624 * encryption info footer and key, and plenty of bytes to spare for future
625 * growth.
626 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800627 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200628 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700629 cached_data = 1;
630 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800631 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700632 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700633 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800634 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700635 cached_off = 0;
636 cached_data = 1;
637 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700638 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700639
Paul Crowley14c8c072018-09-18 13:30:21 -0700640 if (cached_data) {
641 if (metadata_fname) {
642 *metadata_fname = cached_metadata_fname;
643 }
644 if (off) {
645 *off = cached_off;
646 }
647 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700648 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700649
Paul Crowley14c8c072018-09-18 13:30:21 -0700650 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700651}
652
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800653/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700654static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800655 SHA256_CTX c;
656 SHA256_Init(&c);
657 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
658 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
659 SHA256_Final(crypt_ftr->sha256, &c);
660}
661
Ken Sumralle8744072011-01-18 22:01:55 -0800662/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800663 * update the failed mount count but not change the key.
664 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700665static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
666 int fd;
667 unsigned int cnt;
668 /* starting_off is set to the SEEK_SET offset
669 * where the crypto structure starts
670 */
671 off64_t starting_off;
672 int rc = -1;
673 char* fname = NULL;
674 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800675
Paul Crowley14c8c072018-09-18 13:30:21 -0700676 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800677
Paul Crowley14c8c072018-09-18 13:30:21 -0700678 if (get_crypt_ftr_info(&fname, &starting_off)) {
679 SLOGE("Unable to get crypt_ftr_info\n");
680 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800681 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700682 if (fname[0] != '/') {
683 SLOGE("Unexpected value for crypto key location\n");
684 return -1;
685 }
686 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
687 SLOGE("Cannot open footer file %s for put\n", fname);
688 return -1;
689 }
Ken Sumralle8744072011-01-18 22:01:55 -0800690
Paul Crowley14c8c072018-09-18 13:30:21 -0700691 /* Seek to the start of the crypt footer */
692 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
693 SLOGE("Cannot seek to real block device footer\n");
694 goto errout;
695 }
696
697 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
698 SLOGE("Cannot write real block device footer\n");
699 goto errout;
700 }
701
702 fstat(fd, &statbuf);
703 /* If the keys are kept on a raw block device, do not try to truncate it. */
704 if (S_ISREG(statbuf.st_mode)) {
705 if (ftruncate(fd, 0x4000)) {
706 SLOGE("Cannot set footer file size\n");
707 goto errout;
708 }
709 }
710
711 /* Success! */
712 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800713
714errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700715 close(fd);
716 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800717}
718
Paul Crowley14c8c072018-09-18 13:30:21 -0700719static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800720 struct crypt_mnt_ftr copy;
721 memcpy(&copy, crypt_ftr, sizeof(copy));
722 set_ftr_sha(&copy);
723 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
724}
725
Paul Crowley14c8c072018-09-18 13:30:21 -0700726static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700727 return TEMP_FAILURE_RETRY(read(fd, buff, len));
728}
729
Paul Crowley14c8c072018-09-18 13:30:21 -0700730static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700731 return TEMP_FAILURE_RETRY(write(fd, buff, len));
732}
733
Paul Crowley14c8c072018-09-18 13:30:21 -0700734static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700735 memset(pdata, 0, len);
736 pdata->persist_magic = PERSIST_DATA_MAGIC;
737 pdata->persist_valid_entries = 0;
738}
739
740/* A routine to update the passed in crypt_ftr to the lastest version.
741 * fd is open read/write on the device that holds the crypto footer and persistent
742 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
743 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
744 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700745static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700746 int orig_major = crypt_ftr->major_version;
747 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700748
Kenny Root7434b312013-06-14 11:29:53 -0700749 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700750 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700751 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700752
Kenny Rootc4c70f12013-06-14 12:11:38 -0700753 SLOGW("upgrading crypto footer to 1.1");
754
Paul Crowley14c8c072018-09-18 13:30:21 -0700755 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700756 if (pdata == NULL) {
757 SLOGE("Cannot allocate persisent data\n");
758 return;
759 }
760 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
761
762 /* Need to initialize the persistent data area */
763 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
764 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100765 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700766 return;
767 }
768 /* Write all zeros to the first copy, making it invalid */
769 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
770
771 /* Write a valid but empty structure to the second copy */
772 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
773 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
774
775 /* Update the footer */
776 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
777 crypt_ftr->persist_data_offset[0] = pdata_offset;
778 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
779 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100780 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700781 }
782
Paul Lawrencef4faa572014-01-29 13:31:03 -0800783 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700784 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800785 /* But keep the old kdf_type.
786 * It will get updated later to KDF_SCRYPT after the password has been verified.
787 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700788 crypt_ftr->kdf_type = KDF_PBKDF2;
789 get_device_scrypt_params(crypt_ftr);
790 crypt_ftr->minor_version = 2;
791 }
792
Paul Lawrencef4faa572014-01-29 13:31:03 -0800793 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
794 SLOGW("upgrading crypto footer to 1.3");
795 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
796 crypt_ftr->minor_version = 3;
797 }
798
Kenny Root7434b312013-06-14 11:29:53 -0700799 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
800 if (lseek64(fd, offset, SEEK_SET) == -1) {
801 SLOGE("Cannot seek to crypt footer\n");
802 return;
803 }
804 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700805 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700806}
807
Paul Crowley14c8c072018-09-18 13:30:21 -0700808static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
809 int fd;
810 unsigned int cnt;
811 off64_t starting_off;
812 int rc = -1;
813 char* fname = NULL;
814 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815
Paul Crowley14c8c072018-09-18 13:30:21 -0700816 if (get_crypt_ftr_info(&fname, &starting_off)) {
817 SLOGE("Unable to get crypt_ftr_info\n");
818 return -1;
819 }
820 if (fname[0] != '/') {
821 SLOGE("Unexpected value for crypto key location\n");
822 return -1;
823 }
824 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
825 SLOGE("Cannot open footer file %s for get\n", fname);
826 return -1;
827 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800828
Paul Crowley14c8c072018-09-18 13:30:21 -0700829 /* Make sure it's 16 Kbytes in length */
830 fstat(fd, &statbuf);
831 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
832 SLOGE("footer file %s is not the expected size!\n", fname);
833 goto errout;
834 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700835
Paul Crowley14c8c072018-09-18 13:30:21 -0700836 /* Seek to the start of the crypt footer */
837 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
838 SLOGE("Cannot seek to real block device footer\n");
839 goto errout;
840 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700841
Paul Crowley14c8c072018-09-18 13:30:21 -0700842 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
843 SLOGE("Cannot read real block device footer\n");
844 goto errout;
845 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800846
Paul Crowley14c8c072018-09-18 13:30:21 -0700847 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
848 SLOGE("Bad magic for real block device %s\n", fname);
849 goto errout;
850 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800851
Paul Crowley14c8c072018-09-18 13:30:21 -0700852 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
853 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
854 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
855 goto errout;
856 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800857
Paul Crowley14c8c072018-09-18 13:30:21 -0700858 // We risk buffer overflows with oversized keys, so we just reject them.
859 // 0-sized keys are problematic (essentially by-passing encryption), and
860 // AES-CBC key wrapping only works for multiples of 16 bytes.
861 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
862 (crypt_ftr->keysize > MAX_KEY_LEN)) {
863 SLOGE(
864 "Invalid keysize (%u) for block device %s; Must be non-zero, "
865 "divisible by 16, and <= %d\n",
866 crypt_ftr->keysize, fname, MAX_KEY_LEN);
867 goto errout;
868 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800869
Paul Crowley14c8c072018-09-18 13:30:21 -0700870 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
871 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
872 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
873 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800874
Paul Crowley14c8c072018-09-18 13:30:21 -0700875 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
876 * copy on disk before returning.
877 */
878 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
879 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
880 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800881
Paul Crowley14c8c072018-09-18 13:30:21 -0700882 /* Success! */
883 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800884
885errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700886 close(fd);
887 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800888}
889
Paul Crowley14c8c072018-09-18 13:30:21 -0700890static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700891 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
892 crypt_ftr->persist_data_offset[1]) {
893 SLOGE("Crypt_ftr persist data regions overlap");
894 return -1;
895 }
896
897 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
898 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
899 return -1;
900 }
901
902 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700903 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700904 CRYPT_FOOTER_OFFSET) {
905 SLOGE("Persistent data extends past crypto footer");
906 return -1;
907 }
908
909 return 0;
910}
911
Paul Crowley14c8c072018-09-18 13:30:21 -0700912static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700913 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700914 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700915 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700916 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700917 int found = 0;
918 int fd;
919 int ret;
920 int i;
921
922 if (persist_data) {
923 /* Nothing to do, we've already loaded or initialized it */
924 return 0;
925 }
926
Ken Sumrall160b4d62013-04-22 12:15:39 -0700927 /* If not encrypted, just allocate an empty table and initialize it */
928 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700929 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800930 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700931 if (pdata) {
932 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
933 persist_data = pdata;
934 return 0;
935 }
936 return -1;
937 }
938
Paul Crowley14c8c072018-09-18 13:30:21 -0700939 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700940 return -1;
941 }
942
Paul Crowley14c8c072018-09-18 13:30:21 -0700943 if ((crypt_ftr.major_version < 1) ||
944 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700945 SLOGE("Crypt_ftr version doesn't support persistent data");
946 return -1;
947 }
948
949 if (get_crypt_ftr_info(&fname, NULL)) {
950 return -1;
951 }
952
953 ret = validate_persistent_data_storage(&crypt_ftr);
954 if (ret) {
955 return -1;
956 }
957
Paul Crowley14c8c072018-09-18 13:30:21 -0700958 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700959 if (fd < 0) {
960 SLOGE("Cannot open %s metadata file", fname);
961 return -1;
962 }
963
Wei Wang4375f1b2017-02-24 17:43:01 -0800964 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800965 if (pdata == NULL) {
966 SLOGE("Cannot allocate memory for persistent data");
967 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700968 }
969
970 for (i = 0; i < 2; i++) {
971 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
972 SLOGE("Cannot seek to read persistent data on %s", fname);
973 goto err2;
974 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700975 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700976 SLOGE("Error reading persistent data on iteration %d", i);
977 goto err2;
978 }
979 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
980 found = 1;
981 break;
982 }
983 }
984
985 if (!found) {
986 SLOGI("Could not find valid persistent data, creating");
987 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
988 }
989
990 /* Success */
991 persist_data = pdata;
992 close(fd);
993 return 0;
994
995err2:
996 free(pdata);
997
998err:
999 close(fd);
1000 return -1;
1001}
1002
Paul Crowley14c8c072018-09-18 13:30:21 -07001003static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001004 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001005 struct crypt_persist_data* pdata;
1006 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001007 off64_t write_offset;
1008 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001009 int fd;
1010 int ret;
1011
1012 if (persist_data == NULL) {
1013 SLOGE("No persistent data to save");
1014 return -1;
1015 }
1016
Paul Crowley14c8c072018-09-18 13:30:21 -07001017 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001018 return -1;
1019 }
1020
Paul Crowley14c8c072018-09-18 13:30:21 -07001021 if ((crypt_ftr.major_version < 1) ||
1022 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001023 SLOGE("Crypt_ftr version doesn't support persistent data");
1024 return -1;
1025 }
1026
1027 ret = validate_persistent_data_storage(&crypt_ftr);
1028 if (ret) {
1029 return -1;
1030 }
1031
1032 if (get_crypt_ftr_info(&fname, NULL)) {
1033 return -1;
1034 }
1035
Paul Crowley14c8c072018-09-18 13:30:21 -07001036 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001037 if (fd < 0) {
1038 SLOGE("Cannot open %s metadata file", fname);
1039 return -1;
1040 }
1041
Wei Wang4375f1b2017-02-24 17:43:01 -08001042 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001043 if (pdata == NULL) {
1044 SLOGE("Cannot allocate persistant data");
1045 goto err;
1046 }
1047
1048 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1049 SLOGE("Cannot seek to read persistent data on %s", fname);
1050 goto err2;
1051 }
1052
1053 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001054 SLOGE("Error reading persistent data before save");
1055 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001056 }
1057
1058 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1059 /* The first copy is the curent valid copy, so write to
1060 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001061 write_offset = crypt_ftr.persist_data_offset[1];
1062 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001063 } else {
1064 /* The second copy must be the valid copy, so write to
1065 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001066 write_offset = crypt_ftr.persist_data_offset[0];
1067 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001068 }
1069
1070 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001071 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001072 SLOGE("Cannot seek to write persistent data");
1073 goto err2;
1074 }
1075 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001076 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001077 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001078 SLOGE("Cannot seek to erase previous persistent data");
1079 goto err2;
1080 }
1081 fsync(fd);
1082 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001083 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001084 SLOGE("Cannot write to erase previous persistent data");
1085 goto err2;
1086 }
1087 fsync(fd);
1088 } else {
1089 SLOGE("Cannot write to save persistent data");
1090 goto err2;
1091 }
1092
1093 /* Success */
1094 free(pdata);
1095 close(fd);
1096 return 0;
1097
1098err2:
1099 free(pdata);
1100err:
1101 close(fd);
1102 return -1;
1103}
1104
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001105/* Convert a binary key of specified length into an ascii hex string equivalent,
1106 * without the leading 0x and with null termination
1107 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001108static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1109 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001110 unsigned int i, a;
1111 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001112
Paul Crowley14c8c072018-09-18 13:30:21 -07001113 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001114 /* For each byte, write out two ascii hex digits */
1115 nibble = (master_key[i] >> 4) & 0xf;
1116 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001118 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001119 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001120 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001122 /* Add the null termination */
1123 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001124}
1125
Paul Crowley14c8c072018-09-18 13:30:21 -07001126static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
1127 const unsigned char* master_key, const char* real_blk_name,
1128 const char* name, int fd, const char* extra_params) {
1129 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1130 struct dm_ioctl* io;
1131 struct dm_target_spec* tgt;
1132 char* crypt_params;
1133 // We need two ASCII characters to represent each byte, and need space for
1134 // the '\0' terminator.
1135 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1136 size_t buff_offset;
1137 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001138
Paul Crowley14c8c072018-09-18 13:30:21 -07001139 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001140
Paul Crowley14c8c072018-09-18 13:30:21 -07001141 /* Load the mapping table for this device */
1142 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001143
Paul Crowley14c8c072018-09-18 13:30:21 -07001144 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1145 io->target_count = 1;
1146 tgt->status = 0;
1147 tgt->sector_start = 0;
1148 tgt->length = crypt_ftr->fs_size;
Paul Crowley14c8c072018-09-18 13:30:21 -07001149 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
Paul Crowley14c8c072018-09-18 13:30:21 -07001150 buff_offset = crypt_params - buffer;
Eric Biggerse1a7e772019-01-25 12:11:25 -08001151 SLOGI(
1152 "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
1153 name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
1154 extra_params);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301155#ifdef CONFIG_HW_DISK_ENCRYPTION
1156 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1157 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1158 if (is_ice_enabled())
1159 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1160 else
1161 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1162 }
1163 else {
1164 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1165 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1166 }
1167 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1168 crypt_ftr->crypto_type_name, master_key_ascii,
1169 real_blk_name, extra_params);
1170
1171 SLOGI("target_type = %s", tgt->target_type);
1172 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1173#else
1174 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1175 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Paul Crowley14c8c072018-09-18 13:30:21 -07001176 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
1177 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301178#endif
1179
Paul Crowley14c8c072018-09-18 13:30:21 -07001180 crypt_params += strlen(crypt_params) + 1;
1181 crypt_params =
1182 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1183 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001184
Paul Crowley14c8c072018-09-18 13:30:21 -07001185 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1186 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
1187 break;
1188 }
1189 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001190 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001191
Paul Crowley14c8c072018-09-18 13:30:21 -07001192 if (i == TABLE_LOAD_RETRIES) {
1193 /* We failed to load the table, return an error */
1194 return -1;
1195 } else {
1196 return i + 1;
1197 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001198}
1199
Paul Crowley14c8c072018-09-18 13:30:21 -07001200static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001201 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001202 struct dm_ioctl* io;
1203 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001204
Paul Crowley14c8c072018-09-18 13:30:21 -07001205 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001206
1207 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1208
1209 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1210 return -1;
1211 }
1212
1213 /* Iterate over the returned versions, looking for name of "crypt".
1214 * When found, get and return the version.
1215 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001216 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001217 while (v->next) {
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301218#ifdef CONFIG_HW_DISK_ENCRYPTION
1219 if (!strcmp(v->name, "crypt") || !strcmp(v->name, "req-crypt")) {
1220#else
Paul Crowley14c8c072018-09-18 13:30:21 -07001221 if (!strcmp(v->name, "crypt")) {
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301222#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001223 /* We found the crypt driver, return the version, and get out */
1224 version[0] = v->version[0];
1225 version[1] = v->version[1];
1226 version[2] = v->version[2];
1227 return 0;
1228 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001229 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001230 }
1231
1232 return -1;
1233}
1234
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301235#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Crowley5afbc622017-11-27 09:42:17 -08001236static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1237 if (extra_params_vec.empty()) return "";
1238 std::string extra_params = std::to_string(extra_params_vec.size());
1239 for (const auto& p : extra_params_vec) {
1240 extra_params.append(" ");
1241 extra_params.append(p);
1242 }
1243 return extra_params;
1244}
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301245#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001246
Eric Biggersed45ec32019-01-25 10:47:55 -08001247/*
1248 * If the ro.crypto.fde_sector_size system property is set, append the
1249 * parameters to make dm-crypt use the specified crypto sector size and round
1250 * the crypto device size down to a crypto sector boundary.
1251 */
1252static int add_sector_size_param(std::vector<std::string>* extra_params_vec,
1253 struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001254 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001255 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001256
Eric Biggersed45ec32019-01-25 10:47:55 -08001257 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1258 unsigned int sector_size;
1259
1260 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1261 (sector_size & (sector_size - 1)) != 0) {
1262 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1263 DM_CRYPT_SECTOR_SIZE, value);
1264 return -1;
1265 }
1266
1267 std::string param = StringPrintf("sector_size:%u", sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001268 extra_params_vec->push_back(std::move(param));
1269
1270 // With this option, IVs will match the sector numbering, instead
1271 // of being hard-coded to being based on 512-byte sectors.
1272 extra_params_vec->emplace_back("iv_large_sectors");
Eric Biggersed45ec32019-01-25 10:47:55 -08001273
1274 // Round the crypto device size down to a crypto sector boundary.
1275 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001276 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001277 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001278}
1279
Paul Crowley5afbc622017-11-27 09:42:17 -08001280static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1281 const char* real_blk_name, char* crypto_blk_name, const char* name,
1282 uint32_t flags) {
1283 char buffer[DM_CRYPT_BUF_SIZE];
1284 struct dm_ioctl* io;
1285 unsigned int minor;
1286 int fd = 0;
1287 int err;
1288 int retval = -1;
1289 int version[3];
1290 int load_count;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301291#ifdef CONFIG_HW_DISK_ENCRYPTION
1292 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1293 char progress[PROPERTY_VALUE_MAX] = {0};
1294 const char *extra_params;
1295#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001296 std::vector<std::string> extra_params_vec;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301297#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001298
Paul Crowley5afbc622017-11-27 09:42:17 -08001299 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1300 SLOGE("Cannot open device-mapper\n");
1301 goto errout;
1302 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001303
Paul Crowley5afbc622017-11-27 09:42:17 -08001304 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001305
Paul Crowley5afbc622017-11-27 09:42:17 -08001306 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1307 err = ioctl(fd, DM_DEV_CREATE, io);
1308 if (err) {
1309 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1310 goto errout;
1311 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001312
Paul Crowley5afbc622017-11-27 09:42:17 -08001313 /* Get the device status, in particular, the name of it's device file */
1314 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1315 if (ioctl(fd, DM_DEV_STATUS, io)) {
1316 SLOGE("Cannot retrieve dm-crypt device status\n");
1317 goto errout;
1318 }
1319 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1320 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001321
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301322#ifdef CONFIG_HW_DISK_ENCRYPTION
1323 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1324 /* Set fde_enabled if either FDE completed or in-progress */
1325 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1326 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1327 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1328 if (is_ice_enabled()) {
1329 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1330 extra_params = "fde_enabled ice allow_encrypt_override";
1331 else
1332 extra_params = "fde_enabled ice";
1333 } else {
1334 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1335 extra_params = "fde_enabled allow_encrypt_override";
1336 else
1337 extra_params = "fde_enabled";
1338 }
1339 } else {
1340 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1341 extra_params = "fde_enabled allow_encrypt_override";
1342 else
1343 extra_params = "fde_enabled";
1344 }
1345 } else {
1346 extra_params = "";
1347 if (! get_dm_crypt_version(fd, name, version)) {
1348 /* Support for allow_discards was added in version 1.11.0 */
1349 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1350 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1351 extra_params = "2 allow_discards allow_encrypt_override";
1352 else
1353 extra_params = "1 allow_discards";
1354 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1355 }
1356 }
1357 }
1358 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1359 extra_params);
1360#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001361 if (!get_dm_crypt_version(fd, name, version)) {
1362 /* Support for allow_discards was added in version 1.11.0 */
1363 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1364 extra_params_vec.emplace_back("allow_discards");
1365 }
1366 }
1367 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1368 extra_params_vec.emplace_back("allow_encrypt_override");
1369 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001370 if (add_sector_size_param(&extra_params_vec, crypt_ftr)) {
1371 SLOGE("Error processing dm-crypt sector size param\n");
1372 goto errout;
1373 }
Paul Crowley5afbc622017-11-27 09:42:17 -08001374 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1375 extra_params_as_string(extra_params_vec).c_str());
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301376#endif
Paul Crowley5afbc622017-11-27 09:42:17 -08001377 if (load_count < 0) {
1378 SLOGE("Cannot load dm-crypt mapping table.\n");
1379 goto errout;
1380 } else if (load_count > 1) {
1381 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1382 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001383
Paul Crowley5afbc622017-11-27 09:42:17 -08001384 /* Resume this device to activate it */
1385 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001386
Paul Crowley5afbc622017-11-27 09:42:17 -08001387 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1388 SLOGE("Cannot resume the dm-crypt device\n");
1389 goto errout;
1390 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391
Paul Crowleycfe39722018-10-30 15:59:24 -07001392 /* Ensure the dm device has been created before returning. */
1393 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1394 // WaitForFile generates a suitable log message
1395 goto errout;
1396 }
1397
Paul Crowley5afbc622017-11-27 09:42:17 -08001398 /* We made it here with no errors. Woot! */
1399 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001400
1401errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001402 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001403
Paul Crowley14c8c072018-09-18 13:30:21 -07001404 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001405}
1406
Paul Crowley14c8c072018-09-18 13:30:21 -07001407static int delete_crypto_blk_dev(const char* name) {
1408 int fd;
1409 char buffer[DM_CRYPT_BUF_SIZE];
1410 struct dm_ioctl* io;
1411 int retval = -1;
Yue Hu9d6cc182018-12-17 17:09:55 +08001412 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413
Paul Crowley14c8c072018-09-18 13:30:21 -07001414 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1415 SLOGE("Cannot open device-mapper\n");
1416 goto errout;
1417 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001418
Paul Crowley14c8c072018-09-18 13:30:21 -07001419 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001420
Paul Crowley14c8c072018-09-18 13:30:21 -07001421 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Yue Hu9d6cc182018-12-17 17:09:55 +08001422 err = ioctl(fd, DM_DEV_REMOVE, io);
1423 if (err) {
1424 SLOGE("Cannot remove dm-crypt device %s: %s\n", name, strerror(errno));
Paul Crowley14c8c072018-09-18 13:30:21 -07001425 goto errout;
1426 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427
Paul Crowley14c8c072018-09-18 13:30:21 -07001428 /* We made it here with no errors. Woot! */
1429 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430
1431errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001432 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001433
Paul Crowley14c8c072018-09-18 13:30:21 -07001434 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001435}
1436
Paul Crowley14c8c072018-09-18 13:30:21 -07001437static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1438 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001439 SLOGI("Using pbkdf2 for cryptfs KDF");
1440
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001441 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001442 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1443 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001444}
1445
Paul Crowley14c8c072018-09-18 13:30:21 -07001446static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001447 SLOGI("Using scrypt for cryptfs KDF");
1448
Paul Crowley14c8c072018-09-18 13:30:21 -07001449 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001450
1451 int N = 1 << ftr->N_factor;
1452 int r = 1 << ftr->r_factor;
1453 int p = 1 << ftr->p_factor;
1454
1455 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001456 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001457 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001458
Paul Crowley14c8c072018-09-18 13:30:21 -07001459 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001460}
1461
Paul Crowley14c8c072018-09-18 13:30:21 -07001462static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1463 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001464 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1465
1466 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001467 size_t signature_size;
1468 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001469 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001470
1471 int N = 1 << ftr->N_factor;
1472 int r = 1 << ftr->r_factor;
1473 int p = 1 << ftr->p_factor;
1474
Paul Crowley14c8c072018-09-18 13:30:21 -07001475 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001476 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001477
1478 if (rc) {
1479 SLOGE("scrypt failed");
1480 return -1;
1481 }
1482
Paul Crowley14c8c072018-09-18 13:30:21 -07001483 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001484 SLOGE("Signing failed");
1485 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001486 }
1487
Paul Crowley14c8c072018-09-18 13:30:21 -07001488 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1489 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001490 free(signature);
1491
1492 if (rc) {
1493 SLOGE("scrypt failed");
1494 return -1;
1495 }
1496
1497 return 0;
1498}
1499
Paul Crowley14c8c072018-09-18 13:30:21 -07001500static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1501 const unsigned char* decrypted_master_key,
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301502 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1503 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001504 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001505 EVP_CIPHER_CTX e_ctx;
1506 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001507 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001508
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001509 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001510 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001511
1512 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001513 case KDF_SCRYPT_KEYMASTER:
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301514 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001515 SLOGE("keymaster_create_key failed");
1516 return -1;
1517 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001518
Paul Crowley14c8c072018-09-18 13:30:21 -07001519 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1520 SLOGE("scrypt failed");
1521 return -1;
1522 }
1523 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001524
Paul Crowley14c8c072018-09-18 13:30:21 -07001525 case KDF_SCRYPT:
1526 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1527 SLOGE("scrypt failed");
1528 return -1;
1529 }
1530 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001531
Paul Crowley14c8c072018-09-18 13:30:21 -07001532 default:
1533 SLOGE("Invalid kdf_type");
1534 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001535 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001536
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001537 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001538 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001539 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1540 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001541 SLOGE("EVP_EncryptInit failed\n");
1542 return -1;
1543 }
1544 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001545
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001546 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001547 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1548 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001549 SLOGE("EVP_EncryptUpdate failed\n");
1550 return -1;
1551 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001552 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001553 SLOGE("EVP_EncryptFinal failed\n");
1554 return -1;
1555 }
1556
Greg Kaiser59ad0182018-02-16 13:01:36 -08001557 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001558 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1559 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001560 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001561
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001562 /* Store the scrypt of the intermediate key, so we can validate if it's a
1563 password error or mount error when things go wrong.
1564 Note there's no need to check for errors, since if this is incorrect, we
1565 simply won't wipe userdata, which is the correct default behavior
1566 */
1567 int N = 1 << crypt_ftr->N_factor;
1568 int r = 1 << crypt_ftr->r_factor;
1569 int p = 1 << crypt_ftr->p_factor;
1570
Paul Crowley14c8c072018-09-18 13:30:21 -07001571 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1572 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001573 sizeof(crypt_ftr->scrypted_intermediate_key));
1574
1575 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001576 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001577 }
1578
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001579 EVP_CIPHER_CTX_cleanup(&e_ctx);
1580
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001581 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001582}
1583
Paul Crowley14c8c072018-09-18 13:30:21 -07001584static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1585 const unsigned char* encrypted_master_key, size_t keysize,
1586 unsigned char* decrypted_master_key, kdf_func kdf,
1587 void* kdf_params, unsigned char** intermediate_key,
1588 size_t* intermediate_key_size) {
1589 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1590 EVP_CIPHER_CTX d_ctx;
1591 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001592
Paul Crowley14c8c072018-09-18 13:30:21 -07001593 /* Turn the password into an intermediate key and IV that can decrypt the
1594 master key */
1595 if (kdf(passwd, salt, ikey, kdf_params)) {
1596 SLOGE("kdf failed");
1597 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001598 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001599
Paul Crowley14c8c072018-09-18 13:30:21 -07001600 /* Initialize the decryption engine */
1601 EVP_CIPHER_CTX_init(&d_ctx);
1602 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1603 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1604 return -1;
1605 }
1606 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1607 /* Decrypt the master key */
1608 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1609 keysize)) {
1610 return -1;
1611 }
1612 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1613 return -1;
1614 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001615
Paul Crowley14c8c072018-09-18 13:30:21 -07001616 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1617 return -1;
1618 }
1619
1620 /* Copy intermediate key if needed by params */
1621 if (intermediate_key && intermediate_key_size) {
1622 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1623 if (*intermediate_key) {
1624 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1625 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1626 }
1627 }
1628
1629 EVP_CIPHER_CTX_cleanup(&d_ctx);
1630
1631 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001632}
1633
Paul Crowley14c8c072018-09-18 13:30:21 -07001634static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001635 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001636 *kdf = scrypt_keymaster;
1637 *kdf_params = ftr;
1638 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001639 *kdf = scrypt;
1640 *kdf_params = ftr;
1641 } else {
1642 *kdf = pbkdf2;
1643 *kdf_params = NULL;
1644 }
1645}
1646
Paul Crowley14c8c072018-09-18 13:30:21 -07001647static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1648 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1649 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001650 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001651 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001652 int ret;
1653
1654 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001655 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1656 decrypted_master_key, kdf, kdf_params, intermediate_key,
1657 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001658 if (ret != 0) {
1659 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001660 }
1661
1662 return ret;
1663}
1664
Paul Crowley14c8c072018-09-18 13:30:21 -07001665static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1666 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001667 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001668
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001669 /* Get some random bits for a key and salt */
1670 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1671 return -1;
1672 }
1673 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1674 return -1;
1675 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001676
1677 /* Now encrypt it with the password */
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301678 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001679}
1680
Paul Crowley14c8c072018-09-18 13:30:21 -07001681int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001682 int i, err, rc;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301683#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001684
1685 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001686 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001687 if (umount(mountpoint) == 0) {
1688 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001689 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001690
1691 if (errno == EINVAL) {
1692 /* EINVAL is returned if the directory is not a mountpoint,
1693 * i.e. there is no filesystem mounted there. So just get out.
1694 */
1695 break;
1696 }
1697
1698 err = errno;
1699
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301700 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001701 if (kill) {
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301702 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001703 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001704 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301705 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001706 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001707 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001708 }
1709 }
1710
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301711 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001712 }
1713
1714 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001715 SLOGD("unmounting %s succeeded\n", mountpoint);
1716 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001718 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1719 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1720 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001721 }
1722
1723 return rc;
1724}
1725
Paul Crowley14c8c072018-09-18 13:30:21 -07001726static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001727 // NOTE: post_fs_data results in init calling back around to vold, so all
1728 // callers to this method must be async
1729
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001730 /* Do the prep of the /data filesystem */
1731 property_set("vold.post_fs_data_done", "0");
1732 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001733 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001734
Ken Sumrallc5872692013-05-14 15:26:31 -07001735 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001736 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001737 /* We timed out to prep /data in time. Continue wait. */
1738 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001739 }
Wei Wang42e38102017-06-07 10:46:12 -07001740 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001741}
1742
Paul Crowley14c8c072018-09-18 13:30:21 -07001743static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001744 // Mark the footer as bad
1745 struct crypt_mnt_ftr crypt_ftr;
1746 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1747 SLOGE("Failed to get crypto footer - panic");
1748 return;
1749 }
1750
1751 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1752 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1753 SLOGE("Failed to set crypto footer - panic");
1754 return;
1755 }
1756}
1757
Paul Crowley14c8c072018-09-18 13:30:21 -07001758static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001759 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001760 SLOGE("Failed to mount tmpfs on data - panic");
1761 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001762 }
1763
1764 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1765 SLOGE("Failed to trigger post fs data - panic");
1766 return;
1767 }
1768
1769 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1770 SLOGE("Failed to trigger restart min framework - panic");
1771 return;
1772 }
1773}
1774
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001775/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001776static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001777 char crypto_blkdev[MAXPATHLEN];
AnilKumar Chimata47386642018-02-11 17:11:24 +05301778#ifdef CONFIG_HW_DISK_ENCRYPTION
1779 char blkdev[MAXPATHLEN];
1780#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001781 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001782 static int restart_successful = 0;
1783
1784 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001785 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001786 SLOGE("Encrypted filesystem not validated, aborting");
1787 return -1;
1788 }
1789
1790 if (restart_successful) {
1791 SLOGE("System already restarted with encrypted disk, aborting");
1792 return -1;
1793 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001794
Paul Lawrencef4faa572014-01-29 13:31:03 -08001795 if (restart_main) {
1796 /* Here is where we shut down the framework. The init scripts
Martijn Coenenf629b002019-04-24 10:41:11 +02001797 * start all services in one of these classes: core, early_hal, hal,
1798 * main and late_start. To get to the minimal UI for PIN entry, we
1799 * need to start core, early_hal, hal and main. When we want to
1800 * shutdown the framework again, we need to stop most of the services in
1801 * these classes, but only those services that were started after
1802 * /data was mounted. This excludes critical services like vold and
1803 * ueventd, which need to keep running. We could possible stop
1804 * even fewer services, but because we want services to pick up APEX
1805 * libraries from the real /data, restarting is better, as it makes
1806 * these devices consistent with FBE devices and lets them use the
1807 * most recent code.
1808 *
1809 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001810 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenf629b002019-04-24 10:41:11 +02001811 * We then restart the class core, hal, main, and also the class
1812 * late_start.
1813 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001814 * At the moment, I've only put a few things in late_start that I know
1815 * are not needed to bring up the framework, and that also cause problems
1816 * with unmounting the tmpfs /data, but I hope to add add more services
1817 * to the late_start class as we optimize this to decrease the delay
1818 * till the user is asked for the password to the filesystem.
1819 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001820
Martijn Coenenf629b002019-04-24 10:41:11 +02001821 /* The init files are setup to stop the right set of services when
1822 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001823 */
Martijn Coenenf629b002019-04-24 10:41:11 +02001824 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001825 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001826
Paul Lawrencef4faa572014-01-29 13:31:03 -08001827 /* Ugh, shutting down the framework is not synchronous, so until it
1828 * can be fixed, this horrible hack will wait a moment for it all to
1829 * shut down before proceeding. Without it, some devices cannot
1830 * restart the graphics services.
1831 */
1832 sleep(2);
1833 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001834
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001835 /* Now that the framework is shutdown, we should be able to umount()
1836 * the tmpfs filesystem, and mount the real one.
1837 */
1838
AnilKumar Chimata47386642018-02-11 17:11:24 +05301839#if defined(CONFIG_HW_DISK_ENCRYPTION)
1840#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1841 if (is_ice_enabled()) {
1842 fs_mgr_get_crypt_info(fstab_default, 0, blkdev, sizeof(blkdev));
1843 if (set_ice_param(START_ENCDEC)) {
1844 SLOGE("Failed to set ICE data");
1845 return -1;
1846 }
1847 }
1848#else
1849 property_get("ro.crypto.fs_crypto_blkdev", blkdev, "");
1850 if (strlen(blkdev) == 0) {
1851 SLOGE("fs_crypto_blkdev not set\n");
1852 return -1;
1853 }
1854 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1855#endif
1856#else
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001857 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1858 if (strlen(crypto_blkdev) == 0) {
1859 SLOGE("fs_crypto_blkdev not set\n");
1860 return -1;
1861 }
1862
Paul Crowley14c8c072018-09-18 13:30:21 -07001863 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimata47386642018-02-11 17:11:24 +05301864#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001865 /* If ro.crypto.readonly is set to 1, mount the decrypted
1866 * filesystem readonly. This is used when /data is mounted by
1867 * recovery mode.
1868 */
1869 char ro_prop[PROPERTY_VALUE_MAX];
1870 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001871 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001872 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1873 if (entry != nullptr) {
1874 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001875 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001876 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001877
Ken Sumralle5032c42012-04-01 23:58:44 -07001878 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001879 int retries = RETRY_MOUNT_ATTEMPTS;
1880 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001881
1882 /*
1883 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1884 * partitions in the fsck domain.
1885 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001886 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001887 SLOGE("Failed to setexeccon");
1888 return -1;
1889 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001890 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimata47386642018-02-11 17:11:24 +05301891#ifdef CONFIG_HW_DISK_ENCRYPTION
1892 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, blkdev, 0,
1893 needs_cp)) != 0) {
1894#else
Tom Cherry4c5bde22019-01-29 14:34:01 -08001895 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001896 needs_cp)) != 0) {
AnilKumar Chimata47386642018-02-11 17:11:24 +05301897#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001898 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1899 /* TODO: invoke something similar to
1900 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1901 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimata47386642018-02-11 17:11:24 +05301902#ifdef CONFIG_HW_DISK_ENCRYPTION
1903 SLOGI("Failed to mount %s because it is busy - waiting", blkdev);
1904#else
Paul Crowley14c8c072018-09-18 13:30:21 -07001905 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
AnilKumar Chimata47386642018-02-11 17:11:24 +05301906#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001907 if (--retries) {
1908 sleep(RETRY_MOUNT_DELAY_SECONDS);
1909 } else {
1910 /* Let's hope that a reboot clears away whatever is keeping
1911 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001912 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001913 }
1914 } else {
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301915#ifdef CONFIG_HW_DISK_ENCRYPTION
1916 if (--retries) {
1917 sleep(RETRY_MOUNT_DELAY_SECONDS);
1918 } else {
1919 SLOGE("Failed to mount decrypted data");
1920 cryptfs_set_corrupt();
1921 cryptfs_trigger_restart_min_framework();
1922 SLOGI("Started framework to offer wipe");
1923 return -1;
1924 }
1925#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001926 SLOGE("Failed to mount decrypted data");
1927 cryptfs_set_corrupt();
1928 cryptfs_trigger_restart_min_framework();
1929 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001930 if (setexeccon(NULL)) {
1931 SLOGE("Failed to setexeccon");
1932 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001933 return -1;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301934#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001935 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001936 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001937 if (setexeccon(NULL)) {
1938 SLOGE("Failed to setexeccon");
1939 return -1;
1940 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001941
Ken Sumralle5032c42012-04-01 23:58:44 -07001942 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001943 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001944 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001945
1946 /* startup service classes main and late_start */
1947 property_set("vold.decrypt", "trigger_restart_framework");
1948 SLOGD("Just triggered restart_framework\n");
1949
1950 /* Give it a few moments to get started */
1951 sleep(1);
AnilKumar Chimata47386642018-02-11 17:11:24 +05301952#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001953 }
AnilKumar Chimata47386642018-02-11 17:11:24 +05301954#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001955
Ken Sumrall0cc16632011-01-18 20:32:26 -08001956 if (rc == 0) {
1957 restart_successful = 1;
1958 }
1959
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001960 return rc;
1961}
1962
Paul Crowley14c8c072018-09-18 13:30:21 -07001963int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001964 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001965 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001966 SLOGE("cryptfs_restart not valid for file encryption:");
1967 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001968 }
1969
Paul Lawrencef4faa572014-01-29 13:31:03 -08001970 /* Call internal implementation forcing a restart of main service group */
1971 return cryptfs_restart_internal(1);
1972}
1973
Paul Crowley14c8c072018-09-18 13:30:21 -07001974static int do_crypto_complete(const char* mount_point) {
1975 struct crypt_mnt_ftr crypt_ftr;
1976 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001977
Paul Crowley14c8c072018-09-18 13:30:21 -07001978 property_get("ro.crypto.state", encrypted_state, "");
1979 if (strcmp(encrypted_state, "encrypted")) {
1980 SLOGE("not running with encryption, aborting");
1981 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001982 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001983
Paul Crowley14c8c072018-09-18 13:30:21 -07001984 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001985 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001986 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1987 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001988
Paul Crowley14c8c072018-09-18 13:30:21 -07001989 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001990 std::string key_loc;
1991 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001992
Paul Crowley14c8c072018-09-18 13:30:21 -07001993 /*
1994 * Only report this error if key_loc is a file and it exists.
1995 * If the device was never encrypted, and /data is not mountable for
1996 * some reason, returning 1 should prevent the UI from presenting the
1997 * a "enter password" screen, or worse, a "press button to wipe the
1998 * device" screen.
1999 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002000 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002001 SLOGE("master key file does not exist, aborting");
2002 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2003 } else {
2004 SLOGE("Error getting crypt footer and key\n");
2005 return CRYPTO_COMPLETE_BAD_METADATA;
2006 }
2007 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002008
Paul Crowley14c8c072018-09-18 13:30:21 -07002009 // Test for possible error flags
2010 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2011 SLOGE("Encryption process is partway completed\n");
2012 return CRYPTO_COMPLETE_PARTIAL;
2013 }
2014
2015 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2016 SLOGE("Encryption process was interrupted but cannot continue\n");
2017 return CRYPTO_COMPLETE_INCONSISTENT;
2018 }
2019
2020 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
2021 SLOGE("Encryption is successful but data is corrupt\n");
2022 return CRYPTO_COMPLETE_CORRUPT;
2023 }
2024
2025 /* We passed the test! We shall diminish, and return to the west */
2026 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002027}
2028
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302029#ifdef CONFIG_HW_DISK_ENCRYPTION
2030static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
2031 const char *passwd, const char *mount_point, const char *label)
2032{
2033 /* Allocate enough space for a 256 bit key, but we may use less */
2034 unsigned char decrypted_master_key[32];
2035 char crypto_blkdev[MAXPATHLEN];
2036 char real_blkdev[MAXPATHLEN];
2037 unsigned int orig_failed_decrypt_count;
2038 int rc = 0;
2039
2040 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2041 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
2042
2043 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
2044
2045 int key_index = 0;
2046 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
2047 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
2048 if (key_index < 0) {
2049 rc = crypt_ftr->failed_decrypt_count;
2050 goto errout;
2051 }
2052 else {
2053 if (is_ice_enabled()) {
AnilKumar Chimata47386642018-02-11 17:11:24 +05302054#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302055 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
2056 real_blkdev, crypto_blkdev, label, 0)) {
2057 SLOGE("Error creating decrypted block device");
2058 rc = -1;
2059 goto errout;
2060 }
AnilKumar Chimata47386642018-02-11 17:11:24 +05302061#endif
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302062 } else {
2063 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
2064 real_blkdev, crypto_blkdev, label, 0)) {
2065 SLOGE("Error creating decrypted block device");
2066 rc = -1;
2067 goto errout;
2068 }
2069 }
2070 }
2071 }
2072
2073 if (rc == 0) {
2074 crypt_ftr->failed_decrypt_count = 0;
2075 if (orig_failed_decrypt_count != 0) {
2076 put_crypt_ftr_and_key(crypt_ftr);
2077 }
2078
2079 /* Save the name of the crypto block device
2080 * so we can mount it when restarting the framework. */
AnilKumar Chimata47386642018-02-11 17:11:24 +05302081#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2082 if (!is_ice_enabled())
2083#endif
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302084 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2085 master_key_saved = 1;
2086 }
2087
2088 errout:
2089 return rc;
2090}
2091#endif
2092
Paul Crowley14c8c072018-09-18 13:30:21 -07002093static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2094 const char* mount_point, const char* label) {
2095 unsigned char decrypted_master_key[MAX_KEY_LEN];
2096 char crypto_blkdev[MAXPATHLEN];
Tom Cherry4c5bde22019-01-29 14:34:01 -08002097 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07002098 char tmp_mount_point[64];
2099 unsigned int orig_failed_decrypt_count;
2100 int rc;
2101 int use_keymaster = 0;
2102 int upgrade = 0;
2103 unsigned char* intermediate_key = 0;
2104 size_t intermediate_key_size = 0;
2105 int N = 1 << crypt_ftr->N_factor;
2106 int r = 1 << crypt_ftr->r_factor;
2107 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002108
Paul Crowley14c8c072018-09-18 13:30:21 -07002109 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2110 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08002111
Paul Crowley14c8c072018-09-18 13:30:21 -07002112 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2113 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2114 &intermediate_key_size)) {
2115 SLOGE("Failed to decrypt master key\n");
2116 rc = -1;
2117 goto errout;
2118 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002119 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002120
Tom Cherry4c5bde22019-01-29 14:34:01 -08002121 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08002122
Paul Crowley14c8c072018-09-18 13:30:21 -07002123 // Create crypto block device - all (non fatal) code paths
2124 // need it
Tom Cherry4c5bde22019-01-29 14:34:01 -08002125 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
2126 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002127 SLOGE("Error creating decrypted block device\n");
2128 rc = -1;
2129 goto errout;
2130 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002131
Paul Crowley14c8c072018-09-18 13:30:21 -07002132 /* Work out if the problem is the password or the data */
2133 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002134
Paul Crowley14c8c072018-09-18 13:30:21 -07002135 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2136 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2137 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002138
Paul Crowley14c8c072018-09-18 13:30:21 -07002139 // Does the key match the crypto footer?
2140 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2141 sizeof(scrypted_intermediate_key)) == 0) {
2142 SLOGI("Password matches");
2143 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002144 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002145 /* Try mounting the file system anyway, just in case the problem's with
2146 * the footer, not the key. */
2147 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2148 mkdir(tmp_mount_point, 0755);
Tom Cherry4c5bde22019-01-29 14:34:01 -08002149 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002150 SLOGE("Error temp mounting decrypted block device\n");
2151 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002152
Paul Crowley14c8c072018-09-18 13:30:21 -07002153 rc = ++crypt_ftr->failed_decrypt_count;
2154 put_crypt_ftr_and_key(crypt_ftr);
2155 } else {
2156 /* Success! */
2157 SLOGI("Password did not match but decrypted drive mounted - continue");
2158 umount(tmp_mount_point);
2159 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002160 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002161 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002162
Paul Crowley14c8c072018-09-18 13:30:21 -07002163 if (rc == 0) {
2164 crypt_ftr->failed_decrypt_count = 0;
2165 if (orig_failed_decrypt_count != 0) {
2166 put_crypt_ftr_and_key(crypt_ftr);
2167 }
2168
2169 /* Save the name of the crypto block device
2170 * so we can mount it when restarting the framework. */
2171 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2172
2173 /* Also save a the master key so we can reencrypted the key
2174 * the key when we want to change the password on it. */
2175 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2176 saved_mount_point = strdup(mount_point);
2177 master_key_saved = 1;
2178 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2179 rc = 0;
2180
2181 // Upgrade if we're not using the latest KDF.
2182 use_keymaster = keymaster_check_compatibility();
2183 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2184 // Don't allow downgrade
2185 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2186 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2187 upgrade = 1;
2188 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2189 crypt_ftr->kdf_type = KDF_SCRYPT;
2190 upgrade = 1;
2191 }
2192
2193 if (upgrade) {
2194 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302195 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002196 if (!rc) {
2197 rc = put_crypt_ftr_and_key(crypt_ftr);
2198 }
2199 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2200
2201 // Do not fail even if upgrade failed - machine is bootable
2202 // Note that if this code is ever hit, there is a *serious* problem
2203 // since KDFs should never fail. You *must* fix the kdf before
2204 // proceeding!
2205 if (rc) {
2206 SLOGW(
2207 "Upgrade failed with error %d,"
2208 " but continuing with previous state",
2209 rc);
2210 rc = 0;
2211 }
2212 }
2213 }
2214
2215errout:
2216 if (intermediate_key) {
2217 memset(intermediate_key, 0, intermediate_key_size);
2218 free(intermediate_key);
2219 }
2220 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002221}
2222
Ken Sumrall29d8da82011-05-18 17:20:07 -07002223/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002224 * Called by vold when it's asked to mount an encrypted external
2225 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002226 * as any metadata is been stored in a separate, small partition. We
2227 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07002228 *
2229 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002230 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002231int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
2232 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002233 uint64_t nr_sec = 0;
2234 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002235 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002236 return -1;
2237 }
2238
Jeff Sharkey9c484982015-03-31 10:35:33 -07002239 struct crypt_mnt_ftr ext_crypt_ftr;
2240 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2241 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002242 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07002243 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002244 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002245 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002246 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002247 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2248 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002249
Paul Crowley385cb8c2018-03-29 13:27:23 -07002250 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07002251}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002252
Jeff Sharkey9c484982015-03-31 10:35:33 -07002253/*
2254 * Called by vold when it's asked to unmount an encrypted external
2255 * storage volume.
2256 */
2257int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002258 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002259}
2260
Paul Crowley14c8c072018-09-18 13:30:21 -07002261int cryptfs_crypto_complete(void) {
2262 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002263}
2264
Paul Crowley14c8c072018-09-18 13:30:21 -07002265int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002266 char encrypted_state[PROPERTY_VALUE_MAX];
2267 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002268 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2269 SLOGE(
2270 "encrypted fs already validated or not running with encryption,"
2271 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002272 return -1;
2273 }
2274
2275 if (get_crypt_ftr_and_key(crypt_ftr)) {
2276 SLOGE("Error getting crypt footer and key");
2277 return -1;
2278 }
2279
2280 return 0;
2281}
2282
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302283#ifdef CONFIG_HW_DISK_ENCRYPTION
2284int cryptfs_check_passwd_hw(const char* passwd)
2285{
2286 struct crypt_mnt_ftr crypt_ftr;
2287 int rc;
2288 unsigned char master_key[KEY_LEN_BYTES];
2289
2290 /* get key */
2291 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2292 SLOGE("Error getting crypt footer and key");
2293 return -1;
2294 }
2295
2296 /*
2297 * in case of manual encryption (from GUI), the encryption is done with
2298 * default password
2299 */
2300 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2301 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2302 * which was created with actual password before reboot.
2303 */
2304 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2305 if (rc) {
2306 SLOGE("password doesn't match");
2307 rc = ++crypt_ftr.failed_decrypt_count;
2308 put_crypt_ftr_and_key(&crypt_ftr);
2309 return rc;
2310 }
2311
2312 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2313 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2314
2315 if (rc) {
2316 SLOGE("Default password did not match on reboot encryption");
2317 return rc;
2318 }
2319
2320 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2321 put_crypt_ftr_and_key(&crypt_ftr);
2322 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2323 if (rc) {
2324 SLOGE("Could not change password on reboot encryption");
2325 return rc;
2326 }
2327 } else
2328 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2329 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2330
2331 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2332 cryptfs_clear_password();
2333 password = strdup(passwd);
2334 struct timespec now;
2335 clock_gettime(CLOCK_BOOTTIME, &now);
2336 password_expiry_time = now.tv_sec + password_max_age_seconds;
2337 }
2338
2339 return rc;
2340}
2341#endif
2342
Paul Crowley14c8c072018-09-18 13:30:21 -07002343int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002344 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002345 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002346 SLOGE("cryptfs_check_passwd not valid for file encryption");
2347 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002348 }
2349
Paul Lawrencef4faa572014-01-29 13:31:03 -08002350 struct crypt_mnt_ftr crypt_ftr;
2351 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002352
Paul Lawrencef4faa572014-01-29 13:31:03 -08002353 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002354 if (rc) {
2355 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002356 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002357 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002358
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302359#ifdef CONFIG_HW_DISK_ENCRYPTION
2360 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2361 return cryptfs_check_passwd_hw(passwd);
2362#endif
2363
Paul Crowley14c8c072018-09-18 13:30:21 -07002364 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002365 if (rc) {
2366 SLOGE("Password did not match");
2367 return rc;
2368 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002369
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002370 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2371 // Here we have a default actual password but a real password
2372 // we must test against the scrypted value
2373 // First, we must delete the crypto block device that
2374 // test_mount_encrypted_fs leaves behind as a side effect
2375 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002376 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2377 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002378 if (rc) {
2379 SLOGE("Default password did not match on reboot encryption");
2380 return rc;
2381 }
2382
2383 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2384 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302385 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002386 if (rc) {
2387 SLOGE("Could not change password on reboot encryption");
2388 return rc;
2389 }
2390 }
2391
2392 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002393 cryptfs_clear_password();
2394 password = strdup(passwd);
2395 struct timespec now;
2396 clock_gettime(CLOCK_BOOTTIME, &now);
2397 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002398 }
2399
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002400 return rc;
2401}
2402
Paul Crowley14c8c072018-09-18 13:30:21 -07002403int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002404 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002405 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002406 char encrypted_state[PROPERTY_VALUE_MAX];
2407 int rc;
2408
2409 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002410 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002411 SLOGE("device not encrypted, aborting");
2412 return -2;
2413 }
2414
2415 if (!master_key_saved) {
2416 SLOGE("encrypted fs not yet mounted, aborting");
2417 return -1;
2418 }
2419
2420 if (!saved_mount_point) {
2421 SLOGE("encrypted fs failed to save mount point, aborting");
2422 return -1;
2423 }
2424
Ken Sumrall160b4d62013-04-22 12:15:39 -07002425 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002426 SLOGE("Error getting crypt footer and key\n");
2427 return -1;
2428 }
2429
2430 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2431 /* If the device has no password, then just say the password is valid */
2432 rc = 0;
2433 } else {
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302434#ifdef CONFIG_HW_DISK_ENCRYPTION
2435 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2436 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2437 rc = 0;
2438 else
2439 rc = -1;
2440 } else {
2441 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2442 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2443 /* They match, the password is correct */
2444 rc = 0;
2445 } else {
2446 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2447 sleep(1);
2448 rc = 1;
2449 }
2450 }
2451#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002452 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002453 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2454 /* They match, the password is correct */
2455 rc = 0;
2456 } else {
2457 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2458 sleep(1);
2459 rc = 1;
2460 }
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302461#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002462 }
2463
2464 return rc;
2465}
2466
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002467/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002468 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002469 * Presumably, at a minimum, the caller will update the
2470 * filesystem size and crypto_type_name after calling this function.
2471 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002472static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002473 off64_t off;
2474
2475 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002476 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002477 ftr->major_version = CURRENT_MAJOR_VERSION;
2478 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002479 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002480 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002481
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002482 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002483 case 1:
2484 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2485 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002486
Paul Crowley14c8c072018-09-18 13:30:21 -07002487 case 0:
2488 ftr->kdf_type = KDF_SCRYPT;
2489 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002490
Paul Crowley14c8c072018-09-18 13:30:21 -07002491 default:
2492 SLOGE("keymaster_check_compatibility failed");
2493 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002494 }
2495
Kenny Rootc4c70f12013-06-14 12:11:38 -07002496 get_device_scrypt_params(ftr);
2497
Ken Sumrall160b4d62013-04-22 12:15:39 -07002498 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2499 if (get_crypt_ftr_info(NULL, &off) == 0) {
2500 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002501 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002502 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002503
2504 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002505}
2506
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002507#define FRAMEWORK_BOOT_WAIT 60
2508
Paul Crowley14c8c072018-09-18 13:30:21 -07002509static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2510 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002511 if (fd == -1) {
2512 SLOGE("Error opening file %s", filename);
2513 return -1;
2514 }
2515
2516 char block[CRYPT_INPLACE_BUFSIZE];
2517 memset(block, 0, sizeof(block));
2518 if (unix_read(fd, block, sizeof(block)) < 0) {
2519 SLOGE("Error reading file %s", filename);
2520 close(fd);
2521 return -1;
2522 }
2523
2524 close(fd);
2525
2526 SHA256_CTX c;
2527 SHA256_Init(&c);
2528 SHA256_Update(&c, block, sizeof(block));
2529 SHA256_Final(buf, &c);
2530
2531 return 0;
2532}
2533
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002534static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2535 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002536 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002537 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002538
Paul Lawrence87999172014-02-20 12:21:31 -08002539 /* The size of the userdata partition, and add in the vold volumes below */
2540 tot_encryption_size = crypt_ftr->fs_size;
2541
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002542 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002543 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002544
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002545 if (rc == ENABLE_INPLACE_ERR_DEV) {
2546 /* Hack for b/17898962 */
2547 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2548 cryptfs_reboot(RebootType::reboot);
2549 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002550
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002551 if (!rc) {
2552 crypt_ftr->encrypted_upto = cur_encryption_done;
2553 }
Paul Lawrence87999172014-02-20 12:21:31 -08002554
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002555 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2556 /* The inplace routine never actually sets the progress to 100% due
2557 * to the round down nature of integer division, so set it here */
2558 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002559 }
2560
2561 return rc;
2562}
2563
Paul Crowleyb64933a2017-10-31 08:25:55 -07002564static int vold_unmountAll(void) {
2565 VolumeManager* vm = VolumeManager::Instance();
2566 return vm->unmountAll();
2567}
2568
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002569int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002570 char crypto_blkdev[MAXPATHLEN];
2571 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002572 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002573 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002574 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002575 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002576 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002577 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002578 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002579 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002580 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002581 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002582 bool onlyCreateHeader = false;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302583#ifdef CONFIG_HW_DISK_ENCRYPTION
2584 unsigned char newpw[32];
2585 int key_index = 0;
2586#endif
2587 int index = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002588
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002589 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002590 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2591 /* An encryption was underway and was interrupted */
2592 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2593 crypt_ftr.encrypted_upto = 0;
2594 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002595
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002596 /* At this point, we are in an inconsistent state. Until we successfully
2597 complete encryption, a reboot will leave us broken. So mark the
2598 encryption failed in case that happens.
2599 On successfully completing encryption, remove this flag */
2600 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002601
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002602 put_crypt_ftr_and_key(&crypt_ftr);
2603 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2604 if (!check_ftr_sha(&crypt_ftr)) {
2605 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2606 put_crypt_ftr_and_key(&crypt_ftr);
2607 goto error_unencrypted;
2608 }
2609
2610 /* Doing a reboot-encryption*/
2611 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2612 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2613 rebootEncryption = true;
2614 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002615 } else {
2616 // We don't want to accidentally reference invalid data.
2617 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002618 }
2619
2620 property_get("ro.crypto.state", encrypted_state, "");
2621 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2622 SLOGE("Device is already running encrypted, aborting");
2623 goto error_unencrypted;
2624 }
2625
Tom Cherry4c5bde22019-01-29 14:34:01 -08002626 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002627
Ken Sumrall3ed82362011-01-28 23:31:16 -08002628 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002629 uint64_t nr_sec;
2630 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002631 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002632 goto error_unencrypted;
2633 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002634
2635 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002636 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002637 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002638 fs_size_sec = get_fs_size(real_blkdev.c_str());
2639 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002640
Paul Lawrence87999172014-02-20 12:21:31 -08002641 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002642
2643 if (fs_size_sec > max_fs_size_sec) {
2644 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2645 goto error_unencrypted;
2646 }
2647 }
2648
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002649 /* Get a wakelock as this may take a while, and we don't want the
2650 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2651 * wants to keep the screen on, it can grab a full wakelock.
2652 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002653 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002654 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2655
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002656 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002657 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002658 */
2659 property_set("vold.decrypt", "trigger_shutdown_framework");
2660 SLOGD("Just asked init to shut down class main\n");
2661
Jeff Sharkey9c484982015-03-31 10:35:33 -07002662 /* Ask vold to unmount all devices that it manages */
2663 if (vold_unmountAll()) {
2664 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002665 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002666
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002667 /* no_ui means we are being called from init, not settings.
2668 Now we always reboot from settings, so !no_ui means reboot
2669 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002670 if (!no_ui) {
2671 /* Try fallback, which is to reboot and try there */
2672 onlyCreateHeader = true;
2673 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2674 if (breadcrumb == 0) {
2675 SLOGE("Failed to create breadcrumb file");
2676 goto error_shutting_down;
2677 }
2678 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002679 }
2680
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002681 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002682 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002683 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002684 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2685 goto error_shutting_down;
2686 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002687
Tom Cherry4c5bde22019-01-29 14:34:01 -08002688 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002689 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002690 } else {
2691 crypt_ftr.fs_size = nr_sec;
2692 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002693 /* At this point, we are in an inconsistent state. Until we successfully
2694 complete encryption, a reboot will leave us broken. So mark the
2695 encryption failed in case that happens.
2696 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002697 if (onlyCreateHeader) {
2698 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2699 } else {
2700 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2701 }
Paul Lawrence87999172014-02-20 12:21:31 -08002702 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302703#ifdef CONFIG_HW_DISK_ENCRYPTION
2704 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2705 MAX_CRYPTO_TYPE_NAME_LEN);
2706#else
Paul Crowley14c8c072018-09-18 13:30:21 -07002707 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2708 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302709#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002710
Paul Lawrence87999172014-02-20 12:21:31 -08002711 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002712 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2713 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002714 SLOGE("Cannot create encrypted master key\n");
2715 goto error_shutting_down;
2716 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002717
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002718 /* Replace scrypted intermediate key if we are preparing for a reboot */
2719 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002720 unsigned char fake_master_key[MAX_KEY_LEN];
2721 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002722 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002723 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302724 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002725 }
2726
Paul Lawrence87999172014-02-20 12:21:31 -08002727 /* Write the key to the end of the partition */
2728 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002729
Paul Lawrence87999172014-02-20 12:21:31 -08002730 /* If any persistent data has been remembered, save it.
2731 * If none, create a valid empty table and save that.
2732 */
2733 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002734 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2735 if (pdata) {
2736 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2737 persist_data = pdata;
2738 }
Paul Lawrence87999172014-02-20 12:21:31 -08002739 }
2740 if (persist_data) {
2741 save_persistent_data();
2742 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002743 }
2744
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302745 /* When encryption triggered from settings, encryption starts after reboot.
2746 So set the encryption key when the actual encryption starts.
2747 */
2748#ifdef CONFIG_HW_DISK_ENCRYPTION
2749 if (previously_encrypted_upto == 0) {
2750 if (!rebootEncryption)
2751 clear_hw_device_encryption_key();
2752
2753 if (get_keymaster_hw_fde_passwd(
2754 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2755 newpw, crypt_ftr.salt, &crypt_ftr))
2756 key_index = set_hw_device_encryption_key(
2757 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2758 (char*)crypt_ftr.crypto_type_name);
2759 else
2760 key_index = set_hw_device_encryption_key((const char*)newpw,
2761 (char*) crypt_ftr.crypto_type_name);
2762 if (key_index < 0)
2763 goto error_shutting_down;
2764
2765 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2766 put_crypt_ftr_and_key(&crypt_ftr);
2767 }
2768#endif
2769
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002770 if (onlyCreateHeader) {
2771 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002772 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302773 } else {
2774 /* Do extra work for a better UX when doing the long inplace encryption */
2775 /* Now that /data is unmounted, we need to mount a tmpfs
2776 * /data, set a property saying we're doing inplace encryption,
2777 * and restart the framework.
2778 */
2779 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2780 goto error_shutting_down;
2781 }
2782 /* Tells the framework that inplace encryption is starting */
2783 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002784
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302785 /* restart the framework. */
2786 /* Create necessary paths on /data */
2787 prep_data_fs();
2788
2789 /* Ugh, shutting down the framework is not synchronous, so until it
2790 * can be fixed, this horrible hack will wait a moment for it all to
2791 * shut down before proceeding. Without it, some devices cannot
2792 * restart the graphics services.
2793 */
2794 sleep(2);
2795
Ajay Dudani87701e22014-09-17 21:02:52 -07002796 /* startup service classes main and late_start */
2797 property_set("vold.decrypt", "trigger_restart_min_framework");
2798 SLOGD("Just triggered restart_min_framework\n");
2799
2800 /* OK, the framework is restarted and will soon be showing a
2801 * progress bar. Time to setup an encrypted mapping, and
2802 * either write a new filesystem, or encrypt in place updating
2803 * the progress bar as we work.
2804 */
2805 }
2806
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002807 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302808#ifdef CONFIG_HW_DISK_ENCRYPTION
2809 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimata47386642018-02-11 17:11:24 +05302810#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2811 strlcpy(crypto_blkdev, real_blkdev, sizeof(crypto_blkdev));
2812#else
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302813 create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev.c_str(), crypto_blkdev,
2814 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata47386642018-02-11 17:11:24 +05302815#endif
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302816 else
2817 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
2818 CRYPTO_BLOCK_DEVICE, 0);
2819#else
Tom Cherry4c5bde22019-01-29 14:34:01 -08002820 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002821 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302822#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002823
Paul Lawrence87999172014-02-20 12:21:31 -08002824 /* If we are continuing, check checksums match */
2825 rc = 0;
2826 if (previously_encrypted_upto) {
2827 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimata47386642018-02-11 17:11:24 +05302828#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2829 if (set_ice_param(START_ENCDEC)) {
2830 SLOGE("Failed to set ICE data");
2831 goto error_shutting_down;
2832 }
2833#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002834 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002835
Paul Crowley14c8c072018-09-18 13:30:21 -07002836 if (!rc &&
2837 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002838 SLOGE("Checksums do not match - trigger wipe");
2839 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002840 }
2841 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002842
AnilKumar Chimata47386642018-02-11 17:11:24 +05302843#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2844 if (set_ice_param(START_ENC)) {
2845 SLOGE("Failed to set ICE data");
2846 goto error_shutting_down;
2847 }
2848#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002849 if (!rc) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002850 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002851 previously_encrypted_upto);
2852 }
2853
AnilKumar Chimata47386642018-02-11 17:11:24 +05302854#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2855 if (set_ice_param(START_ENCDEC)) {
2856 SLOGE("Failed to set ICE data");
2857 goto error_shutting_down;
2858 }
2859#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002860 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002861 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002862 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002863 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002864 SLOGE("Error calculating checksum for continuing encryption");
2865 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002866 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002867 }
2868
2869 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimata47386642018-02-11 17:11:24 +05302870#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2871 if (!is_ice_enabled())
2872 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2873#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002874 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimata47386642018-02-11 17:11:24 +05302875#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002876
Paul Crowley14c8c072018-09-18 13:30:21 -07002877 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002878 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002879 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002880
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002881 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002882 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2883 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002884 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002885 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002886
Paul Lawrence6bfed202014-07-28 12:47:22 -07002887 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002888
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002889 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2890 char value[PROPERTY_VALUE_MAX];
2891 property_get("ro.crypto.state", value, "");
2892 if (!strcmp(value, "")) {
2893 /* default encryption - continue first boot sequence */
2894 property_set("ro.crypto.state", "encrypted");
2895 property_set("ro.crypto.type", "block");
2896 release_wake_lock(lockid);
2897 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2898 // Bring up cryptkeeper that will check the password and set it
2899 property_set("vold.decrypt", "trigger_shutdown_framework");
2900 sleep(2);
2901 property_set("vold.encrypt_progress", "");
2902 cryptfs_trigger_restart_min_framework();
2903 } else {
2904 cryptfs_check_passwd(DEFAULT_PASSWORD);
2905 cryptfs_restart_internal(1);
2906 }
2907 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002908 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002909 sleep(2); /* Give the UI a chance to show 100% progress */
2910 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002911 }
Paul Lawrence87999172014-02-20 12:21:31 -08002912 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002913 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002914 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002915 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002916 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002917 char value[PROPERTY_VALUE_MAX];
2918
Ken Sumrall319369a2012-06-27 16:30:18 -07002919 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002920 if (!strcmp(value, "1")) {
2921 /* wipe data if encryption failed */
2922 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002923 std::string err;
2924 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002925 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002926 if (!write_bootloader_message(options, &err)) {
2927 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002928 }
Josh Gaofec44372017-08-28 13:22:55 -07002929 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002930 } else {
2931 /* set property to trigger dialog */
2932 property_set("vold.encrypt_progress", "error_partially_encrypted");
2933 release_wake_lock(lockid);
2934 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002935 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002936 }
2937
Ken Sumrall3ed82362011-01-28 23:31:16 -08002938 /* hrm, the encrypt step claims success, but the reboot failed.
2939 * This should not happen.
2940 * Set the property and return. Hope the framework can deal with it.
2941 */
2942 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002943 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002944 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002945
2946error_unencrypted:
2947 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002948 if (lockid[0]) {
2949 release_wake_lock(lockid);
2950 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002951 return -1;
2952
2953error_shutting_down:
2954 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2955 * but the framework is stopped and not restarted to show the error, so it's up to
2956 * vold to restart the system.
2957 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002958 SLOGE(
2959 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2960 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002961 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002962
2963 /* shouldn't get here */
2964 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002965 if (lockid[0]) {
2966 release_wake_lock(lockid);
2967 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002968 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002969}
2970
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002971int cryptfs_enable(int type, const char* passwd, int no_ui) {
2972 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002973}
2974
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002975int cryptfs_enable_default(int no_ui) {
2976 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002977}
2978
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302979int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002980 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002981 SLOGE("cryptfs_changepw not valid for file encryption");
2982 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002983 }
2984
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002985 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002986 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002987
2988 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002989 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002990 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002991 return -1;
2992 }
2993
Paul Lawrencef4faa572014-01-29 13:31:03 -08002994 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2995 SLOGE("Invalid crypt_type %d", crypt_type);
2996 return -1;
2997 }
2998
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002999 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003000 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003001 SLOGE("Error getting crypt footer and key");
3002 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003003 }
3004
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05303005#ifdef CONFIG_HW_DISK_ENCRYPTION
3006 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
3007 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
3008 else {
3009 crypt_ftr.crypt_type = crypt_type;
3010
3011 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
3012 DEFAULT_PASSWORD : newpw,
3013 crypt_ftr.salt,
3014 saved_master_key,
3015 crypt_ftr.master_key,
3016 &crypt_ftr, false);
3017 if (rc) {
3018 SLOGE("Encrypt master key failed: %d", rc);
3019 return -1;
3020 }
3021 /* save the key */
3022 put_crypt_ftr_and_key(&crypt_ftr);
3023
3024 return 0;
3025 }
3026#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08003027 crypt_ftr.crypt_type = crypt_type;
3028
Paul Crowley14c8c072018-09-18 13:30:21 -07003029 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05303030 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
3031 false);
JP Abgrall933216c2015-02-11 13:44:32 -08003032 if (rc) {
3033 SLOGE("Encrypt master key failed: %d", rc);
3034 return -1;
3035 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003036 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003037 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003038
3039 return 0;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05303040#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003041}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003042
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05303043#ifdef CONFIG_HW_DISK_ENCRYPTION
3044int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
3045{
3046 struct crypt_mnt_ftr crypt_ftr;
3047 int rc;
3048 int previous_type;
3049
3050 /* get key */
3051 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3052 SLOGE("Error getting crypt footer and key");
3053 return -1;
3054 }
3055
3056 previous_type = crypt_ftr.crypt_type;
3057 int rc1;
3058 unsigned char tmp_curpw[32] = {0};
3059 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3060 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3061 crypt_ftr.salt, &crypt_ftr);
3062
3063 crypt_ftr.crypt_type = crypt_type;
3064
3065 int ret, rc2;
3066 unsigned char tmp_newpw[32] = {0};
3067
3068 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3069 DEFAULT_PASSWORD : newpw , tmp_newpw,
3070 crypt_ftr.salt, &crypt_ftr);
3071
3072 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3073 ret = update_hw_device_encryption_key(
3074 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3075 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3076 (char*)crypt_ftr.crypto_type_name);
3077 if (ret) {
3078 SLOGE("Error updating device encryption hardware key ret %d", ret);
3079 return -1;
3080 } else {
3081 SLOGI("Encryption hardware key updated");
3082 }
3083 }
3084
3085 /* save the key */
3086 put_crypt_ftr_and_key(&crypt_ftr);
3087 return 0;
3088}
3089#endif
3090
Rubin Xu85c01f92014-10-13 12:49:54 +01003091static unsigned int persist_get_max_entries(int encrypted) {
3092 struct crypt_mnt_ftr crypt_ftr;
3093 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003094
3095 /* If encrypted, use the values from the crypt_ftr, otherwise
3096 * use the values for the current spec.
3097 */
3098 if (encrypted) {
3099 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01003100 /* Something is wrong, assume no space for entries */
3101 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003102 }
3103 dsize = crypt_ftr.persist_data_size;
3104 } else {
3105 dsize = CRYPT_PERSIST_DATA_SIZE;
3106 }
3107
Rubin Xuf83cc612018-10-09 16:13:38 +01003108 if (dsize > sizeof(struct crypt_persist_data)) {
3109 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3110 } else {
3111 return 0;
3112 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003113}
3114
Paul Crowley14c8c072018-09-18 13:30:21 -07003115static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003116 unsigned int i;
3117
3118 if (persist_data == NULL) {
3119 return -1;
3120 }
3121 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3122 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3123 /* We found it! */
3124 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3125 return 0;
3126 }
3127 }
3128
3129 return -1;
3130}
3131
Paul Crowley14c8c072018-09-18 13:30:21 -07003132static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003133 unsigned int i;
3134 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003135 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003136
3137 if (persist_data == NULL) {
3138 return -1;
3139 }
3140
Rubin Xu85c01f92014-10-13 12:49:54 +01003141 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003142
3143 num = persist_data->persist_valid_entries;
3144
3145 for (i = 0; i < num; i++) {
3146 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3147 /* We found an existing entry, update it! */
3148 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3149 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3150 return 0;
3151 }
3152 }
3153
3154 /* We didn't find it, add it to the end, if there is room */
3155 if (persist_data->persist_valid_entries < max_persistent_entries) {
3156 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3157 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3158 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3159 persist_data->persist_valid_entries++;
3160 return 0;
3161 }
3162
3163 return -1;
3164}
3165
Rubin Xu85c01f92014-10-13 12:49:54 +01003166/**
3167 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3168 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3169 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003170int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003171 std::string key_ = key;
3172 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003173
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003174 std::string parsed_field;
3175 unsigned parsed_index;
3176
3177 std::string::size_type split = key_.find_last_of('_');
3178 if (split == std::string::npos) {
3179 parsed_field = key_;
3180 parsed_index = 0;
3181 } else {
3182 parsed_field = key_.substr(0, split);
3183 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003184 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003185
3186 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003187}
3188
3189/*
3190 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3191 * remaining entries starting from index will be deleted.
3192 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3193 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3194 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3195 *
3196 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003197static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003198 unsigned int i;
3199 unsigned int j;
3200 unsigned int num;
3201
3202 if (persist_data == NULL) {
3203 return PERSIST_DEL_KEY_ERROR_OTHER;
3204 }
3205
3206 num = persist_data->persist_valid_entries;
3207
Paul Crowley14c8c072018-09-18 13:30:21 -07003208 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003209 // Filter out to-be-deleted entries in place.
3210 for (i = 0; i < num; i++) {
3211 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3212 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3213 j++;
3214 }
3215 }
3216
3217 if (j < num) {
3218 persist_data->persist_valid_entries = j;
3219 // Zeroise the remaining entries
3220 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3221 return PERSIST_DEL_KEY_OK;
3222 } else {
3223 // Did not find an entry matching the given fieldname
3224 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3225 }
3226}
3227
Paul Crowley14c8c072018-09-18 13:30:21 -07003228static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003229 unsigned int i;
3230 unsigned int count;
3231
3232 if (persist_data == NULL) {
3233 return -1;
3234 }
3235
3236 count = 0;
3237 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3238 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3239 count++;
3240 }
3241 }
3242
3243 return count;
3244}
3245
Ken Sumrall160b4d62013-04-22 12:15:39 -07003246/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003247int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003248 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003249 SLOGE("Cannot get field when file encrypted");
3250 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003251 }
3252
Ken Sumrall160b4d62013-04-22 12:15:39 -07003253 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003254 /* CRYPTO_GETFIELD_OK is success,
3255 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3256 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3257 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003258 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003259 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3260 int i;
3261 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003262
3263 if (persist_data == NULL) {
3264 load_persistent_data();
3265 if (persist_data == NULL) {
3266 SLOGE("Getfield error, cannot load persistent data");
3267 goto out;
3268 }
3269 }
3270
Rubin Xu85c01f92014-10-13 12:49:54 +01003271 // Read value from persistent entries. If the original value is split into multiple entries,
3272 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003273 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003274 // 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 -07003275 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003276 // value too small
3277 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3278 goto out;
3279 }
3280 rc = CRYPTO_GETFIELD_OK;
3281
3282 for (i = 1; /* break explicitly */; i++) {
3283 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003284 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003285 // If the fieldname is very long, we stop as soon as it begins to overflow the
3286 // maximum field length. At this point we have in fact fully read out the original
3287 // value because cryptfs_setfield would not allow fields with longer names to be
3288 // written in the first place.
3289 break;
3290 }
3291 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003292 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3293 // value too small.
3294 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3295 goto out;
3296 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003297 } else {
3298 // Exhaust all entries.
3299 break;
3300 }
3301 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003302 } else {
3303 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003304 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003305 }
3306
3307out:
3308 return rc;
3309}
3310
3311/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003312int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003313 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003314 SLOGE("Cannot set field when file encrypted");
3315 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003316 }
3317
Ken Sumrall160b4d62013-04-22 12:15:39 -07003318 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003319 /* 0 is success, negative values are error */
3320 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003321 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003322 unsigned int field_id;
3323 char temp_field[PROPERTY_KEY_MAX];
3324 unsigned int num_entries;
3325 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003326
3327 if (persist_data == NULL) {
3328 load_persistent_data();
3329 if (persist_data == NULL) {
3330 SLOGE("Setfield error, cannot load persistent data");
3331 goto out;
3332 }
3333 }
3334
3335 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003336 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003337 encrypted = 1;
3338 }
3339
Rubin Xu85c01f92014-10-13 12:49:54 +01003340 // Compute the number of entries required to store value, each entry can store up to
3341 // (PROPERTY_VALUE_MAX - 1) chars
3342 if (strlen(value) == 0) {
3343 // Empty value also needs one entry to store.
3344 num_entries = 1;
3345 } else {
3346 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3347 }
3348
3349 max_keylen = strlen(fieldname);
3350 if (num_entries > 1) {
3351 // Need an extra "_%d" suffix.
3352 max_keylen += 1 + log10(num_entries);
3353 }
3354 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3355 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003356 goto out;
3357 }
3358
Rubin Xu85c01f92014-10-13 12:49:54 +01003359 // Make sure we have enough space to write the new value
3360 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3361 persist_get_max_entries(encrypted)) {
3362 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3363 goto out;
3364 }
3365
3366 // Now that we know persist_data has enough space for value, let's delete the old field first
3367 // to make up space.
3368 persist_del_keys(fieldname, 0);
3369
3370 if (persist_set_key(fieldname, value, encrypted)) {
3371 // fail to set key, should not happen as we have already checked the available space
3372 SLOGE("persist_set_key() error during setfield()");
3373 goto out;
3374 }
3375
3376 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003377 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003378
3379 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3380 // fail to set key, should not happen as we have already checked the available space.
3381 SLOGE("persist_set_key() error during setfield()");
3382 goto out;
3383 }
3384 }
3385
Ken Sumrall160b4d62013-04-22 12:15:39 -07003386 /* If we are running encrypted, save the persistent data now */
3387 if (encrypted) {
3388 if (save_persistent_data()) {
3389 SLOGE("Setfield error, cannot save persistent data");
3390 goto out;
3391 }
3392 }
3393
Rubin Xu85c01f92014-10-13 12:49:54 +01003394 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003395
3396out:
3397 return rc;
3398}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003399
3400/* Checks userdata. Attempt to mount the volume if default-
3401 * encrypted.
3402 * On success trigger next init phase and return 0.
3403 * Currently do not handle failure - see TODO below.
3404 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003405int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003406 int crypt_type = cryptfs_get_password_type();
3407 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3408 SLOGE("Bad crypt type - error");
3409 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003410 SLOGD(
3411 "Password is not default - "
3412 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003413 property_set("vold.decrypt", "trigger_restart_min_framework");
3414 return 0;
3415 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3416 SLOGD("Password is default - restarting filesystem");
3417 cryptfs_restart_internal(0);
3418 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003419 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003420 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003421 }
3422
Paul Lawrence6bfed202014-07-28 12:47:22 -07003423 /** Corrupt. Allow us to boot into framework, which will detect bad
3424 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003425 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003426 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003427 return 0;
3428}
3429
3430/* Returns type of the password, default, pattern, pin or password.
3431 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003432int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003433 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003434 SLOGE("cryptfs_get_password_type not valid for file encryption");
3435 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003436 }
3437
Paul Lawrencef4faa572014-01-29 13:31:03 -08003438 struct crypt_mnt_ftr crypt_ftr;
3439
3440 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3441 SLOGE("Error getting crypt footer and key\n");
3442 return -1;
3443 }
3444
Paul Lawrence6bfed202014-07-28 12:47:22 -07003445 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3446 return -1;
3447 }
3448
Paul Lawrencef4faa572014-01-29 13:31:03 -08003449 return crypt_ftr.crypt_type;
3450}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003451
Paul Crowley14c8c072018-09-18 13:30:21 -07003452const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003453 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003454 SLOGE("cryptfs_get_password not valid for file encryption");
3455 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003456 }
3457
Paul Lawrence399317e2014-03-10 13:20:50 -07003458 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003459 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003460 if (now.tv_sec < password_expiry_time) {
3461 return password;
3462 } else {
3463 cryptfs_clear_password();
3464 return 0;
3465 }
3466}
3467
Paul Crowley14c8c072018-09-18 13:30:21 -07003468void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003469 if (password) {
3470 size_t len = strlen(password);
3471 memset(password, 0, len);
3472 free(password);
3473 password = 0;
3474 password_expiry_time = 0;
3475 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003476}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003477
Paul Crowley14c8c072018-09-18 13:30:21 -07003478int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08003479 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
3480 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07003481}
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05303482
3483int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3484{
3485 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3486 SLOGE("Failed to initialize crypt_ftr");
3487 return -1;
3488 }
3489
3490 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3491 crypt_ftr->salt, crypt_ftr)) {
3492 SLOGE("Cannot create encrypted master key\n");
3493 return -1;
3494 }
3495
3496 //crypt_ftr->keysize = key_length / 8;
3497 return 0;
3498}
3499
3500int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3501 unsigned char* master_key)
3502{
3503 int rc;
3504
3505 unsigned char* intermediate_key = 0;
3506 size_t intermediate_key_size = 0;
3507
3508 if (password == 0 || *password == 0) {
3509 password = DEFAULT_PASSWORD;
3510 }
3511
3512 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3513 &intermediate_key_size);
3514
3515 if (rc) {
3516 SLOGE("Can't calculate intermediate key");
3517 return rc;
3518 }
3519
3520 int N = 1 << ftr->N_factor;
3521 int r = 1 << ftr->r_factor;
3522 int p = 1 << ftr->p_factor;
3523
3524 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3525
3526 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3527 ftr->salt, sizeof(ftr->salt), N, r, p,
3528 scrypted_intermediate_key,
3529 sizeof(scrypted_intermediate_key));
3530
3531 free(intermediate_key);
3532
3533 if (rc) {
3534 SLOGE("Can't scrypt intermediate key");
3535 return rc;
3536 }
3537
3538 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3539 intermediate_key_size);
3540}