blob: 6352de554e630557168c3b5ea7fd443d0e144186 [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
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Paul Crowley3b71fc52017-10-09 10:55:21 -070041#include <ext4_utils/ext4_crypt.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070042#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Paul Crowleyc5e3a522018-10-30 15:59:24 -070057#include "Utils.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070058#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070059#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000060#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000061#include "f2fs_sparseblock.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070062#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080063#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000064#include "Keymaster.h"
Eric Biggers668c23f2019-01-25 10:47:55 -080065#include "android-base/parseint.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080066#include "android-base/properties.h"
Greg Kaiser8c63b572018-12-11 12:40:51 -080067#include "android-base/stringprintf.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070068#include <bootloader_message/bootloader_message.h>
AnilKumar Chimata35850082018-05-11 00:25:09 +053069#ifdef CONFIG_HW_DISK_ENCRYPTION
70#include <cryptfs_hw.h>
71#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080072extern "C" {
73#include <crypto_scrypt.h>
74}
Mark Salyzyn3e971272014-01-21 13:27:04 -080075
Eric Biggers668c23f2019-01-25 10:47:55 -080076using android::base::ParseUint;
Greg Kaiser8c63b572018-12-11 12:40:51 -080077using android::base::StringPrintf;
Paul Crowleyc5e3a522018-10-30 15:59:24 -070078using namespace std::chrono_literals;
79
Mark Salyzyn5eecc442014-02-12 14:16:14 -080080#define UNUSED __attribute__((unused))
81
Ken Sumrall8f869aa2010-12-03 03:47:09 -080082#define DM_CRYPT_BUF_SIZE 4096
83
Jason parks70a4b3f2011-01-28 10:10:47 -060084#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080085
86constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
87constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
88constexpr size_t INTERMEDIATE_BUF_SIZE =
89 (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
90
91// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
92static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN,
93 "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060094
Ken Sumrall29d8da82011-05-18 17:20:07 -070095#define KEY_IN_FOOTER "footer"
96
AnilKumar Chimata35850082018-05-11 00:25:09 +053097#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -070098#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080099
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800100#define CRYPTO_BLOCK_DEVICE "userdata"
101
102#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
103
Ken Sumrall29d8da82011-05-18 17:20:07 -0700104#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700105#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700106
Ken Sumralle919efe2012-09-29 17:07:41 -0700107#define TABLE_LOAD_RETRIES 10
108
Shawn Willden47ba10d2014-09-03 17:07:06 -0600109#define RSA_KEY_SIZE 2048
110#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
111#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600112#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimata35850082018-05-11 00:25:09 +0530113#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700114
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700115#define RETRY_MOUNT_ATTEMPTS 10
116#define RETRY_MOUNT_DELAY_SECONDS 1
117
Paul Crowley5afbc622017-11-27 09:42:17 -0800118#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
119
Paul Crowley73473332017-11-21 15:43:51 -0800120static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
121
Greg Kaiser59ad0182018-02-16 13:01:36 -0800122static unsigned char saved_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700123static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600124static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700125static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800126
AnilKumar Chimata35850082018-05-11 00:25:09 +0530127static int previous_type;
128
129#ifdef CONFIG_HW_DISK_ENCRYPTION
130static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
131 unsigned char *ikey, void *params);
132static void convert_key_to_hex_ascii(const unsigned char *master_key,
133 unsigned int keysize, char *master_key_ascii);
134static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
135static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
136 const char *passwd, const char *mount_point, const char *label);
137int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
138 const char *newpw);
139int cryptfs_check_passwd_hw(char *passwd);
140int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
141 unsigned char* master_key);
142
143static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
144 unsigned int keysize, char *master_key_ascii)
145{
146 unsigned int i, a;
147 unsigned char nibble;
148
149 for (i = 0, a = 0; i < keysize; i++, a += 2) {
150 /* For each byte, write out two ascii hex digits */
151 nibble = (master_key[i] >> 4) & 0xf;
152 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
153
154 nibble = master_key[i] & 0xf;
155 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
156 }
157
158 /* Add the null termination */
159 master_key_ascii[a] = '\0';
160}
161
162static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
163 unsigned char* salt,
164 const struct crypt_mnt_ftr *ftr)
165{
166 /* if newpw updated, return 0
167 * if newpw not updated return -1
168 */
169 int rc = -1;
170
171 if (should_use_keymaster()) {
172 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
173 SLOGE("scrypt failed");
174 } else {
175 rc = 0;
176 }
177 }
178
179 return rc;
180}
181
182static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
183{
184 unsigned char newpw[32] = {0};
185 int key_index;
186 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
187 key_index = set_hw_device_encryption_key(passwd,
188 (char*) crypt_ftr->crypto_type_name);
189 else
190 key_index = set_hw_device_encryption_key((const char*)newpw,
191 (char*) crypt_ftr->crypto_type_name);
192 return key_index;
193}
194
195static int verify_and_update_hw_fde_passwd(const char *passwd,
196 struct crypt_mnt_ftr* crypt_ftr)
197{
198 char* new_passwd = NULL;
199 unsigned char newpw[32] = {0};
200 int key_index = -1;
201 int passwd_updated = -1;
202 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
203
204 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
205 if (key_index < 0) {
206 ++crypt_ftr->failed_decrypt_count;
207
208 if (ascii_passwd_updated) {
209 SLOGI("Ascii password was updated");
210 } else {
211 /* Code in else part would execute only once:
212 * When device is upgraded from L->M release.
213 * Once upgraded, code flow should never come here.
214 * L release passed actual password in hex, so try with hex
215 * Each nible of passwd was encoded as a byte, so allocate memory
216 * twice of password len plus one more byte for null termination
217 */
218 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
219 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
220 if (new_passwd == NULL) {
221 SLOGE("System out of memory. Password verification incomplete");
222 goto out;
223 }
224 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
225 } else {
226 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
227 if (new_passwd == NULL) {
228 SLOGE("System out of memory. Password verification incomplete");
229 goto out;
230 }
231 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
232 strlen(passwd), new_passwd);
233 }
234 key_index = set_hw_device_encryption_key((const char*)new_passwd,
235 (char*) crypt_ftr->crypto_type_name);
236 if (key_index >=0) {
237 crypt_ftr->failed_decrypt_count = 0;
238 SLOGI("Hex password verified...will try to update with Ascii value");
239 /* Before updating password, tie that with keymaster to tie with ROT */
240
241 if (get_keymaster_hw_fde_passwd(passwd, newpw,
242 crypt_ftr->salt, crypt_ftr)) {
243 passwd_updated = update_hw_device_encryption_key(new_passwd,
244 passwd, (char*)crypt_ftr->crypto_type_name);
245 } else {
246 passwd_updated = update_hw_device_encryption_key(new_passwd,
247 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
248 }
249
250 if (passwd_updated >= 0) {
251 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
252 SLOGI("Ascii password recorded and updated");
253 } else {
254 SLOGI("Passwd verified, could not update...Will try next time");
255 }
256 } else {
257 ++crypt_ftr->failed_decrypt_count;
258 }
259 free(new_passwd);
260 }
261 } else {
262 if (!ascii_passwd_updated)
263 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
264 }
265out:
266 // update footer before leaving
267 put_crypt_ftr_and_key(crypt_ftr);
268 return key_index;
269}
270#endif
271
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700272/* Should we use keymaster? */
273static int keymaster_check_compatibility()
274{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000275 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700276}
277
278/* Create a new keymaster key and store it in this footer */
279static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
280{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800281 if (ftr->keymaster_blob_size) {
282 SLOGI("Already have key");
283 return 0;
284 }
285
Janis Danisevskis015ec302017-01-31 11:31:08 +0000286 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
287 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
288 &ftr->keymaster_blob_size);
289 if (rc) {
290 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800291 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000292 ftr->keymaster_blob_size = 0;
293 }
294 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700295 return -1;
296 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000297 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700298}
299
Shawn Willdene17a9c42014-09-08 13:04:08 -0600300/* This signs the given object using the keymaster key. */
301static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600302 const unsigned char *object,
303 const size_t object_size,
304 unsigned char **signature,
305 size_t *signature_size)
306{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600307 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600308 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600309 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600310
Shawn Willdene17a9c42014-09-08 13:04:08 -0600311 // To sign a message with RSA, the message must satisfy two
312 // constraints:
313 //
314 // 1. The message, when interpreted as a big-endian numeric value, must
315 // be strictly less than the public modulus of the RSA key. Note
316 // that because the most significant bit of the public modulus is
317 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
318 // key), an n-bit message with most significant bit 0 always
319 // satisfies this requirement.
320 //
321 // 2. The message must have the same length in bits as the public
322 // modulus of the RSA key. This requirement isn't mathematically
323 // necessary, but is necessary to ensure consistency in
324 // implementations.
325 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600326 case KDF_SCRYPT_KEYMASTER:
327 // This ensures the most significant byte of the signed message
328 // is zero. We could have zero-padded to the left instead, but
329 // this approach is slightly more robust against changes in
330 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600331 // so) because we really should be using a proper deterministic
332 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800333 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600334 SLOGI("Signing safely-padded object");
335 break;
336 default:
337 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000338 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600339 }
Paul Crowley73473332017-11-21 15:43:51 -0800340 for (;;) {
341 auto result = keymaster_sign_object_for_cryptfs_scrypt(
342 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
343 to_sign_size, signature, signature_size);
344 switch (result) {
345 case KeymasterSignResult::ok:
346 return 0;
347 case KeymasterSignResult::upgrade:
348 break;
349 default:
350 return -1;
351 }
352 SLOGD("Upgrading key");
353 if (keymaster_upgrade_key_for_cryptfs_scrypt(
354 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
355 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
356 &ftr->keymaster_blob_size) != 0) {
357 SLOGE("Failed to upgrade key");
358 return -1;
359 }
360 if (put_crypt_ftr_and_key(ftr) != 0) {
361 SLOGE("Failed to write upgraded key to disk");
362 }
363 SLOGD("Key upgraded successfully");
364 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600365}
366
Paul Lawrence399317e2014-03-10 13:20:50 -0700367/* Store password when userdata is successfully decrypted and mounted.
368 * Cleared by cryptfs_clear_password
369 *
370 * To avoid a double prompt at boot, we need to store the CryptKeeper
371 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
372 * Since the entire framework is torn down and rebuilt after encryption,
373 * we have to use a daemon or similar to store the password. Since vold
374 * is secured against IPC except from system processes, it seems a reasonable
375 * place to store this.
376 *
377 * password should be cleared once it has been used.
378 *
379 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800380 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700381static char* password = 0;
382static int password_expiry_time = 0;
383static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800384
Josh Gaofec44372017-08-28 13:22:55 -0700385enum class RebootType {reboot, recovery, shutdown};
386static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700387{
Josh Gaofec44372017-08-28 13:22:55 -0700388 switch (rt) {
389 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800390 property_set(ANDROID_RB_PROPERTY, "reboot");
391 break;
392
Josh Gaofec44372017-08-28 13:22:55 -0700393 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800394 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
395 break;
396
Josh Gaofec44372017-08-28 13:22:55 -0700397 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800398 property_set(ANDROID_RB_PROPERTY, "shutdown");
399 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700400 }
Paul Lawrence87999172014-02-20 12:21:31 -0800401
Ken Sumralladfba362013-06-04 16:37:52 -0700402 sleep(20);
403
404 /* Shouldn't get here, reboot should happen before sleep times out */
405 return;
406}
407
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800408static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
409{
410 memset(io, 0, dataSize);
411 io->data_size = dataSize;
412 io->data_start = sizeof(struct dm_ioctl);
413 io->version[0] = 4;
414 io->version[1] = 0;
415 io->version[2] = 0;
416 io->flags = flags;
417 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100418 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800419 }
420}
421
Greg Kaiser38723f22018-02-16 13:35:35 -0800422namespace {
423
424struct CryptoType;
425
426// Use to get the CryptoType in use on this device.
427const CryptoType &get_crypto_type();
428
429struct CryptoType {
430 // We should only be constructing CryptoTypes as part of
431 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
432 // which isn't pure or fully protected as a concession to being able to
433 // do it all at compile time. Add new CryptoTypes in
434 // supported_crypto_types[] below.
435 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
436 constexpr CryptoType set_keysize(uint32_t size) const {
437 return CryptoType(this->property_name, this->crypto_name, size);
438 }
439 constexpr CryptoType set_property_name(const char *property) const {
440 return CryptoType(property, this->crypto_name, this->keysize);
441 }
442 constexpr CryptoType set_crypto_name(const char *crypto) const {
443 return CryptoType(this->property_name, crypto, this->keysize);
444 }
445
446 constexpr const char *get_property_name() const { return property_name; }
447 constexpr const char *get_crypto_name() const { return crypto_name; }
448 constexpr uint32_t get_keysize() const { return keysize; }
449
450 private:
451 const char *property_name;
452 const char *crypto_name;
453 uint32_t keysize;
454
455 constexpr CryptoType(const char *property, const char *crypto,
456 uint32_t ksize)
457 : property_name(property), crypto_name(crypto), keysize(ksize) {}
458 friend const CryptoType &get_crypto_type();
459 static const CryptoType &get_device_crypto_algorithm();
460};
461
462// We only want to parse this read-only property once. But we need to wait
463// until the system is initialized before we can read it. So we use a static
464// scoped within this function to get it only once.
465const CryptoType &get_crypto_type() {
466 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
467 return crypto_type;
468}
469
470constexpr CryptoType default_crypto_type = CryptoType()
471 .set_property_name("AES-128-CBC")
472 .set_crypto_name("aes-cbc-essiv:sha256")
473 .set_keysize(16);
474
475constexpr CryptoType supported_crypto_types[] = {
476 default_crypto_type,
Greg Kaiserd0285a22018-12-03 11:23:19 -0800477 CryptoType()
478 .set_property_name("adiantum")
479 .set_crypto_name("xchacha12,aes-adiantum-plain64")
480 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800481 // Add new CryptoTypes here. Order is not important.
482};
483
484
485// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
486// We confirm all supported_crypto_types have a small enough keysize and
487// had both set_property_name() and set_crypto_name() called.
488
489template <typename T, size_t N>
490constexpr size_t array_length(T (&)[N]) { return N; }
491
492constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
493 return (index >= array_length(supported_crypto_types));
494}
495
496constexpr bool isValidCryptoType(const CryptoType &crypto_type) {
497 return ((crypto_type.get_property_name() != nullptr) &&
498 (crypto_type.get_crypto_name() != nullptr) &&
499 (crypto_type.get_keysize() <= MAX_KEY_LEN));
500}
501
502// Note in C++11 that constexpr functions can only have a single line.
503// So our code is a bit convoluted (using recursion instead of a loop),
504// but it's asserting at compile time that all of our key lengths are valid.
505constexpr bool validateSupportedCryptoTypes(size_t index) {
506 return indexOutOfBoundsForCryptoTypes(index) ||
507 (isValidCryptoType(supported_crypto_types[index]) &&
508 validateSupportedCryptoTypes(index + 1));
509}
510
511static_assert(validateSupportedCryptoTypes(0),
512 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
513 "incompletely constructed.");
514// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
515
516
517// Don't call this directly, use get_crypto_type(), which caches this result.
518const CryptoType &CryptoType::get_device_crypto_algorithm() {
519 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
520 char paramstr[PROPERTY_VALUE_MAX];
521
522 property_get(CRYPT_ALGO_PROP, paramstr,
523 default_crypto_type.get_property_name());
524 for (auto const &ctype : supported_crypto_types) {
525 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
526 return ctype;
527 }
528 }
529 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr,
530 CRYPT_ALGO_PROP, default_crypto_type.get_property_name());
531 return default_crypto_type;
532}
533
534} // namespace
535
536
537
Kenny Rootc4c70f12013-06-14 12:11:38 -0700538/**
539 * Gets the default device scrypt parameters for key derivation time tuning.
540 * The parameters should lead to about one second derivation time for the
541 * given device.
542 */
543static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700544 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000545 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700546
Paul Crowley63c18d32016-02-10 14:02:47 +0000547 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
548 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
549 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
550 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700551 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000552 ftr->N_factor = Nf;
553 ftr->r_factor = rf;
554 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700555}
556
Greg Kaiser57f9af62018-02-16 13:13:58 -0800557uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800558 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800559}
560
561const char *cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800562 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800563}
564
Ken Sumrall3ed82362011-01-28 23:31:16 -0800565static unsigned int get_fs_size(char *dev)
566{
567 int fd, block_size;
568 struct ext4_super_block sb;
569 off64_t len;
570
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700571 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800572 SLOGE("Cannot open device to get filesystem size ");
573 return 0;
574 }
575
576 if (lseek64(fd, 1024, SEEK_SET) < 0) {
577 SLOGE("Cannot seek to superblock");
578 return 0;
579 }
580
581 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
582 SLOGE("Cannot read superblock");
583 return 0;
584 }
585
586 close(fd);
587
Daniel Rosenberge82df162014-08-15 22:19:23 +0000588 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
589 SLOGE("Not a valid ext4 superblock");
590 return 0;
591 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800592 block_size = 1024 << sb.s_log_block_size;
593 /* compute length in bytes */
594 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
595
596 /* return length in sectors */
597 return (unsigned int) (len / 512);
598}
599
Ken Sumrall160b4d62013-04-22 12:15:39 -0700600static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
601{
602 static int cached_data = 0;
603 static off64_t cached_off = 0;
604 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
605 int fd;
606 char key_loc[PROPERTY_VALUE_MAX];
607 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700608 int rc = -1;
609
610 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700611 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700612
613 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700614 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700615 SLOGE("Cannot open real block device %s\n", real_blkdev);
616 return -1;
617 }
618
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900619 unsigned long nr_sec = 0;
620 get_blkdev_size(fd, &nr_sec);
621 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700622 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
623 * encryption info footer and key, and plenty of bytes to spare for future
624 * growth.
625 */
626 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
627 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
628 cached_data = 1;
629 } else {
630 SLOGE("Cannot get size of block device %s\n", real_blkdev);
631 }
632 close(fd);
633 } else {
634 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
635 cached_off = 0;
636 cached_data = 1;
637 }
638 }
639
640 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;
648 }
649
650 return rc;
651}
652
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800653/* Set sha256 checksum in structure */
654static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
655{
656 SHA256_CTX c;
657 SHA256_Init(&c);
658 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
659 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
660 SHA256_Final(crypt_ftr->sha256, &c);
661}
662
Ken Sumralle8744072011-01-18 22:01:55 -0800663/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800664 * update the failed mount count but not change the key.
665 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700666static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800667{
668 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800669 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700670 /* starting_off is set to the SEEK_SET offset
671 * where the crypto structure starts
672 */
673 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800674 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700675 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700676 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800677
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800678 set_ftr_sha(crypt_ftr);
679
Ken Sumrall160b4d62013-04-22 12:15:39 -0700680 if (get_crypt_ftr_info(&fname, &starting_off)) {
681 SLOGE("Unable to get crypt_ftr_info\n");
682 return -1;
683 }
684 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700685 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700686 return -1;
687 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700688 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700689 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700690 return -1;
691 }
692
693 /* Seek to the start of the crypt footer */
694 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
695 SLOGE("Cannot seek to real block device footer\n");
696 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800697 }
698
699 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
700 SLOGE("Cannot write real block device footer\n");
701 goto errout;
702 }
703
Ken Sumrall3be890f2011-09-14 16:53:46 -0700704 fstat(fd, &statbuf);
705 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700706 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700707 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800708 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800709 goto errout;
710 }
711 }
712
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800713 /* Success! */
714 rc = 0;
715
716errout:
717 close(fd);
718 return rc;
719
720}
721
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800722static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
723{
724 struct crypt_mnt_ftr copy;
725 memcpy(&copy, crypt_ftr, sizeof(copy));
726 set_ftr_sha(&copy);
727 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
728}
729
Ken Sumrall160b4d62013-04-22 12:15:39 -0700730static inline int unix_read(int fd, void* buff, int len)
731{
732 return TEMP_FAILURE_RETRY(read(fd, buff, len));
733}
734
735static inline int unix_write(int fd, const void* buff, int len)
736{
737 return TEMP_FAILURE_RETRY(write(fd, buff, len));
738}
739
740static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
741{
742 memset(pdata, 0, len);
743 pdata->persist_magic = PERSIST_DATA_MAGIC;
744 pdata->persist_valid_entries = 0;
745}
746
747/* A routine to update the passed in crypt_ftr to the lastest version.
748 * fd is open read/write on the device that holds the crypto footer and persistent
749 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
750 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
751 */
752static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
753{
Kenny Root7434b312013-06-14 11:29:53 -0700754 int orig_major = crypt_ftr->major_version;
755 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700756
Kenny Root7434b312013-06-14 11:29:53 -0700757 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
758 struct crypt_persist_data *pdata;
759 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700760
Kenny Rootc4c70f12013-06-14 12:11:38 -0700761 SLOGW("upgrading crypto footer to 1.1");
762
Wei Wang4375f1b2017-02-24 17:43:01 -0800763 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700764 if (pdata == NULL) {
765 SLOGE("Cannot allocate persisent data\n");
766 return;
767 }
768 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
769
770 /* Need to initialize the persistent data area */
771 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
772 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100773 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700774 return;
775 }
776 /* Write all zeros to the first copy, making it invalid */
777 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
778
779 /* Write a valid but empty structure to the second copy */
780 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
781 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
782
783 /* Update the footer */
784 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
785 crypt_ftr->persist_data_offset[0] = pdata_offset;
786 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
787 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100788 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700789 }
790
Paul Lawrencef4faa572014-01-29 13:31:03 -0800791 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700792 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800793 /* But keep the old kdf_type.
794 * It will get updated later to KDF_SCRYPT after the password has been verified.
795 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700796 crypt_ftr->kdf_type = KDF_PBKDF2;
797 get_device_scrypt_params(crypt_ftr);
798 crypt_ftr->minor_version = 2;
799 }
800
Paul Lawrencef4faa572014-01-29 13:31:03 -0800801 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
802 SLOGW("upgrading crypto footer to 1.3");
803 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
804 crypt_ftr->minor_version = 3;
805 }
806
Kenny Root7434b312013-06-14 11:29:53 -0700807 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
808 if (lseek64(fd, offset, SEEK_SET) == -1) {
809 SLOGE("Cannot seek to crypt footer\n");
810 return;
811 }
812 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700813 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700814}
815
816
817static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800818{
819 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800820 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700821 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800822 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700823 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700824 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800825
Ken Sumrall160b4d62013-04-22 12:15:39 -0700826 if (get_crypt_ftr_info(&fname, &starting_off)) {
827 SLOGE("Unable to get crypt_ftr_info\n");
828 return -1;
829 }
830 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700831 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700832 return -1;
833 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700834 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700835 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700836 return -1;
837 }
838
839 /* Make sure it's 16 Kbytes in length */
840 fstat(fd, &statbuf);
841 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
842 SLOGE("footer file %s is not the expected size!\n", fname);
843 goto errout;
844 }
845
846 /* Seek to the start of the crypt footer */
847 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
848 SLOGE("Cannot seek to real block device footer\n");
849 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800850 }
851
852 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
853 SLOGE("Cannot read real block device footer\n");
854 goto errout;
855 }
856
857 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700858 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800859 goto errout;
860 }
861
Kenny Rootc96a5f82013-06-14 12:08:28 -0700862 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
863 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
864 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800865 goto errout;
866 }
867
Greg Kaiser59ad0182018-02-16 13:01:36 -0800868 // We risk buffer overflows with oversized keys, so we just reject them.
869 // 0-sized keys are problematic (essentially by-passing encryption), and
870 // AES-CBC key wrapping only works for multiples of 16 bytes.
871 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
872 (crypt_ftr->keysize > MAX_KEY_LEN)) {
873 SLOGE("Invalid keysize (%u) for block device %s; Must be non-zero, "
874 "divisible by 16, and <= %d\n", crypt_ftr->keysize, fname,
875 MAX_KEY_LEN);
876 goto errout;
877 }
878
Kenny Rootc96a5f82013-06-14 12:08:28 -0700879 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
880 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
881 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800882 }
883
Ken Sumrall160b4d62013-04-22 12:15:39 -0700884 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
885 * copy on disk before returning.
886 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700887 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700888 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800889 }
890
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800891 /* Success! */
892 rc = 0;
893
894errout:
895 close(fd);
896 return rc;
897}
898
Ken Sumrall160b4d62013-04-22 12:15:39 -0700899static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
900{
901 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
902 crypt_ftr->persist_data_offset[1]) {
903 SLOGE("Crypt_ftr persist data regions overlap");
904 return -1;
905 }
906
907 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
908 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
909 return -1;
910 }
911
912 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
913 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
914 CRYPT_FOOTER_OFFSET) {
915 SLOGE("Persistent data extends past crypto footer");
916 return -1;
917 }
918
919 return 0;
920}
921
922static int load_persistent_data(void)
923{
924 struct crypt_mnt_ftr crypt_ftr;
925 struct crypt_persist_data *pdata = NULL;
926 char encrypted_state[PROPERTY_VALUE_MAX];
927 char *fname;
928 int found = 0;
929 int fd;
930 int ret;
931 int i;
932
933 if (persist_data) {
934 /* Nothing to do, we've already loaded or initialized it */
935 return 0;
936 }
937
938
939 /* If not encrypted, just allocate an empty table and initialize it */
940 property_get("ro.crypto.state", encrypted_state, "");
941 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800942 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700943 if (pdata) {
944 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
945 persist_data = pdata;
946 return 0;
947 }
948 return -1;
949 }
950
951 if(get_crypt_ftr_and_key(&crypt_ftr)) {
952 return -1;
953 }
954
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700955 if ((crypt_ftr.major_version < 1)
956 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700957 SLOGE("Crypt_ftr version doesn't support persistent data");
958 return -1;
959 }
960
961 if (get_crypt_ftr_info(&fname, NULL)) {
962 return -1;
963 }
964
965 ret = validate_persistent_data_storage(&crypt_ftr);
966 if (ret) {
967 return -1;
968 }
969
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700970 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700971 if (fd < 0) {
972 SLOGE("Cannot open %s metadata file", fname);
973 return -1;
974 }
975
Wei Wang4375f1b2017-02-24 17:43:01 -0800976 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800977 if (pdata == NULL) {
978 SLOGE("Cannot allocate memory for persistent data");
979 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700980 }
981
982 for (i = 0; i < 2; i++) {
983 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
984 SLOGE("Cannot seek to read persistent data on %s", fname);
985 goto err2;
986 }
987 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
988 SLOGE("Error reading persistent data on iteration %d", i);
989 goto err2;
990 }
991 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
992 found = 1;
993 break;
994 }
995 }
996
997 if (!found) {
998 SLOGI("Could not find valid persistent data, creating");
999 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
1000 }
1001
1002 /* Success */
1003 persist_data = pdata;
1004 close(fd);
1005 return 0;
1006
1007err2:
1008 free(pdata);
1009
1010err:
1011 close(fd);
1012 return -1;
1013}
1014
1015static int save_persistent_data(void)
1016{
1017 struct crypt_mnt_ftr crypt_ftr;
1018 struct crypt_persist_data *pdata;
1019 char *fname;
1020 off64_t write_offset;
1021 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001022 int fd;
1023 int ret;
1024
1025 if (persist_data == NULL) {
1026 SLOGE("No persistent data to save");
1027 return -1;
1028 }
1029
1030 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1031 return -1;
1032 }
1033
Paul Lawrence8561b5c2014-03-17 14:10:51 -07001034 if ((crypt_ftr.major_version < 1)
1035 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001036 SLOGE("Crypt_ftr version doesn't support persistent data");
1037 return -1;
1038 }
1039
1040 ret = validate_persistent_data_storage(&crypt_ftr);
1041 if (ret) {
1042 return -1;
1043 }
1044
1045 if (get_crypt_ftr_info(&fname, NULL)) {
1046 return -1;
1047 }
1048
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001049 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001050 if (fd < 0) {
1051 SLOGE("Cannot open %s metadata file", fname);
1052 return -1;
1053 }
1054
Wei Wang4375f1b2017-02-24 17:43:01 -08001055 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001056 if (pdata == NULL) {
1057 SLOGE("Cannot allocate persistant data");
1058 goto err;
1059 }
1060
1061 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1062 SLOGE("Cannot seek to read persistent data on %s", fname);
1063 goto err2;
1064 }
1065
1066 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
1067 SLOGE("Error reading persistent data before save");
1068 goto err2;
1069 }
1070
1071 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1072 /* The first copy is the curent valid copy, so write to
1073 * the second copy and erase this one */
1074 write_offset = crypt_ftr.persist_data_offset[1];
1075 erase_offset = crypt_ftr.persist_data_offset[0];
1076 } else {
1077 /* The second copy must be the valid copy, so write to
1078 * the first copy, and erase the second */
1079 write_offset = crypt_ftr.persist_data_offset[0];
1080 erase_offset = crypt_ftr.persist_data_offset[1];
1081 }
1082
1083 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001084 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001085 SLOGE("Cannot seek to write persistent data");
1086 goto err2;
1087 }
1088 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1089 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001090 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001091 SLOGE("Cannot seek to erase previous persistent data");
1092 goto err2;
1093 }
1094 fsync(fd);
1095 memset(pdata, 0, crypt_ftr.persist_data_size);
1096 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
1097 (int) crypt_ftr.persist_data_size) {
1098 SLOGE("Cannot write to erase previous persistent data");
1099 goto err2;
1100 }
1101 fsync(fd);
1102 } else {
1103 SLOGE("Cannot write to save persistent data");
1104 goto err2;
1105 }
1106
1107 /* Success */
1108 free(pdata);
1109 close(fd);
1110 return 0;
1111
1112err2:
1113 free(pdata);
1114err:
1115 close(fd);
1116 return -1;
1117}
1118
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001119/* Convert a binary key of specified length into an ascii hex string equivalent,
1120 * without the leading 0x and with null termination
1121 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001122static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001123 unsigned int keysize, char *master_key_ascii) {
1124 unsigned int i, a;
1125 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001127 for (i=0, a=0; i<keysize; i++, a+=2) {
1128 /* For each byte, write out two ascii hex digits */
1129 nibble = (master_key[i] >> 4) & 0xf;
1130 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001132 nibble = master_key[i] & 0xf;
1133 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1134 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001135
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001136 /* Add the null termination */
1137 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001138
1139}
1140
Jeff Sharkey9c484982015-03-31 10:35:33 -07001141static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
1142 const unsigned char *master_key, const char *real_blk_name,
1143 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -08001144 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001145 struct dm_ioctl *io;
1146 struct dm_target_spec *tgt;
1147 char *crypt_params;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001148 // We need two ASCII characters to represent each byte, and need space for
1149 // the '\0' terminator.
1150 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
George Burgess IV605d7ae2016-02-29 13:39:17 -08001151 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001152 int i;
1153
1154 io = (struct dm_ioctl *) buffer;
1155
1156 /* Load the mapping table for this device */
1157 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1158
1159 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1160 io->target_count = 1;
1161 tgt->status = 0;
1162 tgt->sector_start = 0;
1163 tgt->length = crypt_ftr->fs_size;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001164 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
George Burgess IV605d7ae2016-02-29 13:39:17 -08001165 buff_offset = crypt_params - buffer;
Eric Biggers9820d1e2019-01-25 12:11:25 -08001166 SLOGI(
1167 "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
1168 name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
1169 extra_params);
Jackeagle5223b002019-05-06 01:51:10 -04001170
AnilKumar Chimata35850082018-05-11 00:25:09 +05301171#ifdef CONFIG_HW_DISK_ENCRYPTION
1172 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1173 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1174 if (is_ice_enabled())
1175 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1176 else
1177 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1178 }
1179 else {
1180 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1181 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1182 }
1183 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1184 crypt_ftr->crypto_type_name, master_key_ascii,
1185 real_blk_name, extra_params);
1186
1187 SLOGI("target_type = %s", tgt->target_type);
1188 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1189#else
1190 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1191 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Jackeagle5223b002019-05-06 01:51:10 -04001192
George Burgess IV605d7ae2016-02-29 13:39:17 -08001193 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
1194 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
1195 extra_params);
AnilKumar Chimata35850082018-05-11 00:25:09 +05301196#endif
1197
Ken Sumralldb5e0262013-02-05 17:39:48 -08001198 crypt_params += strlen(crypt_params) + 1;
1199 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1200 tgt->next = crypt_params - buffer;
1201
1202 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1203 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1204 break;
1205 }
1206 usleep(500000);
1207 }
1208
1209 if (i == TABLE_LOAD_RETRIES) {
1210 /* We failed to load the table, return an error */
1211 return -1;
1212 } else {
1213 return i + 1;
1214 }
1215}
1216
Ken Sumralldb5e0262013-02-05 17:39:48 -08001217static int get_dm_crypt_version(int fd, const char *name, int *version)
1218{
1219 char buffer[DM_CRYPT_BUF_SIZE];
1220 struct dm_ioctl *io;
1221 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001222
1223 io = (struct dm_ioctl *) buffer;
1224
1225 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1226
1227 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1228 return -1;
1229 }
1230
1231 /* Iterate over the returned versions, looking for name of "crypt".
1232 * When found, get and return the version.
1233 */
1234 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1235 while (v->next) {
AnilKumar Chimata35850082018-05-11 00:25:09 +05301236#ifdef CONFIG_HW_DISK_ENCRYPTION
1237 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
1238#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001239 if (! strcmp(v->name, "crypt")) {
AnilKumar Chimata35850082018-05-11 00:25:09 +05301240#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001241 /* We found the crypt driver, return the version, and get out */
1242 version[0] = v->version[0];
1243 version[1] = v->version[1];
1244 version[2] = v->version[2];
1245 return 0;
1246 }
1247 v = (struct dm_target_versions *)(((char *)v) + v->next);
1248 }
1249
1250 return -1;
1251}
1252
AnilKumar Chimata35850082018-05-11 00:25:09 +05301253#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Crowley5afbc622017-11-27 09:42:17 -08001254static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1255 if (extra_params_vec.empty()) return "";
1256 std::string extra_params = std::to_string(extra_params_vec.size());
1257 for (const auto& p : extra_params_vec) {
1258 extra_params.append(" ");
1259 extra_params.append(p);
1260 }
1261 return extra_params;
1262}
AnilKumar Chimata35850082018-05-11 00:25:09 +05301263#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001264
Eric Biggers668c23f2019-01-25 10:47:55 -08001265/*
1266 * If the ro.crypto.fde_sector_size system property is set, append the
1267 * parameters to make dm-crypt use the specified crypto sector size and round
1268 * the crypto device size down to a crypto sector boundary.
1269 */
1270static int add_sector_size_param(std::vector<std::string>* extra_params_vec,
1271 struct crypt_mnt_ftr* ftr) {
Greg Kaiser8c63b572018-12-11 12:40:51 -08001272 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggers668c23f2019-01-25 10:47:55 -08001273 char value[PROPERTY_VALUE_MAX];
Greg Kaiser8c63b572018-12-11 12:40:51 -08001274
Eric Biggers668c23f2019-01-25 10:47:55 -08001275 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1276 unsigned int sector_size;
1277
1278 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1279 (sector_size & (sector_size - 1)) != 0) {
1280 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1281 DM_CRYPT_SECTOR_SIZE, value);
1282 return -1;
1283 }
1284
1285 std::string param = StringPrintf("sector_size:%u", sector_size);
Greg Kaiser8c63b572018-12-11 12:40:51 -08001286 extra_params_vec->push_back(std::move(param));
1287
1288 // With this option, IVs will match the sector numbering, instead
1289 // of being hard-coded to being based on 512-byte sectors.
1290 extra_params_vec->emplace_back("iv_large_sectors");
Eric Biggers668c23f2019-01-25 10:47:55 -08001291
1292 // Round the crypto device size down to a crypto sector boundary.
1293 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiser8c63b572018-12-11 12:40:51 -08001294 }
Eric Biggers668c23f2019-01-25 10:47:55 -08001295 return 0;
Greg Kaiser8c63b572018-12-11 12:40:51 -08001296}
1297
Paul Crowley5afbc622017-11-27 09:42:17 -08001298static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1299 const char* real_blk_name, char* crypto_blk_name, const char* name,
1300 uint32_t flags) {
1301 char buffer[DM_CRYPT_BUF_SIZE];
1302 struct dm_ioctl* io;
1303 unsigned int minor;
1304 int fd = 0;
1305 int err;
1306 int retval = -1;
1307 int version[3];
1308 int load_count;
AnilKumar Chimata35850082018-05-11 00:25:09 +05301309#ifdef CONFIG_HW_DISK_ENCRYPTION
1310 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1311 char progress[PROPERTY_VALUE_MAX] = {0};
1312 const char *extra_params;
1313#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001314 std::vector<std::string> extra_params_vec;
AnilKumar Chimata35850082018-05-11 00:25:09 +05301315#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001316
Paul Crowley5afbc622017-11-27 09:42:17 -08001317 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1318 SLOGE("Cannot open device-mapper\n");
1319 goto errout;
1320 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001321
Paul Crowley5afbc622017-11-27 09:42:17 -08001322 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001323
Paul Crowley5afbc622017-11-27 09:42:17 -08001324 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1325 err = ioctl(fd, DM_DEV_CREATE, io);
1326 if (err) {
1327 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1328 goto errout;
1329 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001330
Paul Crowley5afbc622017-11-27 09:42:17 -08001331 /* Get the device status, in particular, the name of it's device file */
1332 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1333 if (ioctl(fd, DM_DEV_STATUS, io)) {
1334 SLOGE("Cannot retrieve dm-crypt device status\n");
1335 goto errout;
1336 }
1337 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1338 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001339
AnilKumar Chimata35850082018-05-11 00:25:09 +05301340#ifdef CONFIG_HW_DISK_ENCRYPTION
1341 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1342 /* Set fde_enabled if either FDE completed or in-progress */
1343 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1344 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1345 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1346 if (is_ice_enabled()) {
1347 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1348 extra_params = "fde_enabled ice allow_encrypt_override";
1349 else
1350 extra_params = "fde_enabled ice";
1351 } else {
1352 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1353 extra_params = "fde_enabled allow_encrypt_override";
1354 else
1355 extra_params = "fde_enabled";
1356 }
1357 } else {
1358 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1359 extra_params = "fde_enabled allow_encrypt_override";
1360 else
1361 extra_params = "fde_enabled";
1362 }
1363 } else {
1364 extra_params = "";
1365 if (! get_dm_crypt_version(fd, name, version)) {
1366 /* Support for allow_discards was added in version 1.11.0 */
1367 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1368 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1369 extra_params = "2 allow_discards allow_encrypt_override";
1370 else
1371 extra_params = "1 allow_discards";
1372 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1373 }
1374 }
1375 }
1376 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1377 extra_params);
1378#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001379 if (!get_dm_crypt_version(fd, name, version)) {
1380 /* Support for allow_discards was added in version 1.11.0 */
1381 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1382 extra_params_vec.emplace_back("allow_discards");
1383 }
1384 }
1385 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1386 extra_params_vec.emplace_back("allow_encrypt_override");
1387 }
Eric Biggers668c23f2019-01-25 10:47:55 -08001388 if (add_sector_size_param(&extra_params_vec, crypt_ftr)) {
1389 SLOGE("Error processing dm-crypt sector size param\n");
1390 goto errout;
1391 }
Paul Crowley5afbc622017-11-27 09:42:17 -08001392 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1393 extra_params_as_string(extra_params_vec).c_str());
AnilKumar Chimata35850082018-05-11 00:25:09 +05301394#endif
Paul Crowley5afbc622017-11-27 09:42:17 -08001395 if (load_count < 0) {
1396 SLOGE("Cannot load dm-crypt mapping table.\n");
1397 goto errout;
1398 } else if (load_count > 1) {
1399 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1400 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001401
Paul Crowley5afbc622017-11-27 09:42:17 -08001402 /* Resume this device to activate it */
1403 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001404
Paul Crowley5afbc622017-11-27 09:42:17 -08001405 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1406 SLOGE("Cannot resume the dm-crypt device\n");
1407 goto errout;
1408 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001409
Paul Crowleyc5e3a522018-10-30 15:59:24 -07001410 /* Ensure the dm device has been created before returning. */
1411 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1412 // WaitForFile generates a suitable log message
1413 goto errout;
1414 }
1415
Paul Crowley5afbc622017-11-27 09:42:17 -08001416 /* We made it here with no errors. Woot! */
1417 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001418
1419errout:
1420 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1421
1422 return retval;
1423}
1424
Wei Wang4375f1b2017-02-24 17:43:01 -08001425static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426{
1427 int fd;
1428 char buffer[DM_CRYPT_BUF_SIZE];
1429 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430 int retval = -1;
1431
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001432 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001433 SLOGE("Cannot open device-mapper\n");
1434 goto errout;
1435 }
1436
1437 io = (struct dm_ioctl *) buffer;
1438
1439 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1440 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1441 SLOGE("Cannot remove dm-crypt device\n");
1442 goto errout;
1443 }
1444
1445 /* We made it here with no errors. Woot! */
1446 retval = 0;
1447
1448errout:
1449 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1450
1451 return retval;
1452
1453}
1454
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001455static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001456 unsigned char *ikey, void *params UNUSED)
1457{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001458 SLOGI("Using pbkdf2 for cryptfs KDF");
1459
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001460 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001461 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001462 HASH_COUNT, INTERMEDIATE_BUF_SIZE,
Adam Langleybf0d9722015-11-04 14:51:39 -08001463 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001464}
1465
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001466static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001467 unsigned char *ikey, void *params)
1468{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001469 SLOGI("Using scrypt for cryptfs KDF");
1470
Kenny Rootc4c70f12013-06-14 12:11:38 -07001471 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1472
1473 int N = 1 << ftr->N_factor;
1474 int r = 1 << ftr->r_factor;
1475 int p = 1 << ftr->p_factor;
1476
1477 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001478 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1479 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001480 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001481
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001482 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001483}
1484
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001485static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1486 unsigned char *ikey, void *params)
1487{
1488 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1489
1490 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001491 size_t signature_size;
1492 unsigned char* signature;
1493 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1494
1495 int N = 1 << ftr->N_factor;
1496 int r = 1 << ftr->r_factor;
1497 int p = 1 << ftr->p_factor;
1498
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001499 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1500 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001501 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001502
1503 if (rc) {
1504 SLOGE("scrypt failed");
1505 return -1;
1506 }
1507
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001508 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE,
Shawn Willdene17a9c42014-09-08 13:04:08 -06001509 &signature, &signature_size)) {
1510 SLOGE("Signing failed");
1511 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001512 }
1513
1514 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001515 N, r, p, ikey, INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001516 free(signature);
1517
1518 if (rc) {
1519 SLOGE("scrypt failed");
1520 return -1;
1521 }
1522
1523 return 0;
1524}
1525
1526static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1527 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001528 unsigned char *encrypted_master_key,
AnilKumar Chimata35850082018-05-11 00:25:09 +05301529 struct crypt_mnt_ftr *crypt_ftr,
1530 bool create_keymaster_key)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001531{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001532 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001533 EVP_CIPHER_CTX e_ctx;
1534 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001535 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001536
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001537 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001538 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001539
1540 switch (crypt_ftr->kdf_type) {
1541 case KDF_SCRYPT_KEYMASTER:
AnilKumar Chimata35850082018-05-11 00:25:09 +05301542 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001543 SLOGE("keymaster_create_key failed");
1544 return -1;
1545 }
1546
1547 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1548 SLOGE("scrypt failed");
1549 return -1;
1550 }
1551 break;
1552
1553 case KDF_SCRYPT:
1554 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1555 SLOGE("scrypt failed");
1556 return -1;
1557 }
1558 break;
1559
1560 default:
1561 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001562 return -1;
1563 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001564
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001565 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001566 EVP_CIPHER_CTX_init(&e_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001567 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1568 ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569 SLOGE("EVP_EncryptInit failed\n");
1570 return -1;
1571 }
1572 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001573
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001574 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001575 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001576 decrypted_master_key, crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001577 SLOGE("EVP_EncryptUpdate failed\n");
1578 return -1;
1579 }
Adam Langley889c4f12014-09-03 14:23:13 -07001580 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001581 SLOGE("EVP_EncryptFinal failed\n");
1582 return -1;
1583 }
1584
Greg Kaiser59ad0182018-02-16 13:01:36 -08001585 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001586 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1587 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001588 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001589
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001590 /* Store the scrypt of the intermediate key, so we can validate if it's a
1591 password error or mount error when things go wrong.
1592 Note there's no need to check for errors, since if this is incorrect, we
1593 simply won't wipe userdata, which is the correct default behavior
1594 */
1595 int N = 1 << crypt_ftr->N_factor;
1596 int r = 1 << crypt_ftr->r_factor;
1597 int p = 1 << crypt_ftr->p_factor;
1598
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001599 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001600 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1601 crypt_ftr->scrypted_intermediate_key,
1602 sizeof(crypt_ftr->scrypted_intermediate_key));
1603
1604 if (rc) {
1605 SLOGE("encrypt_master_key: crypto_scrypt failed");
1606 }
1607
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001608 EVP_CIPHER_CTX_cleanup(&e_ctx);
1609
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001610 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001611}
1612
Paul Lawrence731a7a22015-04-28 22:14:15 +00001613static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001614 const unsigned char *encrypted_master_key,
1615 size_t keysize,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001616 unsigned char *decrypted_master_key,
1617 kdf_func kdf, void *kdf_params,
1618 unsigned char** intermediate_key,
1619 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001620{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001621 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001622 EVP_CIPHER_CTX d_ctx;
1623 int decrypted_len, final_len;
1624
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001625 /* Turn the password into an intermediate key and IV that can decrypt the
1626 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001627 if (kdf(passwd, salt, ikey, kdf_params)) {
1628 SLOGE("kdf failed");
1629 return -1;
1630 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001631
1632 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001633 EVP_CIPHER_CTX_init(&d_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001634 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001635 return -1;
1636 }
1637 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1638 /* Decrypt the master key */
1639 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001640 encrypted_master_key, keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001641 return -1;
1642 }
Adam Langley889c4f12014-09-03 14:23:13 -07001643 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001644 return -1;
1645 }
1646
Greg Kaiser59ad0182018-02-16 13:01:36 -08001647 if (decrypted_len + final_len != static_cast<int>(keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001648 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001649 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001650
1651 /* Copy intermediate key if needed by params */
1652 if (intermediate_key && intermediate_key_size) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001653 *intermediate_key = (unsigned char*) malloc(INTERMEDIATE_KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001654 if (*intermediate_key) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001655 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1656 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001657 }
1658 }
1659
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001660 EVP_CIPHER_CTX_cleanup(&d_ctx);
1661
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001662 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001663}
1664
Kenny Rootc4c70f12013-06-14 12:11:38 -07001665static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001666{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001667 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001668 *kdf = scrypt_keymaster;
1669 *kdf_params = ftr;
1670 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001671 *kdf = scrypt;
1672 *kdf_params = ftr;
1673 } else {
1674 *kdf = pbkdf2;
1675 *kdf_params = NULL;
1676 }
1677}
1678
Paul Lawrence731a7a22015-04-28 22:14:15 +00001679static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001680 struct crypt_mnt_ftr *crypt_ftr,
1681 unsigned char** intermediate_key,
1682 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001683{
1684 kdf_func kdf;
1685 void *kdf_params;
1686 int ret;
1687
1688 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001689 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001690 crypt_ftr->keysize,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001691 decrypted_master_key, kdf, kdf_params,
1692 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001693 if (ret != 0) {
1694 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001695 }
1696
1697 return ret;
1698}
1699
Wei Wang4375f1b2017-02-24 17:43:01 -08001700static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001701 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001702 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001703 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001704
1705 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001706 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001707 read(fd, key_buf, sizeof(key_buf));
1708 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001709 close(fd);
1710
1711 /* Now encrypt it with the password */
AnilKumar Chimata35850082018-05-11 00:25:09 +05301712 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001713}
1714
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001715int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001716{
Greg Hackmann955653e2014-09-24 14:55:20 -07001717 int i, err, rc;
AnilKumar Chimata35850082018-05-11 00:25:09 +05301718#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001719
1720 /* Now umount the tmpfs filesystem */
1721 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001722 if (umount(mountpoint) == 0) {
1723 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001725
1726 if (errno == EINVAL) {
1727 /* EINVAL is returned if the directory is not a mountpoint,
1728 * i.e. there is no filesystem mounted there. So just get out.
1729 */
1730 break;
1731 }
1732
1733 err = errno;
1734
AnilKumar Chimata35850082018-05-11 00:25:09 +05301735 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001736 if (kill) {
AnilKumar Chimata35850082018-05-11 00:25:09 +05301737 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001738 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001739 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata35850082018-05-11 00:25:09 +05301740 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001741 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001742 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001743 }
1744 }
1745
AnilKumar Chimata35850082018-05-11 00:25:09 +05301746 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001747 }
1748
1749 if (i < WAIT_UNMOUNT_COUNT) {
1750 SLOGD("unmounting %s succeeded\n", mountpoint);
1751 rc = 0;
1752 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001753 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001754 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001755 rc = -1;
1756 }
1757
1758 return rc;
1759}
1760
Wei Wang42e38102017-06-07 10:46:12 -07001761static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001762{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001763 // NOTE: post_fs_data results in init calling back around to vold, so all
1764 // callers to this method must be async
1765
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001766 /* Do the prep of the /data filesystem */
1767 property_set("vold.post_fs_data_done", "0");
1768 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001769 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001770
Ken Sumrallc5872692013-05-14 15:26:31 -07001771 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001772 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001773 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001774 std::chrono::seconds(15))) {
1775 /* We timed out to prep /data in time. Continue wait. */
1776 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001777 }
Wei Wang42e38102017-06-07 10:46:12 -07001778 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001779}
1780
Paul Lawrence74f29f12014-08-28 15:54:10 -07001781static void cryptfs_set_corrupt()
1782{
1783 // Mark the footer as bad
1784 struct crypt_mnt_ftr crypt_ftr;
1785 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1786 SLOGE("Failed to get crypto footer - panic");
1787 return;
1788 }
1789
1790 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1791 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1792 SLOGE("Failed to set crypto footer - panic");
1793 return;
1794 }
1795}
1796
1797static void cryptfs_trigger_restart_min_framework()
1798{
1799 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1800 SLOGE("Failed to mount tmpfs on data - panic");
1801 return;
1802 }
1803
1804 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1805 SLOGE("Failed to trigger post fs data - panic");
1806 return;
1807 }
1808
1809 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1810 SLOGE("Failed to trigger restart min framework - panic");
1811 return;
1812 }
1813}
1814
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001815/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001816static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001817{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001818 char crypto_blkdev[MAXPATHLEN];
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05301819#ifdef CONFIG_HW_DISK_ENCRYPTION
1820 char blkdev[MAXPATHLEN];
1821#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001822 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001823 static int restart_successful = 0;
1824
1825 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001826 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001827 SLOGE("Encrypted filesystem not validated, aborting");
1828 return -1;
1829 }
1830
1831 if (restart_successful) {
1832 SLOGE("System already restarted with encrypted disk, aborting");
1833 return -1;
1834 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001835
Paul Lawrencef4faa572014-01-29 13:31:03 -08001836 if (restart_main) {
1837 /* Here is where we shut down the framework. The init scripts
1838 * start all services in one of three classes: core, main or late_start.
1839 * On boot, we start core and main. Now, we stop main, but not core,
1840 * as core includes vold and a few other really important things that
1841 * we need to keep running. Once main has stopped, we should be able
1842 * to umount the tmpfs /data, then mount the encrypted /data.
1843 * We then restart the class main, and also the class late_start.
1844 * At the moment, I've only put a few things in late_start that I know
1845 * are not needed to bring up the framework, and that also cause problems
1846 * with unmounting the tmpfs /data, but I hope to add add more services
1847 * to the late_start class as we optimize this to decrease the delay
1848 * till the user is asked for the password to the filesystem.
1849 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001850
Paul Lawrencef4faa572014-01-29 13:31:03 -08001851 /* The init files are setup to stop the class main when vold.decrypt is
1852 * set to trigger_reset_main.
1853 */
1854 property_set("vold.decrypt", "trigger_reset_main");
1855 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001856
Paul Lawrencef4faa572014-01-29 13:31:03 -08001857 /* Ugh, shutting down the framework is not synchronous, so until it
1858 * can be fixed, this horrible hack will wait a moment for it all to
1859 * shut down before proceeding. Without it, some devices cannot
1860 * restart the graphics services.
1861 */
1862 sleep(2);
1863 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001864
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001865 /* Now that the framework is shutdown, we should be able to umount()
1866 * the tmpfs filesystem, and mount the real one.
1867 */
1868
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05301869#if defined(CONFIG_HW_DISK_ENCRYPTION)
1870#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1871 if (is_ice_enabled()) {
1872 fs_mgr_get_crypt_info(fstab_default, 0, blkdev, sizeof(blkdev));
1873 if (set_ice_param(START_ENCDEC)) {
1874 SLOGE("Failed to set ICE data");
1875 return -1;
1876 }
1877 }
1878#else
1879 property_get("ro.crypto.fs_crypto_blkdev", blkdev, "");
1880 if (strlen(blkdev) == 0) {
1881 SLOGE("fs_crypto_blkdev not set\n");
1882 return -1;
1883 }
1884 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1885#endif
1886#else
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001887 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1888 if (strlen(crypto_blkdev) == 0) {
1889 SLOGE("fs_crypto_blkdev not set\n");
1890 return -1;
1891 }
1892
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001893 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05301894#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001895 /* If ro.crypto.readonly is set to 1, mount the decrypted
1896 * filesystem readonly. This is used when /data is mounted by
1897 * recovery mode.
1898 */
1899 char ro_prop[PROPERTY_VALUE_MAX];
1900 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001901 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001902 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001903 rec->flags |= MS_RDONLY;
1904 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001905
Ken Sumralle5032c42012-04-01 23:58:44 -07001906 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001907 int retries = RETRY_MOUNT_ATTEMPTS;
1908 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001909
1910 /*
1911 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1912 * partitions in the fsck domain.
1913 */
1914 if (setexeccon(secontextFsck())){
1915 SLOGE("Failed to setexeccon");
1916 return -1;
1917 }
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05301918#ifdef CONFIG_HW_DISK_ENCRYPTION
1919 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
1920 blkdev, 0))
1921 != 0) {
1922#else
Paul Crowleye2ee1522017-09-26 14:05:26 -07001923 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001924 crypto_blkdev, 0))
1925 != 0) {
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05301926#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001927 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1928 /* TODO: invoke something similar to
1929 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1930 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05301931#ifdef CONFIG_HW_DISK_ENCRYPTION
1932 SLOGI("Failed to mount %s because it is busy - waiting",
1933 blkdev);
1934#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001935 SLOGI("Failed to mount %s because it is busy - waiting",
1936 crypto_blkdev);
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05301937#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001938 if (--retries) {
1939 sleep(RETRY_MOUNT_DELAY_SECONDS);
1940 } else {
1941 /* Let's hope that a reboot clears away whatever is keeping
1942 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001943 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001944 }
1945 } else {
AnilKumar Chimata35850082018-05-11 00:25:09 +05301946#ifdef CONFIG_HW_DISK_ENCRYPTION
1947 if (--retries) {
1948 sleep(RETRY_MOUNT_DELAY_SECONDS);
1949 } else {
1950 SLOGE("Failed to mount decrypted data");
1951 cryptfs_set_corrupt();
1952 cryptfs_trigger_restart_min_framework();
1953 SLOGI("Started framework to offer wipe");
1954 return -1;
1955 }
1956#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001957 SLOGE("Failed to mount decrypted data");
1958 cryptfs_set_corrupt();
1959 cryptfs_trigger_restart_min_framework();
1960 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001961 if (setexeccon(NULL)) {
1962 SLOGE("Failed to setexeccon");
1963 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001964 return -1;
AnilKumar Chimata35850082018-05-11 00:25:09 +05301965#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001966 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001967 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001968 if (setexeccon(NULL)) {
1969 SLOGE("Failed to setexeccon");
1970 return -1;
1971 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001972
Ken Sumralle5032c42012-04-01 23:58:44 -07001973 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001974 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001975 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001976
1977 /* startup service classes main and late_start */
1978 property_set("vold.decrypt", "trigger_restart_framework");
1979 SLOGD("Just triggered restart_framework\n");
1980
1981 /* Give it a few moments to get started */
1982 sleep(1);
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05301983#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001984 }
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05301985#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001986
Ken Sumrall0cc16632011-01-18 20:32:26 -08001987 if (rc == 0) {
1988 restart_successful = 1;
1989 }
1990
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001991 return rc;
1992}
1993
Paul Lawrencef4faa572014-01-29 13:31:03 -08001994int cryptfs_restart(void)
1995{
Paul Lawrence05335c32015-03-05 09:46:23 -08001996 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001997 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001998 SLOGE("cryptfs_restart not valid for file encryption:");
1999 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002000 }
2001
Paul Lawrencef4faa572014-01-29 13:31:03 -08002002 /* Call internal implementation forcing a restart of main service group */
2003 return cryptfs_restart_internal(1);
2004}
2005
Wei Wang4375f1b2017-02-24 17:43:01 -08002006static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002007{
2008 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002009 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08002010 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002011
2012 property_get("ro.crypto.state", encrypted_state, "");
2013 if (strcmp(encrypted_state, "encrypted") ) {
2014 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002015 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002016 }
2017
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002018 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00002019 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002020 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08002021 }
2022
Ken Sumrall160b4d62013-04-22 12:15:39 -07002023 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002024 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07002025
Ken Sumralle1a45852011-12-14 21:24:27 -08002026 /*
2027 * Only report this error if key_loc is a file and it exists.
2028 * If the device was never encrypted, and /data is not mountable for
2029 * some reason, returning 1 should prevent the UI from presenting the
2030 * a "enter password" screen, or worse, a "press button to wipe the
2031 * device" screen.
2032 */
2033 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
2034 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002035 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08002036 } else {
2037 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002038 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08002039 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002040 }
2041
Paul Lawrence74f29f12014-08-28 15:54:10 -07002042 // Test for possible error flags
2043 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
2044 SLOGE("Encryption process is partway completed\n");
2045 return CRYPTO_COMPLETE_PARTIAL;
2046 }
2047
2048 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
2049 SLOGE("Encryption process was interrupted but cannot continue\n");
2050 return CRYPTO_COMPLETE_INCONSISTENT;
2051 }
2052
2053 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
2054 SLOGE("Encryption is successful but data is corrupt\n");
2055 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002056 }
2057
2058 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07002059 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002060}
2061
AnilKumar Chimata35850082018-05-11 00:25:09 +05302062#ifdef CONFIG_HW_DISK_ENCRYPTION
2063static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
2064 const char *passwd, const char *mount_point, const char *label)
2065{
2066 /* Allocate enough space for a 256 bit key, but we may use less */
2067 unsigned char decrypted_master_key[32];
2068 char crypto_blkdev[MAXPATHLEN];
2069 char real_blkdev[MAXPATHLEN];
2070 unsigned int orig_failed_decrypt_count;
2071 int rc = 0;
2072
2073 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2074 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
2075
2076 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
2077
2078 int key_index = 0;
2079 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
2080 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
2081 if (key_index < 0) {
2082 rc = crypt_ftr->failed_decrypt_count;
2083 goto errout;
2084 }
2085 else {
2086 if (is_ice_enabled()) {
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05302087#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
AnilKumar Chimata35850082018-05-11 00:25:09 +05302088 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
2089 real_blkdev, crypto_blkdev, label, 0)) {
2090 SLOGE("Error creating decrypted block device");
2091 rc = -1;
2092 goto errout;
2093 }
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05302094#endif
AnilKumar Chimata35850082018-05-11 00:25:09 +05302095 } else {
2096 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
2097 real_blkdev, crypto_blkdev, label, 0)) {
2098 SLOGE("Error creating decrypted block device");
2099 rc = -1;
2100 goto errout;
2101 }
2102 }
2103 }
2104 }
2105
2106 if (rc == 0) {
2107 crypt_ftr->failed_decrypt_count = 0;
2108 if (orig_failed_decrypt_count != 0) {
2109 put_crypt_ftr_and_key(crypt_ftr);
2110 }
2111
2112 /* Save the name of the crypto block device
2113 * so we can mount it when restarting the framework. */
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05302114#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2115 if (!is_ice_enabled())
2116#endif
AnilKumar Chimata35850082018-05-11 00:25:09 +05302117 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2118 master_key_saved = 1;
2119 }
2120
2121 errout:
2122 return rc;
2123}
2124#endif
2125
2126
Paul Lawrencef4faa572014-01-29 13:31:03 -08002127static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08002128 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002129{
Greg Kaiser59ad0182018-02-16 13:01:36 -08002130 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002131 char crypto_blkdev[MAXPATHLEN];
2132 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002133 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002134 unsigned int orig_failed_decrypt_count;
2135 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002136 int use_keymaster = 0;
2137 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002138 unsigned char* intermediate_key = 0;
2139 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08002140 int N = 1 << crypt_ftr->N_factor;
2141 int r = 1 << crypt_ftr->r_factor;
2142 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002143
Paul Lawrencef4faa572014-01-29 13:31:03 -08002144 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2145 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08002146
Paul Lawrencef4faa572014-01-29 13:31:03 -08002147 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002148 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
2149 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08002150 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002151 rc = -1;
2152 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08002153 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002154 }
2155
Paul Crowleye2ee1522017-09-26 14:05:26 -07002156 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08002157
Paul Lawrence74f29f12014-08-28 15:54:10 -07002158 // Create crypto block device - all (non fatal) code paths
2159 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08002160 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
2161 SLOGE("Error creating decrypted block device\n");
2162 rc = -1;
2163 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002164 }
2165
Paul Lawrence74f29f12014-08-28 15:54:10 -07002166 /* Work out if the problem is the password or the data */
2167 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
2168 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002169
Paul Lawrence74f29f12014-08-28 15:54:10 -07002170 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
2171 crypt_ftr->salt, sizeof(crypt_ftr->salt),
2172 N, r, p, scrypted_intermediate_key,
2173 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002174
Paul Lawrence74f29f12014-08-28 15:54:10 -07002175 // Does the key match the crypto footer?
2176 if (rc == 0 && memcmp(scrypted_intermediate_key,
2177 crypt_ftr->scrypted_intermediate_key,
2178 sizeof(scrypted_intermediate_key)) == 0) {
2179 SLOGI("Password matches");
2180 rc = 0;
2181 } else {
2182 /* Try mounting the file system anyway, just in case the problem's with
2183 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08002184 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
2185 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002186 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07002187 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07002188 SLOGE("Error temp mounting decrypted block device\n");
2189 delete_crypto_blk_dev(label);
2190
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002191 rc = ++crypt_ftr->failed_decrypt_count;
2192 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002193 } else {
2194 /* Success! */
2195 SLOGI("Password did not match but decrypted drive mounted - continue");
2196 umount(tmp_mount_point);
2197 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002198 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002199 }
2200
2201 if (rc == 0) {
2202 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07002203 if (orig_failed_decrypt_count != 0) {
2204 put_crypt_ftr_and_key(crypt_ftr);
2205 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002206
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002207 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07002208 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08002209 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06002210
2211 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07002212 * the key when we want to change the password on it. */
Greg Kaiser59ad0182018-02-16 13:01:36 -08002213 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002214 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06002215 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08002216 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08002217 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002218
Paul Lawrence74f29f12014-08-28 15:54:10 -07002219 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002220 use_keymaster = keymaster_check_compatibility();
2221 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06002222 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002223 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2224 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2225 upgrade = 1;
2226 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002227 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002228 upgrade = 1;
2229 }
2230
2231 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002232 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
AnilKumar Chimata35850082018-05-11 00:25:09 +05302233 crypt_ftr->master_key, crypt_ftr, true);
JP Abgrall7bdfa522013-11-15 13:42:56 -08002234 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002235 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08002236 }
2237 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002238
2239 // Do not fail even if upgrade failed - machine is bootable
2240 // Note that if this code is ever hit, there is a *serious* problem
2241 // since KDFs should never fail. You *must* fix the kdf before
2242 // proceeding!
2243 if (rc) {
2244 SLOGW("Upgrade failed with error %d,"
2245 " but continuing with previous state",
2246 rc);
2247 rc = 0;
2248 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002249 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002250 }
2251
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002252 errout:
2253 if (intermediate_key) {
2254 memset(intermediate_key, 0, intermediate_key_size);
2255 free(intermediate_key);
2256 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002257 return rc;
2258}
2259
Ken Sumrall29d8da82011-05-18 17:20:07 -07002260/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002261 * Called by vold when it's asked to mount an encrypted external
2262 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002263 * as any metadata is been stored in a separate, small partition. We
2264 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07002265 *
2266 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002267 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07002268int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002269 const unsigned char* key, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002270 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002271 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002272 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002273 return -1;
2274 }
2275
2276 unsigned long nr_sec = 0;
2277 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002278 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002279
Ken Sumrall29d8da82011-05-18 17:20:07 -07002280 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002281 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002282 return -1;
2283 }
2284
Jeff Sharkey9c484982015-03-31 10:35:33 -07002285 struct crypt_mnt_ftr ext_crypt_ftr;
2286 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2287 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002288 ext_crypt_ftr.keysize = cryptfs_get_keysize();
2289 strlcpy((char*) ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002290 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002291 uint32_t flags = 0;
2292 if (e4crypt_is_native() &&
2293 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2294 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002295
Paul Crowley385cb8c2018-03-29 13:27:23 -07002296 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07002297}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002298
Jeff Sharkey9c484982015-03-31 10:35:33 -07002299/*
2300 * Called by vold when it's asked to unmount an encrypted external
2301 * storage volume.
2302 */
2303int cryptfs_revert_ext_volume(const char* label) {
2304 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002305}
2306
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002307int cryptfs_crypto_complete(void)
2308{
2309 return do_crypto_complete("/data");
2310}
2311
Paul Lawrencef4faa572014-01-29 13:31:03 -08002312int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2313{
2314 char encrypted_state[PROPERTY_VALUE_MAX];
2315 property_get("ro.crypto.state", encrypted_state, "");
2316 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2317 SLOGE("encrypted fs already validated or not running with encryption,"
2318 " aborting");
2319 return -1;
2320 }
2321
2322 if (get_crypt_ftr_and_key(crypt_ftr)) {
2323 SLOGE("Error getting crypt footer and key");
2324 return -1;
2325 }
2326
2327 return 0;
2328}
2329
AnilKumar Chimata35850082018-05-11 00:25:09 +05302330#ifdef CONFIG_HW_DISK_ENCRYPTION
2331int cryptfs_check_passwd_hw(const char* passwd)
2332{
2333 struct crypt_mnt_ftr crypt_ftr;
2334 int rc;
2335 unsigned char master_key[KEY_LEN_BYTES];
2336
2337 /* get key */
2338 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2339 SLOGE("Error getting crypt footer and key");
2340 return -1;
2341 }
2342
2343 /*
2344 * in case of manual encryption (from GUI), the encryption is done with
2345 * default password
2346 */
2347 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2348 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2349 * which was created with actual password before reboot.
2350 */
2351 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2352 if (rc) {
2353 SLOGE("password doesn't match");
2354 rc = ++crypt_ftr.failed_decrypt_count;
2355 put_crypt_ftr_and_key(&crypt_ftr);
2356 return rc;
2357 }
2358
2359 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2360 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2361
2362 if (rc) {
2363 SLOGE("Default password did not match on reboot encryption");
2364 return rc;
2365 }
2366
2367 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2368 put_crypt_ftr_and_key(&crypt_ftr);
2369 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2370 if (rc) {
2371 SLOGE("Could not change password on reboot encryption");
2372 return rc;
2373 }
2374 } else
2375 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2376 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2377
2378 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2379 cryptfs_clear_password();
2380 password = strdup(passwd);
2381 struct timespec now;
2382 clock_gettime(CLOCK_BOOTTIME, &now);
2383 password_expiry_time = now.tv_sec + password_max_age_seconds;
2384 }
2385
2386 return rc;
2387}
2388#endif
2389
Wei Wang4375f1b2017-02-24 17:43:01 -08002390int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002391{
Paul Lawrence05335c32015-03-05 09:46:23 -08002392 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00002393 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002394 SLOGE("cryptfs_check_passwd not valid for file encryption");
2395 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002396 }
2397
Paul Lawrencef4faa572014-01-29 13:31:03 -08002398 struct crypt_mnt_ftr crypt_ftr;
2399 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002400
Paul Lawrencef4faa572014-01-29 13:31:03 -08002401 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002402 if (rc) {
2403 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002404 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002405 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002406
AnilKumar Chimata35850082018-05-11 00:25:09 +05302407#ifdef CONFIG_HW_DISK_ENCRYPTION
2408 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2409 return cryptfs_check_passwd_hw(passwd);
2410#endif
2411
Paul Lawrence3bd36d52015-06-09 13:37:44 -07002412 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002413 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
AnilKumar Chimata35850082018-05-11 00:25:09 +05302414
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002415 if (rc) {
2416 SLOGE("Password did not match");
2417 return rc;
2418 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002419
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002420 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2421 // Here we have a default actual password but a real password
2422 // we must test against the scrypted value
2423 // First, we must delete the crypto block device that
2424 // test_mount_encrypted_fs leaves behind as a side effect
2425 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2426 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2427 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2428 if (rc) {
2429 SLOGE("Default password did not match on reboot encryption");
2430 return rc;
2431 }
2432
2433 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2434 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata35850082018-05-11 00:25:09 +05302435 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002436 if (rc) {
2437 SLOGE("Could not change password on reboot encryption");
2438 return rc;
2439 }
2440 }
2441
2442 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002443 cryptfs_clear_password();
2444 password = strdup(passwd);
2445 struct timespec now;
2446 clock_gettime(CLOCK_BOOTTIME, &now);
2447 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002448 }
2449
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002450 return rc;
2451}
2452
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002453int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07002454{
2455 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002456 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002457 char encrypted_state[PROPERTY_VALUE_MAX];
2458 int rc;
2459
2460 property_get("ro.crypto.state", encrypted_state, "");
2461 if (strcmp(encrypted_state, "encrypted") ) {
2462 SLOGE("device not encrypted, aborting");
2463 return -2;
2464 }
2465
2466 if (!master_key_saved) {
2467 SLOGE("encrypted fs not yet mounted, aborting");
2468 return -1;
2469 }
2470
2471 if (!saved_mount_point) {
2472 SLOGE("encrypted fs failed to save mount point, aborting");
2473 return -1;
2474 }
2475
Ken Sumrall160b4d62013-04-22 12:15:39 -07002476 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002477 SLOGE("Error getting crypt footer and key\n");
2478 return -1;
2479 }
2480
2481 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2482 /* If the device has no password, then just say the password is valid */
2483 rc = 0;
2484 } else {
AnilKumar Chimata35850082018-05-11 00:25:09 +05302485#ifdef CONFIG_HW_DISK_ENCRYPTION
2486 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2487 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2488 rc = 0;
2489 else
2490 rc = -1;
2491 } else {
2492 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2493 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2494 /* They match, the password is correct */
2495 rc = 0;
2496 } else {
2497 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2498 sleep(1);
2499 rc = 1;
2500 }
2501 }
2502#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002503 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002504 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2505 /* They match, the password is correct */
2506 rc = 0;
2507 } else {
2508 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2509 sleep(1);
2510 rc = 1;
2511 }
AnilKumar Chimata35850082018-05-11 00:25:09 +05302512#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002513 }
2514
2515 return rc;
2516}
2517
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002518/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002519 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002520 * Presumably, at a minimum, the caller will update the
2521 * filesystem size and crypto_type_name after calling this function.
2522 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002523static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002524{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002525 off64_t off;
2526
2527 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002528 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002529 ftr->major_version = CURRENT_MAJOR_VERSION;
2530 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002531 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002532 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002533
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002534 switch (keymaster_check_compatibility()) {
2535 case 1:
2536 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2537 break;
2538
2539 case 0:
2540 ftr->kdf_type = KDF_SCRYPT;
2541 break;
2542
2543 default:
2544 SLOGE("keymaster_check_compatibility failed");
2545 return -1;
2546 }
2547
Kenny Rootc4c70f12013-06-14 12:11:38 -07002548 get_device_scrypt_params(ftr);
2549
Ken Sumrall160b4d62013-04-22 12:15:39 -07002550 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2551 if (get_crypt_ftr_info(NULL, &off) == 0) {
2552 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2553 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2554 ftr->persist_data_size;
2555 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002556
2557 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002558}
2559
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002560#define FRAMEWORK_BOOT_WAIT 60
2561
Paul Lawrence87999172014-02-20 12:21:31 -08002562static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2563{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002564 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002565 if (fd == -1) {
2566 SLOGE("Error opening file %s", filename);
2567 return -1;
2568 }
2569
2570 char block[CRYPT_INPLACE_BUFSIZE];
2571 memset(block, 0, sizeof(block));
2572 if (unix_read(fd, block, sizeof(block)) < 0) {
2573 SLOGE("Error reading file %s", filename);
2574 close(fd);
2575 return -1;
2576 }
2577
2578 close(fd);
2579
2580 SHA256_CTX c;
2581 SHA256_Init(&c);
2582 SHA256_Update(&c, block, sizeof(block));
2583 SHA256_Final(buf, &c);
2584
2585 return 0;
2586}
2587
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002588static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2589 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08002590 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002591 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002592
Paul Lawrence87999172014-02-20 12:21:31 -08002593 /* The size of the userdata partition, and add in the vold volumes below */
2594 tot_encryption_size = crypt_ftr->fs_size;
2595
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002596 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002597 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002598
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002599 if (rc == ENABLE_INPLACE_ERR_DEV) {
2600 /* Hack for b/17898962 */
2601 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2602 cryptfs_reboot(RebootType::reboot);
2603 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002604
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002605 if (!rc) {
2606 crypt_ftr->encrypted_upto = cur_encryption_done;
2607 }
Paul Lawrence87999172014-02-20 12:21:31 -08002608
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002609 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2610 /* The inplace routine never actually sets the progress to 100% due
2611 * to the round down nature of integer division, so set it here */
2612 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002613 }
2614
2615 return rc;
2616}
2617
Paul Crowleyb64933a2017-10-31 08:25:55 -07002618static int vold_unmountAll(void) {
2619 VolumeManager* vm = VolumeManager::Instance();
2620 return vm->unmountAll();
2621}
2622
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002623int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002624 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002625 unsigned char decrypted_master_key[MAX_KEY_LEN];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002626 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002627 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002628 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002629 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002630 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002631 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002632 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002633 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002634 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002635 bool onlyCreateHeader = false;
AnilKumar Chimata35850082018-05-11 00:25:09 +05302636#ifdef CONFIG_HW_DISK_ENCRYPTION
2637 unsigned char newpw[32];
2638 int key_index = 0;
2639#endif
2640 int index = 0;
2641
Wei Wang4375f1b2017-02-24 17:43:01 -08002642 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002643
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002644 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002645 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2646 /* An encryption was underway and was interrupted */
2647 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2648 crypt_ftr.encrypted_upto = 0;
2649 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002650
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002651 /* At this point, we are in an inconsistent state. Until we successfully
2652 complete encryption, a reboot will leave us broken. So mark the
2653 encryption failed in case that happens.
2654 On successfully completing encryption, remove this flag */
2655 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002656
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002657 put_crypt_ftr_and_key(&crypt_ftr);
2658 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2659 if (!check_ftr_sha(&crypt_ftr)) {
2660 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2661 put_crypt_ftr_and_key(&crypt_ftr);
2662 goto error_unencrypted;
2663 }
2664
2665 /* Doing a reboot-encryption*/
2666 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2667 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2668 rebootEncryption = true;
2669 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002670 } else {
2671 // We don't want to accidentally reference invalid data.
2672 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002673 }
2674
2675 property_get("ro.crypto.state", encrypted_state, "");
2676 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2677 SLOGE("Device is already running encrypted, aborting");
2678 goto error_unencrypted;
2679 }
2680
2681 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002682 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2683 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002684
Ken Sumrall3ed82362011-01-28 23:31:16 -08002685 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002686 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002687 if (fd == -1) {
2688 SLOGE("Cannot open block device %s\n", real_blkdev);
2689 goto error_unencrypted;
2690 }
2691 unsigned long nr_sec;
2692 get_blkdev_size(fd, &nr_sec);
2693 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002694 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2695 goto error_unencrypted;
2696 }
2697 close(fd);
2698
2699 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002700 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002701 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002702 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002703 if (fs_size_sec == 0)
2704 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2705
Paul Lawrence87999172014-02-20 12:21:31 -08002706 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002707
2708 if (fs_size_sec > max_fs_size_sec) {
2709 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2710 goto error_unencrypted;
2711 }
2712 }
2713
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002714 /* Get a wakelock as this may take a while, and we don't want the
2715 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2716 * wants to keep the screen on, it can grab a full wakelock.
2717 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002718 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002719 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2720
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002721 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002722 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002723 */
2724 property_set("vold.decrypt", "trigger_shutdown_framework");
2725 SLOGD("Just asked init to shut down class main\n");
2726
Jeff Sharkey9c484982015-03-31 10:35:33 -07002727 /* Ask vold to unmount all devices that it manages */
2728 if (vold_unmountAll()) {
2729 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002730 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002731
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002732 /* no_ui means we are being called from init, not settings.
2733 Now we always reboot from settings, so !no_ui means reboot
2734 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002735 if (!no_ui) {
2736 /* Try fallback, which is to reboot and try there */
2737 onlyCreateHeader = true;
2738 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2739 if (breadcrumb == 0) {
2740 SLOGE("Failed to create breadcrumb file");
2741 goto error_shutting_down;
2742 }
2743 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002744 }
2745
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002746 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002747 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002748 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002749 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2750 goto error_shutting_down;
2751 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002752
Paul Lawrence87999172014-02-20 12:21:31 -08002753 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2754 crypt_ftr.fs_size = nr_sec
2755 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2756 } else {
2757 crypt_ftr.fs_size = nr_sec;
2758 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002759 /* At this point, we are in an inconsistent state. Until we successfully
2760 complete encryption, a reboot will leave us broken. So mark the
2761 encryption failed in case that happens.
2762 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002763 if (onlyCreateHeader) {
2764 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2765 } else {
2766 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2767 }
Paul Lawrence87999172014-02-20 12:21:31 -08002768 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata35850082018-05-11 00:25:09 +05302769#ifdef CONFIG_HW_DISK_ENCRYPTION
2770 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
2771#else
Greg Kaiser57f9af62018-02-16 13:13:58 -08002772 strlcpy((char *)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(), MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata35850082018-05-11 00:25:09 +05302773#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002774
Paul Lawrence87999172014-02-20 12:21:31 -08002775 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002776 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2777 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002778 SLOGE("Cannot create encrypted master key\n");
2779 goto error_shutting_down;
2780 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002781
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002782 /* Replace scrypted intermediate key if we are preparing for a reboot */
2783 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002784 unsigned char fake_master_key[MAX_KEY_LEN];
2785 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002786 memset(fake_master_key, 0, sizeof(fake_master_key));
2787 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
AnilKumar Chimata35850082018-05-11 00:25:09 +05302788 encrypted_fake_master_key, &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002789 }
2790
Paul Lawrence87999172014-02-20 12:21:31 -08002791 /* Write the key to the end of the partition */
2792 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002793
Paul Lawrence87999172014-02-20 12:21:31 -08002794 /* If any persistent data has been remembered, save it.
2795 * If none, create a valid empty table and save that.
2796 */
2797 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002798 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002799 if (pdata) {
2800 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2801 persist_data = pdata;
2802 }
2803 }
2804 if (persist_data) {
2805 save_persistent_data();
2806 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002807 }
2808
AnilKumar Chimata35850082018-05-11 00:25:09 +05302809 /* When encryption triggered from settings, encryption starts after reboot.
2810 So set the encryption key when the actual encryption starts.
2811 */
2812#ifdef CONFIG_HW_DISK_ENCRYPTION
2813 if (previously_encrypted_upto == 0) {
2814 if (!rebootEncryption)
2815 clear_hw_device_encryption_key();
2816
2817 if (get_keymaster_hw_fde_passwd(
2818 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2819 newpw, crypt_ftr.salt, &crypt_ftr))
2820 key_index = set_hw_device_encryption_key(
2821 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2822 (char*)crypt_ftr.crypto_type_name);
2823 else
2824 key_index = set_hw_device_encryption_key((const char*)newpw,
2825 (char*) crypt_ftr.crypto_type_name);
2826 if (key_index < 0)
2827 goto error_shutting_down;
2828
2829 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2830 put_crypt_ftr_and_key(&crypt_ftr);
2831 }
2832#endif
2833
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002834 if (onlyCreateHeader) {
2835 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002836 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata35850082018-05-11 00:25:09 +05302837 } else {
2838 /* Do extra work for a better UX when doing the long inplace encryption */
2839 /* Now that /data is unmounted, we need to mount a tmpfs
2840 * /data, set a property saying we're doing inplace encryption,
2841 * and restart the framework.
2842 */
2843 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2844 goto error_shutting_down;
2845 }
2846 /* Tells the framework that inplace encryption is starting */
2847 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002848
AnilKumar Chimata35850082018-05-11 00:25:09 +05302849 /* restart the framework. */
2850 /* Create necessary paths on /data */
2851 prep_data_fs();
2852
2853 /* Ugh, shutting down the framework is not synchronous, so until it
2854 * can be fixed, this horrible hack will wait a moment for it all to
2855 * shut down before proceeding. Without it, some devices cannot
2856 * restart the graphics services.
2857 */
2858 sleep(2);
2859
Ajay Dudani87701e22014-09-17 21:02:52 -07002860 /* startup service classes main and late_start */
2861 property_set("vold.decrypt", "trigger_restart_min_framework");
2862 SLOGD("Just triggered restart_min_framework\n");
2863
2864 /* OK, the framework is restarted and will soon be showing a
2865 * progress bar. Time to setup an encrypted mapping, and
2866 * either write a new filesystem, or encrypt in place updating
2867 * the progress bar as we work.
2868 */
2869 }
2870
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002871 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata35850082018-05-11 00:25:09 +05302872#ifdef CONFIG_HW_DISK_ENCRYPTION
2873 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05302874#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2875 strlcpy(crypto_blkdev, real_blkdev, sizeof(crypto_blkdev));
2876#else
AnilKumar Chimata35850082018-05-11 00:25:09 +05302877 create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev, crypto_blkdev,
2878 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05302879#endif
AnilKumar Chimata35850082018-05-11 00:25:09 +05302880 else
2881 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2882 CRYPTO_BLOCK_DEVICE, 0);
2883#else
Ken Sumrall29d8da82011-05-18 17:20:07 -07002884 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002885 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata35850082018-05-11 00:25:09 +05302886#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002887
Paul Lawrence87999172014-02-20 12:21:31 -08002888 /* If we are continuing, check checksums match */
2889 rc = 0;
2890 if (previously_encrypted_upto) {
2891 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05302892#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2893 if (set_ice_param(START_ENCDEC)) {
2894 SLOGE("Failed to set ICE data");
2895 goto error_shutting_down;
2896 }
2897#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002898 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002899
Paul Lawrence87999172014-02-20 12:21:31 -08002900 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2901 sizeof(hash_first_block)) != 0) {
2902 SLOGE("Checksums do not match - trigger wipe");
2903 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002904 }
2905 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002906
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05302907#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2908 if (set_ice_param(START_ENC)) {
2909 SLOGE("Failed to set ICE data");
2910 goto error_shutting_down;
2911 }
2912#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002913 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002914 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002915 previously_encrypted_upto);
2916 }
2917
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05302918#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2919 if (set_ice_param(START_ENCDEC)) {
2920 SLOGE("Failed to set ICE data");
2921 goto error_shutting_down;
2922 }
2923#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002924 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002925 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002926 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2927 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002928 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002929 SLOGE("Error calculating checksum for continuing encryption");
2930 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002931 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002932 }
2933
2934 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05302935#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2936 if (!is_ice_enabled())
2937 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2938#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002939 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimata4d404ad2018-02-11 17:11:24 +05302940#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002941
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002942 if (! rc) {
2943 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002944 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002945
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002946 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002947 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2948 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002949 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002950 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002951
Paul Lawrence6bfed202014-07-28 12:47:22 -07002952 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002953
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002954 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2955 char value[PROPERTY_VALUE_MAX];
2956 property_get("ro.crypto.state", value, "");
2957 if (!strcmp(value, "")) {
2958 /* default encryption - continue first boot sequence */
2959 property_set("ro.crypto.state", "encrypted");
2960 property_set("ro.crypto.type", "block");
2961 release_wake_lock(lockid);
2962 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2963 // Bring up cryptkeeper that will check the password and set it
2964 property_set("vold.decrypt", "trigger_shutdown_framework");
2965 sleep(2);
2966 property_set("vold.encrypt_progress", "");
2967 cryptfs_trigger_restart_min_framework();
2968 } else {
2969 cryptfs_check_passwd(DEFAULT_PASSWORD);
2970 cryptfs_restart_internal(1);
2971 }
2972 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002973 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002974 sleep(2); /* Give the UI a chance to show 100% progress */
2975 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002976 }
Paul Lawrence87999172014-02-20 12:21:31 -08002977 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002978 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002979 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002980 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002981 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002982 char value[PROPERTY_VALUE_MAX];
2983
Ken Sumrall319369a2012-06-27 16:30:18 -07002984 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002985 if (!strcmp(value, "1")) {
2986 /* wipe data if encryption failed */
2987 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002988 std::string err;
2989 const std::vector<std::string> options = {
2990 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2991 };
2992 if (!write_bootloader_message(options, &err)) {
2993 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002994 }
Josh Gaofec44372017-08-28 13:22:55 -07002995 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002996 } else {
2997 /* set property to trigger dialog */
2998 property_set("vold.encrypt_progress", "error_partially_encrypted");
2999 release_wake_lock(lockid);
3000 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003001 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003002 }
3003
Ken Sumrall3ed82362011-01-28 23:31:16 -08003004 /* hrm, the encrypt step claims success, but the reboot failed.
3005 * This should not happen.
3006 * Set the property and return. Hope the framework can deal with it.
3007 */
3008 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003009 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003010 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003011
3012error_unencrypted:
3013 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003014 if (lockid[0]) {
3015 release_wake_lock(lockid);
3016 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003017 return -1;
3018
3019error_shutting_down:
3020 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3021 * but the framework is stopped and not restarted to show the error, so it's up to
3022 * vold to restart the system.
3023 */
3024 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07003025 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003026
3027 /* shouldn't get here */
3028 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003029 if (lockid[0]) {
3030 release_wake_lock(lockid);
3031 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003032 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003033}
3034
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003035int cryptfs_enable(int type, const char* passwd, int no_ui) {
3036 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003037}
3038
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003039int cryptfs_enable_default(int no_ui) {
3040 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003041}
3042
AnilKumar Chimata35850082018-05-11 00:25:09 +05303043int cryptfs_changepw(int crypt_type, const char *currentpw, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003044{
Paul Crowley38132a12016-02-09 09:50:32 +00003045 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003046 SLOGE("cryptfs_changepw not valid for file encryption");
3047 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003048 }
3049
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003050 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003051 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003052
3053 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003054 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003055 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003056 return -1;
3057 }
3058
Paul Lawrencef4faa572014-01-29 13:31:03 -08003059 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3060 SLOGE("Invalid crypt_type %d", crypt_type);
3061 return -1;
3062 }
3063
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003064 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003065 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003066 SLOGE("Error getting crypt footer and key");
3067 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003068 }
3069
AnilKumar Chimata35850082018-05-11 00:25:09 +05303070#ifdef CONFIG_HW_DISK_ENCRYPTION
3071 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
3072 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
3073 else {
3074 crypt_ftr.crypt_type = crypt_type;
3075
3076 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
3077 DEFAULT_PASSWORD : newpw,
3078 crypt_ftr.salt,
3079 saved_master_key,
3080 crypt_ftr.master_key,
3081 &crypt_ftr, false);
3082 if (rc) {
3083 SLOGE("Encrypt master key failed: %d", rc);
3084 return -1;
3085 }
3086 /* save the key */
3087 put_crypt_ftr_and_key(&crypt_ftr);
3088
3089 return 0;
3090 }
3091#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08003092 crypt_ftr.crypt_type = crypt_type;
3093
JP Abgrall933216c2015-02-11 13:44:32 -08003094 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003095 : newpw,
3096 crypt_ftr.salt,
3097 saved_master_key,
3098 crypt_ftr.master_key,
AnilKumar Chimata35850082018-05-11 00:25:09 +05303099 &crypt_ftr, false);
JP Abgrall933216c2015-02-11 13:44:32 -08003100 if (rc) {
3101 SLOGE("Encrypt master key failed: %d", rc);
3102 return -1;
3103 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003104 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003105 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003106
3107 return 0;
AnilKumar Chimata35850082018-05-11 00:25:09 +05303108#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003109}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003110
AnilKumar Chimata35850082018-05-11 00:25:09 +05303111#ifdef CONFIG_HW_DISK_ENCRYPTION
3112int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
3113{
3114 struct crypt_mnt_ftr crypt_ftr;
3115 int rc;
3116 int previous_type;
3117
3118 /* get key */
3119 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3120 SLOGE("Error getting crypt footer and key");
3121 return -1;
3122 }
3123
3124 previous_type = crypt_ftr.crypt_type;
3125 int rc1;
3126 unsigned char tmp_curpw[32] = {0};
3127 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3128 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3129 crypt_ftr.salt, &crypt_ftr);
3130
3131 crypt_ftr.crypt_type = crypt_type;
3132
3133 int ret, rc2;
3134 unsigned char tmp_newpw[32] = {0};
3135
3136 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3137 DEFAULT_PASSWORD : newpw , tmp_newpw,
3138 crypt_ftr.salt, &crypt_ftr);
3139
3140 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3141 ret = update_hw_device_encryption_key(
3142 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3143 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3144 (char*)crypt_ftr.crypto_type_name);
3145 if (ret) {
3146 SLOGE("Error updating device encryption hardware key ret %d", ret);
3147 return -1;
3148 } else {
3149 SLOGI("Encryption hardware key updated");
3150 }
3151 }
3152
3153 /* save the key */
3154 put_crypt_ftr_and_key(&crypt_ftr);
3155 return 0;
3156}
3157#endif
3158
Rubin Xu85c01f92014-10-13 12:49:54 +01003159static unsigned int persist_get_max_entries(int encrypted) {
3160 struct crypt_mnt_ftr crypt_ftr;
3161 unsigned int dsize;
3162 unsigned int max_persistent_entries;
3163
3164 /* If encrypted, use the values from the crypt_ftr, otherwise
3165 * use the values for the current spec.
3166 */
3167 if (encrypted) {
3168 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3169 return -1;
3170 }
3171 dsize = crypt_ftr.persist_data_size;
3172 } else {
3173 dsize = CRYPT_PERSIST_DATA_SIZE;
3174 }
3175
3176 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3177 sizeof(struct crypt_persist_entry);
3178
3179 return max_persistent_entries;
3180}
3181
3182static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003183{
3184 unsigned int i;
3185
3186 if (persist_data == NULL) {
3187 return -1;
3188 }
3189 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3190 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3191 /* We found it! */
3192 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3193 return 0;
3194 }
3195 }
3196
3197 return -1;
3198}
3199
Rubin Xu85c01f92014-10-13 12:49:54 +01003200static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003201{
3202 unsigned int i;
3203 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003204 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003205
3206 if (persist_data == NULL) {
3207 return -1;
3208 }
3209
Rubin Xu85c01f92014-10-13 12:49:54 +01003210 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003211
3212 num = persist_data->persist_valid_entries;
3213
3214 for (i = 0; i < num; i++) {
3215 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3216 /* We found an existing entry, update it! */
3217 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3218 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3219 return 0;
3220 }
3221 }
3222
3223 /* We didn't find it, add it to the end, if there is room */
3224 if (persist_data->persist_valid_entries < max_persistent_entries) {
3225 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3226 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3227 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3228 persist_data->persist_valid_entries++;
3229 return 0;
3230 }
3231
3232 return -1;
3233}
3234
Rubin Xu85c01f92014-10-13 12:49:54 +01003235/**
3236 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3237 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3238 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003239int match_multi_entry(const char *key, const char *field, unsigned index) {
3240 std::string key_ = key;
3241 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003242
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003243 std::string parsed_field;
3244 unsigned parsed_index;
3245
3246 std::string::size_type split = key_.find_last_of('_');
3247 if (split == std::string::npos) {
3248 parsed_field = key_;
3249 parsed_index = 0;
3250 } else {
3251 parsed_field = key_.substr(0, split);
3252 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003253 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003254
3255 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003256}
3257
3258/*
3259 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3260 * remaining entries starting from index will be deleted.
3261 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3262 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3263 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3264 *
3265 */
3266static int persist_del_keys(const char *fieldname, unsigned index)
3267{
3268 unsigned int i;
3269 unsigned int j;
3270 unsigned int num;
3271
3272 if (persist_data == NULL) {
3273 return PERSIST_DEL_KEY_ERROR_OTHER;
3274 }
3275
3276 num = persist_data->persist_valid_entries;
3277
3278 j = 0; // points to the end of non-deleted entries.
3279 // Filter out to-be-deleted entries in place.
3280 for (i = 0; i < num; i++) {
3281 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3282 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3283 j++;
3284 }
3285 }
3286
3287 if (j < num) {
3288 persist_data->persist_valid_entries = j;
3289 // Zeroise the remaining entries
3290 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3291 return PERSIST_DEL_KEY_OK;
3292 } else {
3293 // Did not find an entry matching the given fieldname
3294 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3295 }
3296}
3297
3298static int persist_count_keys(const char *fieldname)
3299{
3300 unsigned int i;
3301 unsigned int count;
3302
3303 if (persist_data == NULL) {
3304 return -1;
3305 }
3306
3307 count = 0;
3308 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3309 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3310 count++;
3311 }
3312 }
3313
3314 return count;
3315}
3316
Ken Sumrall160b4d62013-04-22 12:15:39 -07003317/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003318int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003319{
Paul Crowley38132a12016-02-09 09:50:32 +00003320 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003321 SLOGE("Cannot get field when file encrypted");
3322 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003323 }
3324
Ken Sumrall160b4d62013-04-22 12:15:39 -07003325 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003326 /* CRYPTO_GETFIELD_OK is success,
3327 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3328 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3329 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003330 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003331 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3332 int i;
3333 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003334
3335 if (persist_data == NULL) {
3336 load_persistent_data();
3337 if (persist_data == NULL) {
3338 SLOGE("Getfield error, cannot load persistent data");
3339 goto out;
3340 }
3341 }
3342
Rubin Xu85c01f92014-10-13 12:49:54 +01003343 // Read value from persistent entries. If the original value is split into multiple entries,
3344 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003345 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003346 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3347 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3348 // value too small
3349 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3350 goto out;
3351 }
3352 rc = CRYPTO_GETFIELD_OK;
3353
3354 for (i = 1; /* break explicitly */; i++) {
3355 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3356 (int) sizeof(temp_field)) {
3357 // If the fieldname is very long, we stop as soon as it begins to overflow the
3358 // maximum field length. At this point we have in fact fully read out the original
3359 // value because cryptfs_setfield would not allow fields with longer names to be
3360 // written in the first place.
3361 break;
3362 }
3363 if (!persist_get_key(temp_field, temp_value)) {
3364 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3365 // value too small.
3366 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3367 goto out;
3368 }
3369 } else {
3370 // Exhaust all entries.
3371 break;
3372 }
3373 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003374 } else {
3375 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003376 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003377 }
3378
3379out:
3380 return rc;
3381}
3382
3383/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003384int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003385{
Paul Crowley38132a12016-02-09 09:50:32 +00003386 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003387 SLOGE("Cannot set field when file encrypted");
3388 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003389 }
3390
Ken Sumrall160b4d62013-04-22 12:15:39 -07003391 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003392 /* 0 is success, negative values are error */
3393 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003394 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003395 unsigned int field_id;
3396 char temp_field[PROPERTY_KEY_MAX];
3397 unsigned int num_entries;
3398 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003399
3400 if (persist_data == NULL) {
3401 load_persistent_data();
3402 if (persist_data == NULL) {
3403 SLOGE("Setfield error, cannot load persistent data");
3404 goto out;
3405 }
3406 }
3407
3408 property_get("ro.crypto.state", encrypted_state, "");
3409 if (!strcmp(encrypted_state, "encrypted") ) {
3410 encrypted = 1;
3411 }
3412
Rubin Xu85c01f92014-10-13 12:49:54 +01003413 // Compute the number of entries required to store value, each entry can store up to
3414 // (PROPERTY_VALUE_MAX - 1) chars
3415 if (strlen(value) == 0) {
3416 // Empty value also needs one entry to store.
3417 num_entries = 1;
3418 } else {
3419 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3420 }
3421
3422 max_keylen = strlen(fieldname);
3423 if (num_entries > 1) {
3424 // Need an extra "_%d" suffix.
3425 max_keylen += 1 + log10(num_entries);
3426 }
3427 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3428 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003429 goto out;
3430 }
3431
Rubin Xu85c01f92014-10-13 12:49:54 +01003432 // Make sure we have enough space to write the new value
3433 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3434 persist_get_max_entries(encrypted)) {
3435 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3436 goto out;
3437 }
3438
3439 // Now that we know persist_data has enough space for value, let's delete the old field first
3440 // to make up space.
3441 persist_del_keys(fieldname, 0);
3442
3443 if (persist_set_key(fieldname, value, encrypted)) {
3444 // fail to set key, should not happen as we have already checked the available space
3445 SLOGE("persist_set_key() error during setfield()");
3446 goto out;
3447 }
3448
3449 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003450 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003451
3452 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3453 // fail to set key, should not happen as we have already checked the available space.
3454 SLOGE("persist_set_key() error during setfield()");
3455 goto out;
3456 }
3457 }
3458
Ken Sumrall160b4d62013-04-22 12:15:39 -07003459 /* If we are running encrypted, save the persistent data now */
3460 if (encrypted) {
3461 if (save_persistent_data()) {
3462 SLOGE("Setfield error, cannot save persistent data");
3463 goto out;
3464 }
3465 }
3466
Rubin Xu85c01f92014-10-13 12:49:54 +01003467 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003468
3469out:
3470 return rc;
3471}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003472
3473/* Checks userdata. Attempt to mount the volume if default-
3474 * encrypted.
3475 * On success trigger next init phase and return 0.
3476 * Currently do not handle failure - see TODO below.
3477 */
3478int cryptfs_mount_default_encrypted(void)
3479{
Paul Lawrence84274cc2016-04-15 15:41:33 -07003480 int crypt_type = cryptfs_get_password_type();
3481 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3482 SLOGE("Bad crypt type - error");
3483 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3484 SLOGD("Password is not default - "
3485 "starting min framework to prompt");
3486 property_set("vold.decrypt", "trigger_restart_min_framework");
3487 return 0;
3488 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3489 SLOGD("Password is default - restarting filesystem");
3490 cryptfs_restart_internal(0);
3491 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003492 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003493 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003494 }
3495
Paul Lawrence6bfed202014-07-28 12:47:22 -07003496 /** Corrupt. Allow us to boot into framework, which will detect bad
3497 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003498 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003499 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003500 return 0;
3501}
3502
3503/* Returns type of the password, default, pattern, pin or password.
3504 */
3505int cryptfs_get_password_type(void)
3506{
Paul Crowley38132a12016-02-09 09:50:32 +00003507 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003508 SLOGE("cryptfs_get_password_type not valid for file encryption");
3509 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003510 }
3511
Paul Lawrencef4faa572014-01-29 13:31:03 -08003512 struct crypt_mnt_ftr crypt_ftr;
3513
3514 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3515 SLOGE("Error getting crypt footer and key\n");
3516 return -1;
3517 }
3518
Paul Lawrence6bfed202014-07-28 12:47:22 -07003519 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3520 return -1;
3521 }
3522
Paul Lawrencef4faa572014-01-29 13:31:03 -08003523 return crypt_ftr.crypt_type;
3524}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003525
Paul Lawrence05335c32015-03-05 09:46:23 -08003526const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003527{
Paul Crowley38132a12016-02-09 09:50:32 +00003528 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003529 SLOGE("cryptfs_get_password not valid for file encryption");
3530 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003531 }
3532
Paul Lawrence399317e2014-03-10 13:20:50 -07003533 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003534 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003535 if (now.tv_sec < password_expiry_time) {
3536 return password;
3537 } else {
3538 cryptfs_clear_password();
3539 return 0;
3540 }
3541}
3542
3543void cryptfs_clear_password()
3544{
3545 if (password) {
3546 size_t len = strlen(password);
3547 memset(password, 0, len);
3548 free(password);
3549 password = 0;
3550 password_expiry_time = 0;
3551 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003552}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003553
Paul Lawrence0c247462015-10-29 10:30:57 -07003554int cryptfs_isConvertibleToFBE()
3555{
Paul Crowleye2ee1522017-09-26 14:05:26 -07003556 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07003557 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
3558}
AnilKumar Chimata35850082018-05-11 00:25:09 +05303559
3560int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3561{
3562 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3563 SLOGE("Failed to initialize crypt_ftr");
3564 return -1;
3565 }
3566
3567 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3568 crypt_ftr->salt, crypt_ftr)) {
3569 SLOGE("Cannot create encrypted master key\n");
3570 return -1;
3571 }
3572
3573 //crypt_ftr->keysize = key_length / 8;
3574 return 0;
3575}
3576
3577int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3578 unsigned char* master_key)
3579{
3580 int rc;
3581
3582 unsigned char* intermediate_key = 0;
3583 size_t intermediate_key_size = 0;
3584
3585 if (password == 0 || *password == 0) {
3586 password = DEFAULT_PASSWORD;
3587 }
3588
3589 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3590 &intermediate_key_size);
3591
3592 if (rc) {
3593 SLOGE("Can't calculate intermediate key");
3594 return rc;
3595 }
3596
3597 int N = 1 << ftr->N_factor;
3598 int r = 1 << ftr->r_factor;
3599 int p = 1 << ftr->p_factor;
3600
3601 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3602
3603 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3604 ftr->salt, sizeof(ftr->salt), N, r, p,
3605 scrypted_intermediate_key,
3606 sizeof(scrypted_intermediate_key));
3607
3608 free(intermediate_key);
3609
3610 if (rc) {
3611 SLOGE("Can't scrypt intermediate key");
3612 return rc;
3613 }
3614
3615 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3616 intermediate_key_size);
3617}