blob: 8a63d51a0e02c45937d547ca4c6700a2add6c494 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
Logan Chiend557d762018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
Daniel Rosenberg4f684712018-08-28 01:58:49 -070027#include "Checkpoint.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "EncryptInplace.h"
29#include "Ext4Crypt.h"
30#include "Keymaster.h"
31#include "Process.h"
32#include "ScryptParameters.h"
33#include "VoldUtil.h"
34#include "VolumeManager.h"
35#include "secontext.h"
36
Logan Chien3f2b1222018-05-02 11:39:03 +080037#include <android-base/properties.h>
Logan Chiend557d762018-05-02 11:36:45 +080038#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080039#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080040#include <cutils/properties.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>
Logan Chien3f2b1222018-05-02 11:39:03 +080043#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080045#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080046#include <log/log.h>
Ken Sumralle550f782013-08-20 13:48:23 -070047#include <logwrap/logwrap.h>
Logan Chiend557d762018-05-02 11:36:45 +080048#include <openssl/evp.h>
49#include <openssl/sha.h>
Ken Sumrallc290eaf2011-03-07 23:40:35 -080050#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080051
52#include <ctype.h>
53#include <errno.h>
54#include <fcntl.h>
55#include <inttypes.h>
56#include <libgen.h>
57#include <linux/dm-ioctl.h>
58#include <linux/kdev_t.h>
59#include <math.h>
60#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
63#include <sys/ioctl.h>
64#include <sys/mount.h>
65#include <sys/param.h>
66#include <sys/stat.h>
67#include <sys/types.h>
68#include <sys/wait.h>
69#include <time.h>
70#include <unistd.h>
71
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053072#ifdef CONFIG_HW_DISK_ENCRYPTION
73#include <cryptfs_hw.h>
74#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080075extern "C" {
76#include <crypto_scrypt.h>
77}
Mark Salyzyn3e971272014-01-21 13:27:04 -080078
Mark Salyzyn5eecc442014-02-12 14:16:14 -080079#define UNUSED __attribute__((unused))
80
Ken Sumrall8f869aa2010-12-03 03:47:09 -080081#define DM_CRYPT_BUF_SIZE 4096
82
Jason parks70a4b3f2011-01-28 10:10:47 -060083#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080084
85constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
86constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070087constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080088
89// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070090static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060091
Paul Crowley14c8c072018-09-18 13:30:21 -070092#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070093
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053094#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -070095#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080096
Paul Lawrence3d99eba2015-11-20 07:07:19 -080097#define CRYPTO_BLOCK_DEVICE "userdata"
98
99#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
100
Ken Sumrall29d8da82011-05-18 17:20:07 -0700101#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700102#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700103
Ken Sumralle919efe2012-09-29 17:07:41 -0700104#define TABLE_LOAD_RETRIES 10
105
Shawn Willden47ba10d2014-09-03 17:07:06 -0600106#define RSA_KEY_SIZE 2048
107#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
108#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600109#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530110#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700111
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700112#define RETRY_MOUNT_ATTEMPTS 10
113#define RETRY_MOUNT_DELAY_SECONDS 1
114
Paul Crowley5afbc622017-11-27 09:42:17 -0800115#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
116
Paul Crowley73473332017-11-21 15:43:51 -0800117static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
118
Greg Kaiser59ad0182018-02-16 13:01:36 -0800119static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700120static char* saved_mount_point;
121static int master_key_saved = 0;
122static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800123
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530124static int previous_type;
125
126#ifdef CONFIG_HW_DISK_ENCRYPTION
127static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
128 unsigned char *ikey, void *params);
129static void convert_key_to_hex_ascii(const unsigned char *master_key,
130 unsigned int keysize, char *master_key_ascii);
131static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
132static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
133 const char *passwd, const char *mount_point, const char *label);
134int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
135 const char *newpw);
136int cryptfs_check_passwd_hw(char *passwd);
137int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
138 unsigned char* master_key);
139
140static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
141 unsigned int keysize, char *master_key_ascii)
142{
143 unsigned int i, a;
144 unsigned char nibble;
145
146 for (i = 0, a = 0; i < keysize; i++, a += 2) {
147 /* For each byte, write out two ascii hex digits */
148 nibble = (master_key[i] >> 4) & 0xf;
149 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
150
151 nibble = master_key[i] & 0xf;
152 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
153 }
154
155 /* Add the null termination */
156 master_key_ascii[a] = '\0';
157}
158
159static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
160 unsigned char* salt,
161 const struct crypt_mnt_ftr *ftr)
162{
163 /* if newpw updated, return 0
164 * if newpw not updated return -1
165 */
166 int rc = -1;
167
168 if (should_use_keymaster()) {
169 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
170 SLOGE("scrypt failed");
171 } else {
172 rc = 0;
173 }
174 }
175
176 return rc;
177}
178
179static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
180{
181 unsigned char newpw[32] = {0};
182 int key_index;
183 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
184 key_index = set_hw_device_encryption_key(passwd,
185 (char*) crypt_ftr->crypto_type_name);
186 else
187 key_index = set_hw_device_encryption_key((const char*)newpw,
188 (char*) crypt_ftr->crypto_type_name);
189 return key_index;
190}
191
192static int verify_and_update_hw_fde_passwd(const char *passwd,
193 struct crypt_mnt_ftr* crypt_ftr)
194{
195 char* new_passwd = NULL;
196 unsigned char newpw[32] = {0};
197 int key_index = -1;
198 int passwd_updated = -1;
199 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
200
201 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
202 if (key_index < 0) {
203 ++crypt_ftr->failed_decrypt_count;
204
205 if (ascii_passwd_updated) {
206 SLOGI("Ascii password was updated");
207 } else {
208 /* Code in else part would execute only once:
209 * When device is upgraded from L->M release.
210 * Once upgraded, code flow should never come here.
211 * L release passed actual password in hex, so try with hex
212 * Each nible of passwd was encoded as a byte, so allocate memory
213 * twice of password len plus one more byte for null termination
214 */
215 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
216 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
217 if (new_passwd == NULL) {
218 SLOGE("System out of memory. Password verification incomplete");
219 goto out;
220 }
221 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
222 } else {
223 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
224 if (new_passwd == NULL) {
225 SLOGE("System out of memory. Password verification incomplete");
226 goto out;
227 }
228 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
229 strlen(passwd), new_passwd);
230 }
231 key_index = set_hw_device_encryption_key((const char*)new_passwd,
232 (char*) crypt_ftr->crypto_type_name);
233 if (key_index >=0) {
234 crypt_ftr->failed_decrypt_count = 0;
235 SLOGI("Hex password verified...will try to update with Ascii value");
236 /* Before updating password, tie that with keymaster to tie with ROT */
237
238 if (get_keymaster_hw_fde_passwd(passwd, newpw,
239 crypt_ftr->salt, crypt_ftr)) {
240 passwd_updated = update_hw_device_encryption_key(new_passwd,
241 passwd, (char*)crypt_ftr->crypto_type_name);
242 } else {
243 passwd_updated = update_hw_device_encryption_key(new_passwd,
244 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
245 }
246
247 if (passwd_updated >= 0) {
248 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
249 SLOGI("Ascii password recorded and updated");
250 } else {
251 SLOGI("Passwd verified, could not update...Will try next time");
252 }
253 } else {
254 ++crypt_ftr->failed_decrypt_count;
255 }
256 free(new_passwd);
257 }
258 } else {
259 if (!ascii_passwd_updated)
260 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
261 }
262out:
263 // update footer before leaving
264 put_crypt_ftr_and_key(crypt_ftr);
265 return key_index;
266}
267#endif
268
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700269/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700270static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000271 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700272}
273
274/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700275static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800276 if (ftr->keymaster_blob_size) {
277 SLOGI("Already have key");
278 return 0;
279 }
280
Paul Crowley14c8c072018-09-18 13:30:21 -0700281 int rc = keymaster_create_key_for_cryptfs_scrypt(
282 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
283 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000284 if (rc) {
285 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800286 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000287 ftr->keymaster_blob_size = 0;
288 }
289 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700290 return -1;
291 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000292 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700293}
294
Shawn Willdene17a9c42014-09-08 13:04:08 -0600295/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700296static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
297 const size_t object_size, unsigned char** signature,
298 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600299 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600300 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600301 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600302
Shawn Willdene17a9c42014-09-08 13:04:08 -0600303 // To sign a message with RSA, the message must satisfy two
304 // constraints:
305 //
306 // 1. The message, when interpreted as a big-endian numeric value, must
307 // be strictly less than the public modulus of the RSA key. Note
308 // that because the most significant bit of the public modulus is
309 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
310 // key), an n-bit message with most significant bit 0 always
311 // satisfies this requirement.
312 //
313 // 2. The message must have the same length in bits as the public
314 // modulus of the RSA key. This requirement isn't mathematically
315 // necessary, but is necessary to ensure consistency in
316 // implementations.
317 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600318 case KDF_SCRYPT_KEYMASTER:
319 // This ensures the most significant byte of the signed message
320 // is zero. We could have zero-padded to the left instead, but
321 // this approach is slightly more robust against changes in
322 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600323 // so) because we really should be using a proper deterministic
324 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800325 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600326 SLOGI("Signing safely-padded object");
327 break;
328 default:
329 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000330 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600331 }
Paul Crowley73473332017-11-21 15:43:51 -0800332 for (;;) {
333 auto result = keymaster_sign_object_for_cryptfs_scrypt(
334 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
335 to_sign_size, signature, signature_size);
336 switch (result) {
337 case KeymasterSignResult::ok:
338 return 0;
339 case KeymasterSignResult::upgrade:
340 break;
341 default:
342 return -1;
343 }
344 SLOGD("Upgrading key");
345 if (keymaster_upgrade_key_for_cryptfs_scrypt(
346 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
347 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
348 &ftr->keymaster_blob_size) != 0) {
349 SLOGE("Failed to upgrade key");
350 return -1;
351 }
352 if (put_crypt_ftr_and_key(ftr) != 0) {
353 SLOGE("Failed to write upgraded key to disk");
354 }
355 SLOGD("Key upgraded successfully");
356 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600357}
358
Paul Lawrence399317e2014-03-10 13:20:50 -0700359/* Store password when userdata is successfully decrypted and mounted.
360 * Cleared by cryptfs_clear_password
361 *
362 * To avoid a double prompt at boot, we need to store the CryptKeeper
363 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
364 * Since the entire framework is torn down and rebuilt after encryption,
365 * we have to use a daemon or similar to store the password. Since vold
366 * is secured against IPC except from system processes, it seems a reasonable
367 * place to store this.
368 *
369 * password should be cleared once it has been used.
370 *
371 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800372 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700373static char* password = 0;
374static int password_expiry_time = 0;
375static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800376
Paul Crowley14c8c072018-09-18 13:30:21 -0700377enum class RebootType { reboot, recovery, shutdown };
378static void cryptfs_reboot(RebootType rt) {
379 switch (rt) {
380 case RebootType::reboot:
381 property_set(ANDROID_RB_PROPERTY, "reboot");
382 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800383
Paul Crowley14c8c072018-09-18 13:30:21 -0700384 case RebootType::recovery:
385 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
386 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800387
Paul Crowley14c8c072018-09-18 13:30:21 -0700388 case RebootType::shutdown:
389 property_set(ANDROID_RB_PROPERTY, "shutdown");
390 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700391 }
Paul Lawrence87999172014-02-20 12:21:31 -0800392
Ken Sumralladfba362013-06-04 16:37:52 -0700393 sleep(20);
394
395 /* Shouldn't get here, reboot should happen before sleep times out */
396 return;
397}
398
Paul Crowley14c8c072018-09-18 13:30:21 -0700399static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800400 memset(io, 0, dataSize);
401 io->data_size = dataSize;
402 io->data_start = sizeof(struct dm_ioctl);
403 io->version[0] = 4;
404 io->version[1] = 0;
405 io->version[2] = 0;
406 io->flags = flags;
407 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100408 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800409 }
410}
411
Greg Kaiser38723f22018-02-16 13:35:35 -0800412namespace {
413
414struct CryptoType;
415
416// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700417const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800418
419struct CryptoType {
420 // We should only be constructing CryptoTypes as part of
421 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
422 // which isn't pure or fully protected as a concession to being able to
423 // do it all at compile time. Add new CryptoTypes in
424 // supported_crypto_types[] below.
425 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
426 constexpr CryptoType set_keysize(uint32_t size) const {
427 return CryptoType(this->property_name, this->crypto_name, size);
428 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700429 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800430 return CryptoType(property, this->crypto_name, this->keysize);
431 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700432 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800433 return CryptoType(this->property_name, crypto, this->keysize);
434 }
435
Paul Crowley14c8c072018-09-18 13:30:21 -0700436 constexpr const char* get_property_name() const { return property_name; }
437 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800438 constexpr uint32_t get_keysize() const { return keysize; }
439
Paul Crowley14c8c072018-09-18 13:30:21 -0700440 private:
441 const char* property_name;
442 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800443 uint32_t keysize;
444
Paul Crowley14c8c072018-09-18 13:30:21 -0700445 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800446 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700447 friend const CryptoType& get_crypto_type();
448 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800449};
450
451// We only want to parse this read-only property once. But we need to wait
452// until the system is initialized before we can read it. So we use a static
453// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700454const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800455 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
456 return crypto_type;
457}
458
459constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700460 .set_property_name("AES-128-CBC")
461 .set_crypto_name("aes-cbc-essiv:sha256")
462 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800463
464constexpr CryptoType supported_crypto_types[] = {
465 default_crypto_type,
Greg Kaiser38723f22018-02-16 13:35:35 -0800466 // Add new CryptoTypes here. Order is not important.
467};
468
Greg Kaiser38723f22018-02-16 13:35:35 -0800469// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
470// We confirm all supported_crypto_types have a small enough keysize and
471// had both set_property_name() and set_crypto_name() called.
472
473template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700474constexpr size_t array_length(T (&)[N]) {
475 return N;
476}
Greg Kaiser38723f22018-02-16 13:35:35 -0800477
478constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
479 return (index >= array_length(supported_crypto_types));
480}
481
Paul Crowley14c8c072018-09-18 13:30:21 -0700482constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800483 return ((crypto_type.get_property_name() != nullptr) &&
484 (crypto_type.get_crypto_name() != nullptr) &&
485 (crypto_type.get_keysize() <= MAX_KEY_LEN));
486}
487
488// Note in C++11 that constexpr functions can only have a single line.
489// So our code is a bit convoluted (using recursion instead of a loop),
490// but it's asserting at compile time that all of our key lengths are valid.
491constexpr bool validateSupportedCryptoTypes(size_t index) {
492 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700493 (isValidCryptoType(supported_crypto_types[index]) &&
494 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800495}
496
497static_assert(validateSupportedCryptoTypes(0),
498 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
499 "incompletely constructed.");
500// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
501
Greg Kaiser38723f22018-02-16 13:35:35 -0800502// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700503const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800504 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
505 char paramstr[PROPERTY_VALUE_MAX];
506
Paul Crowley14c8c072018-09-18 13:30:21 -0700507 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
508 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800509 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
510 return ctype;
511 }
512 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700513 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
514 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800515 return default_crypto_type;
516}
517
518} // namespace
519
Kenny Rootc4c70f12013-06-14 12:11:38 -0700520/**
521 * Gets the default device scrypt parameters for key derivation time tuning.
522 * The parameters should lead to about one second derivation time for the
523 * given device.
524 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700525static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700526 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000527 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700528
Paul Crowley63c18d32016-02-10 14:02:47 +0000529 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
530 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
531 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
532 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700533 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000534 ftr->N_factor = Nf;
535 ftr->r_factor = rf;
536 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700537}
538
Greg Kaiser57f9af62018-02-16 13:13:58 -0800539uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800540 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800541}
542
Paul Crowley14c8c072018-09-18 13:30:21 -0700543const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800544 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800545}
546
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200547static uint64_t get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800548 int fd, block_size;
549 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200550 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800551
Paul Crowley14c8c072018-09-18 13:30:21 -0700552 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800553 SLOGE("Cannot open device to get filesystem size ");
554 return 0;
555 }
556
557 if (lseek64(fd, 1024, SEEK_SET) < 0) {
558 SLOGE("Cannot seek to superblock");
559 return 0;
560 }
561
562 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
563 SLOGE("Cannot read superblock");
564 return 0;
565 }
566
567 close(fd);
568
Daniel Rosenberge82df162014-08-15 22:19:23 +0000569 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
570 SLOGE("Not a valid ext4 superblock");
571 return 0;
572 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800573 block_size = 1024 << sb.s_log_block_size;
574 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200575 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800576
577 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200578 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800579}
580
Paul Crowley14c8c072018-09-18 13:30:21 -0700581static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
582 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200583 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700584 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700585 char key_loc[PROPERTY_VALUE_MAX];
586 char real_blkdev[PROPERTY_VALUE_MAX];
587 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700588
Paul Crowley14c8c072018-09-18 13:30:21 -0700589 if (!cached_data) {
590 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700591
Paul Crowley14c8c072018-09-18 13:30:21 -0700592 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200593 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700594 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
595 * encryption info footer and key, and plenty of bytes to spare for future
596 * growth.
597 */
598 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200599 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700600 cached_data = 1;
601 } else {
602 SLOGE("Cannot get size of block device %s\n", real_blkdev);
603 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700604 } else {
605 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
606 cached_off = 0;
607 cached_data = 1;
608 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700609 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700610
Paul Crowley14c8c072018-09-18 13:30:21 -0700611 if (cached_data) {
612 if (metadata_fname) {
613 *metadata_fname = cached_metadata_fname;
614 }
615 if (off) {
616 *off = cached_off;
617 }
618 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620
Paul Crowley14c8c072018-09-18 13:30:21 -0700621 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700622}
623
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800624/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700625static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800626 SHA256_CTX c;
627 SHA256_Init(&c);
628 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
629 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
630 SHA256_Final(crypt_ftr->sha256, &c);
631}
632
Ken Sumralle8744072011-01-18 22:01:55 -0800633/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800634 * update the failed mount count but not change the key.
635 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700636static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
637 int fd;
638 unsigned int cnt;
639 /* starting_off is set to the SEEK_SET offset
640 * where the crypto structure starts
641 */
642 off64_t starting_off;
643 int rc = -1;
644 char* fname = NULL;
645 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800646
Paul Crowley14c8c072018-09-18 13:30:21 -0700647 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800648
Paul Crowley14c8c072018-09-18 13:30:21 -0700649 if (get_crypt_ftr_info(&fname, &starting_off)) {
650 SLOGE("Unable to get crypt_ftr_info\n");
651 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800652 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700653 if (fname[0] != '/') {
654 SLOGE("Unexpected value for crypto key location\n");
655 return -1;
656 }
657 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
658 SLOGE("Cannot open footer file %s for put\n", fname);
659 return -1;
660 }
Ken Sumralle8744072011-01-18 22:01:55 -0800661
Paul Crowley14c8c072018-09-18 13:30:21 -0700662 /* Seek to the start of the crypt footer */
663 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
664 SLOGE("Cannot seek to real block device footer\n");
665 goto errout;
666 }
667
668 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
669 SLOGE("Cannot write real block device footer\n");
670 goto errout;
671 }
672
673 fstat(fd, &statbuf);
674 /* If the keys are kept on a raw block device, do not try to truncate it. */
675 if (S_ISREG(statbuf.st_mode)) {
676 if (ftruncate(fd, 0x4000)) {
677 SLOGE("Cannot set footer file size\n");
678 goto errout;
679 }
680 }
681
682 /* Success! */
683 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800684
685errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700686 close(fd);
687 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800688}
689
Paul Crowley14c8c072018-09-18 13:30:21 -0700690static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800691 struct crypt_mnt_ftr copy;
692 memcpy(&copy, crypt_ftr, sizeof(copy));
693 set_ftr_sha(&copy);
694 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
695}
696
Paul Crowley14c8c072018-09-18 13:30:21 -0700697static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700698 return TEMP_FAILURE_RETRY(read(fd, buff, len));
699}
700
Paul Crowley14c8c072018-09-18 13:30:21 -0700701static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700702 return TEMP_FAILURE_RETRY(write(fd, buff, len));
703}
704
Paul Crowley14c8c072018-09-18 13:30:21 -0700705static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700706 memset(pdata, 0, len);
707 pdata->persist_magic = PERSIST_DATA_MAGIC;
708 pdata->persist_valid_entries = 0;
709}
710
711/* A routine to update the passed in crypt_ftr to the lastest version.
712 * fd is open read/write on the device that holds the crypto footer and persistent
713 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
714 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
715 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700716static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700717 int orig_major = crypt_ftr->major_version;
718 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700719
Kenny Root7434b312013-06-14 11:29:53 -0700720 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700721 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700722 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700723
Kenny Rootc4c70f12013-06-14 12:11:38 -0700724 SLOGW("upgrading crypto footer to 1.1");
725
Paul Crowley14c8c072018-09-18 13:30:21 -0700726 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700727 if (pdata == NULL) {
728 SLOGE("Cannot allocate persisent data\n");
729 return;
730 }
731 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
732
733 /* Need to initialize the persistent data area */
734 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
735 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100736 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700737 return;
738 }
739 /* Write all zeros to the first copy, making it invalid */
740 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
741
742 /* Write a valid but empty structure to the second copy */
743 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
744 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
745
746 /* Update the footer */
747 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
748 crypt_ftr->persist_data_offset[0] = pdata_offset;
749 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
750 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100751 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700752 }
753
Paul Lawrencef4faa572014-01-29 13:31:03 -0800754 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700755 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800756 /* But keep the old kdf_type.
757 * It will get updated later to KDF_SCRYPT after the password has been verified.
758 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700759 crypt_ftr->kdf_type = KDF_PBKDF2;
760 get_device_scrypt_params(crypt_ftr);
761 crypt_ftr->minor_version = 2;
762 }
763
Paul Lawrencef4faa572014-01-29 13:31:03 -0800764 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
765 SLOGW("upgrading crypto footer to 1.3");
766 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
767 crypt_ftr->minor_version = 3;
768 }
769
Kenny Root7434b312013-06-14 11:29:53 -0700770 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
771 if (lseek64(fd, offset, SEEK_SET) == -1) {
772 SLOGE("Cannot seek to crypt footer\n");
773 return;
774 }
775 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700776 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700777}
778
Paul Crowley14c8c072018-09-18 13:30:21 -0700779static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
780 int fd;
781 unsigned int cnt;
782 off64_t starting_off;
783 int rc = -1;
784 char* fname = NULL;
785 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700786
Paul Crowley14c8c072018-09-18 13:30:21 -0700787 if (get_crypt_ftr_info(&fname, &starting_off)) {
788 SLOGE("Unable to get crypt_ftr_info\n");
789 return -1;
790 }
791 if (fname[0] != '/') {
792 SLOGE("Unexpected value for crypto key location\n");
793 return -1;
794 }
795 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
796 SLOGE("Cannot open footer file %s for get\n", fname);
797 return -1;
798 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800799
Paul Crowley14c8c072018-09-18 13:30:21 -0700800 /* Make sure it's 16 Kbytes in length */
801 fstat(fd, &statbuf);
802 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
803 SLOGE("footer file %s is not the expected size!\n", fname);
804 goto errout;
805 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700806
Paul Crowley14c8c072018-09-18 13:30:21 -0700807 /* Seek to the start of the crypt footer */
808 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
809 SLOGE("Cannot seek to real block device footer\n");
810 goto errout;
811 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700812
Paul Crowley14c8c072018-09-18 13:30:21 -0700813 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
814 SLOGE("Cannot read real block device footer\n");
815 goto errout;
816 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800817
Paul Crowley14c8c072018-09-18 13:30:21 -0700818 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
819 SLOGE("Bad magic for real block device %s\n", fname);
820 goto errout;
821 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800822
Paul Crowley14c8c072018-09-18 13:30:21 -0700823 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
824 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
825 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
826 goto errout;
827 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800828
Paul Crowley14c8c072018-09-18 13:30:21 -0700829 // We risk buffer overflows with oversized keys, so we just reject them.
830 // 0-sized keys are problematic (essentially by-passing encryption), and
831 // AES-CBC key wrapping only works for multiples of 16 bytes.
832 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
833 (crypt_ftr->keysize > MAX_KEY_LEN)) {
834 SLOGE(
835 "Invalid keysize (%u) for block device %s; Must be non-zero, "
836 "divisible by 16, and <= %d\n",
837 crypt_ftr->keysize, fname, MAX_KEY_LEN);
838 goto errout;
839 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800840
Paul Crowley14c8c072018-09-18 13:30:21 -0700841 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
842 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
843 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
844 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800845
Paul Crowley14c8c072018-09-18 13:30:21 -0700846 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
847 * copy on disk before returning.
848 */
849 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
850 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
851 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800852
Paul Crowley14c8c072018-09-18 13:30:21 -0700853 /* Success! */
854 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800855
856errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700857 close(fd);
858 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800859}
860
Paul Crowley14c8c072018-09-18 13:30:21 -0700861static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700862 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
863 crypt_ftr->persist_data_offset[1]) {
864 SLOGE("Crypt_ftr persist data regions overlap");
865 return -1;
866 }
867
868 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
869 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
870 return -1;
871 }
872
873 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700874 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700875 CRYPT_FOOTER_OFFSET) {
876 SLOGE("Persistent data extends past crypto footer");
877 return -1;
878 }
879
880 return 0;
881}
882
Paul Crowley14c8c072018-09-18 13:30:21 -0700883static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700884 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700885 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700886 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700887 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700888 int found = 0;
889 int fd;
890 int ret;
891 int i;
892
893 if (persist_data) {
894 /* Nothing to do, we've already loaded or initialized it */
895 return 0;
896 }
897
Ken Sumrall160b4d62013-04-22 12:15:39 -0700898 /* If not encrypted, just allocate an empty table and initialize it */
899 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700900 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800901 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700902 if (pdata) {
903 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
904 persist_data = pdata;
905 return 0;
906 }
907 return -1;
908 }
909
Paul Crowley14c8c072018-09-18 13:30:21 -0700910 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700911 return -1;
912 }
913
Paul Crowley14c8c072018-09-18 13:30:21 -0700914 if ((crypt_ftr.major_version < 1) ||
915 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700916 SLOGE("Crypt_ftr version doesn't support persistent data");
917 return -1;
918 }
919
920 if (get_crypt_ftr_info(&fname, NULL)) {
921 return -1;
922 }
923
924 ret = validate_persistent_data_storage(&crypt_ftr);
925 if (ret) {
926 return -1;
927 }
928
Paul Crowley14c8c072018-09-18 13:30:21 -0700929 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700930 if (fd < 0) {
931 SLOGE("Cannot open %s metadata file", fname);
932 return -1;
933 }
934
Wei Wang4375f1b2017-02-24 17:43:01 -0800935 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800936 if (pdata == NULL) {
937 SLOGE("Cannot allocate memory for persistent data");
938 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700939 }
940
941 for (i = 0; i < 2; i++) {
942 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
943 SLOGE("Cannot seek to read persistent data on %s", fname);
944 goto err2;
945 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700946 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700947 SLOGE("Error reading persistent data on iteration %d", i);
948 goto err2;
949 }
950 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
951 found = 1;
952 break;
953 }
954 }
955
956 if (!found) {
957 SLOGI("Could not find valid persistent data, creating");
958 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
959 }
960
961 /* Success */
962 persist_data = pdata;
963 close(fd);
964 return 0;
965
966err2:
967 free(pdata);
968
969err:
970 close(fd);
971 return -1;
972}
973
Paul Crowley14c8c072018-09-18 13:30:21 -0700974static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700975 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700976 struct crypt_persist_data* pdata;
977 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700978 off64_t write_offset;
979 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700980 int fd;
981 int ret;
982
983 if (persist_data == NULL) {
984 SLOGE("No persistent data to save");
985 return -1;
986 }
987
Paul Crowley14c8c072018-09-18 13:30:21 -0700988 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700989 return -1;
990 }
991
Paul Crowley14c8c072018-09-18 13:30:21 -0700992 if ((crypt_ftr.major_version < 1) ||
993 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700994 SLOGE("Crypt_ftr version doesn't support persistent data");
995 return -1;
996 }
997
998 ret = validate_persistent_data_storage(&crypt_ftr);
999 if (ret) {
1000 return -1;
1001 }
1002
1003 if (get_crypt_ftr_info(&fname, NULL)) {
1004 return -1;
1005 }
1006
Paul Crowley14c8c072018-09-18 13:30:21 -07001007 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001008 if (fd < 0) {
1009 SLOGE("Cannot open %s metadata file", fname);
1010 return -1;
1011 }
1012
Wei Wang4375f1b2017-02-24 17:43:01 -08001013 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001014 if (pdata == NULL) {
1015 SLOGE("Cannot allocate persistant data");
1016 goto err;
1017 }
1018
1019 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1020 SLOGE("Cannot seek to read persistent data on %s", fname);
1021 goto err2;
1022 }
1023
1024 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001025 SLOGE("Error reading persistent data before save");
1026 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001027 }
1028
1029 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1030 /* The first copy is the curent valid copy, so write to
1031 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001032 write_offset = crypt_ftr.persist_data_offset[1];
1033 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001034 } else {
1035 /* The second copy must be the valid copy, so write to
1036 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001037 write_offset = crypt_ftr.persist_data_offset[0];
1038 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001039 }
1040
1041 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001042 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001043 SLOGE("Cannot seek to write persistent data");
1044 goto err2;
1045 }
1046 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001047 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001048 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001049 SLOGE("Cannot seek to erase previous persistent data");
1050 goto err2;
1051 }
1052 fsync(fd);
1053 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001054 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001055 SLOGE("Cannot write to erase previous persistent data");
1056 goto err2;
1057 }
1058 fsync(fd);
1059 } else {
1060 SLOGE("Cannot write to save persistent data");
1061 goto err2;
1062 }
1063
1064 /* Success */
1065 free(pdata);
1066 close(fd);
1067 return 0;
1068
1069err2:
1070 free(pdata);
1071err:
1072 close(fd);
1073 return -1;
1074}
1075
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001076/* Convert a binary key of specified length into an ascii hex string equivalent,
1077 * without the leading 0x and with null termination
1078 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001079static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1080 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001081 unsigned int i, a;
1082 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001083
Paul Crowley14c8c072018-09-18 13:30:21 -07001084 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001085 /* For each byte, write out two ascii hex digits */
1086 nibble = (master_key[i] >> 4) & 0xf;
1087 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001088
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001089 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001090 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001091 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001092
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001093 /* Add the null termination */
1094 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001095}
1096
Paul Crowley14c8c072018-09-18 13:30:21 -07001097static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
1098 const unsigned char* master_key, const char* real_blk_name,
1099 const char* name, int fd, const char* extra_params) {
1100 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1101 struct dm_ioctl* io;
1102 struct dm_target_spec* tgt;
1103 char* crypt_params;
1104 // We need two ASCII characters to represent each byte, and need space for
1105 // the '\0' terminator.
1106 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1107 size_t buff_offset;
1108 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001109
Paul Crowley14c8c072018-09-18 13:30:21 -07001110 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001111
Paul Crowley14c8c072018-09-18 13:30:21 -07001112 /* Load the mapping table for this device */
1113 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001114
Paul Crowley14c8c072018-09-18 13:30:21 -07001115 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1116 io->target_count = 1;
1117 tgt->status = 0;
1118 tgt->sector_start = 0;
1119 tgt->length = crypt_ftr->fs_size;
Paul Crowley14c8c072018-09-18 13:30:21 -07001120 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
Paul Crowley14c8c072018-09-18 13:30:21 -07001121 buff_offset = crypt_params - buffer;
1122 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301123
1124#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001125 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1126 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1127 if (is_ice_enabled())
1128 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1129 else
1130 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1131 }
1132 else {
1133 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1134 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1135 }
1136 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1137 crypt_ftr->crypto_type_name, master_key_ascii,
1138 real_blk_name, extra_params);
1139
1140 SLOGI("target_type = %s", tgt->target_type);
1141 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1142#else
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301143 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1144 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Paul Crowley14c8c072018-09-18 13:30:21 -07001145 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
1146 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301147#endif
1148
Paul Crowley14c8c072018-09-18 13:30:21 -07001149 crypt_params += strlen(crypt_params) + 1;
1150 crypt_params =
1151 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1152 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001153
Paul Crowley14c8c072018-09-18 13:30:21 -07001154 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1155 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
1156 break;
1157 }
1158 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001159 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001160
Paul Crowley14c8c072018-09-18 13:30:21 -07001161 if (i == TABLE_LOAD_RETRIES) {
1162 /* We failed to load the table, return an error */
1163 return -1;
1164 } else {
1165 return i + 1;
1166 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001167}
1168
Paul Crowley14c8c072018-09-18 13:30:21 -07001169static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001170 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001171 struct dm_ioctl* io;
1172 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001173
Paul Crowley14c8c072018-09-18 13:30:21 -07001174 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001175
1176 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1177
1178 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1179 return -1;
1180 }
1181
1182 /* Iterate over the returned versions, looking for name of "crypt".
1183 * When found, get and return the version.
1184 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001185 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001186 while (v->next) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301187#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001188 if (!strcmp(v->name, "crypt") || !strcmp(v->name, "req-crypt")) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301189#else
Paul Crowley14c8c072018-09-18 13:30:21 -07001190 if (!strcmp(v->name, "crypt")) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301191#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001192 /* We found the crypt driver, return the version, and get out */
1193 version[0] = v->version[0];
1194 version[1] = v->version[1];
1195 version[2] = v->version[2];
1196 return 0;
1197 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001198 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001199 }
1200
1201 return -1;
1202}
1203
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301204#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Crowley5afbc622017-11-27 09:42:17 -08001205static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1206 if (extra_params_vec.empty()) return "";
1207 std::string extra_params = std::to_string(extra_params_vec.size());
1208 for (const auto& p : extra_params_vec) {
1209 extra_params.append(" ");
1210 extra_params.append(p);
1211 }
1212 return extra_params;
1213}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301214#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001215
Paul Crowley5afbc622017-11-27 09:42:17 -08001216static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1217 const char* real_blk_name, char* crypto_blk_name, const char* name,
1218 uint32_t flags) {
1219 char buffer[DM_CRYPT_BUF_SIZE];
1220 struct dm_ioctl* io;
1221 unsigned int minor;
1222 int fd = 0;
1223 int err;
1224 int retval = -1;
1225 int version[3];
1226 int load_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301227#ifdef CONFIG_HW_DISK_ENCRYPTION
1228 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1229 char progress[PROPERTY_VALUE_MAX] = {0};
1230 const char *extra_params;
1231#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001232 std::vector<std::string> extra_params_vec;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301233#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001234
Paul Crowley5afbc622017-11-27 09:42:17 -08001235 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1236 SLOGE("Cannot open device-mapper\n");
1237 goto errout;
1238 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001239
Paul Crowley5afbc622017-11-27 09:42:17 -08001240 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001241
Paul Crowley5afbc622017-11-27 09:42:17 -08001242 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1243 err = ioctl(fd, DM_DEV_CREATE, io);
1244 if (err) {
1245 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1246 goto errout;
1247 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001248
Paul Crowley5afbc622017-11-27 09:42:17 -08001249 /* Get the device status, in particular, the name of it's device file */
1250 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1251 if (ioctl(fd, DM_DEV_STATUS, io)) {
1252 SLOGE("Cannot retrieve dm-crypt device status\n");
1253 goto errout;
1254 }
1255 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1256 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001257
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301258#ifdef CONFIG_HW_DISK_ENCRYPTION
1259 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1260 /* Set fde_enabled if either FDE completed or in-progress */
1261 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1262 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1263 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1264 if (is_ice_enabled()) {
1265 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1266 extra_params = "fde_enabled ice allow_encrypt_override";
1267 else
1268 extra_params = "fde_enabled ice";
1269 } else {
1270 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1271 extra_params = "fde_enabled allow_encrypt_override";
1272 else
1273 extra_params = "fde_enabled";
1274 }
1275 } else {
1276 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1277 extra_params = "fde_enabled allow_encrypt_override";
1278 else
1279 extra_params = "fde_enabled";
1280 }
1281 } else {
1282 extra_params = "";
1283 if (! get_dm_crypt_version(fd, name, version)) {
1284 /* Support for allow_discards was added in version 1.11.0 */
1285 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1286 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1287 extra_params = "2 allow_discards allow_encrypt_override";
1288 else
1289 extra_params = "1 allow_discards";
1290 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1291 }
1292 }
1293 }
1294 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1295 extra_params);
1296#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001297 if (!get_dm_crypt_version(fd, name, version)) {
1298 /* Support for allow_discards was added in version 1.11.0 */
1299 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1300 extra_params_vec.emplace_back("allow_discards");
1301 }
1302 }
1303 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1304 extra_params_vec.emplace_back("allow_encrypt_override");
1305 }
1306 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1307 extra_params_as_string(extra_params_vec).c_str());
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301308#endif
Paul Crowley5afbc622017-11-27 09:42:17 -08001309 if (load_count < 0) {
1310 SLOGE("Cannot load dm-crypt mapping table.\n");
1311 goto errout;
1312 } else if (load_count > 1) {
1313 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1314 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001315
Paul Crowley5afbc622017-11-27 09:42:17 -08001316 /* Resume this device to activate it */
1317 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001318
Paul Crowley5afbc622017-11-27 09:42:17 -08001319 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1320 SLOGE("Cannot resume the dm-crypt device\n");
1321 goto errout;
1322 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001323
Paul Crowley5afbc622017-11-27 09:42:17 -08001324 /* We made it here with no errors. Woot! */
1325 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001326
1327errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001328 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001329
Paul Crowley14c8c072018-09-18 13:30:21 -07001330 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001331}
1332
Paul Crowley14c8c072018-09-18 13:30:21 -07001333static int delete_crypto_blk_dev(const char* name) {
1334 int fd;
1335 char buffer[DM_CRYPT_BUF_SIZE];
1336 struct dm_ioctl* io;
1337 int retval = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001338
Paul Crowley14c8c072018-09-18 13:30:21 -07001339 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1340 SLOGE("Cannot open device-mapper\n");
1341 goto errout;
1342 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001343
Paul Crowley14c8c072018-09-18 13:30:21 -07001344 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001345
Paul Crowley14c8c072018-09-18 13:30:21 -07001346 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1347 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1348 SLOGE("Cannot remove dm-crypt device\n");
1349 goto errout;
1350 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001351
Paul Crowley14c8c072018-09-18 13:30:21 -07001352 /* We made it here with no errors. Woot! */
1353 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001354
1355errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001356 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001357
Paul Crowley14c8c072018-09-18 13:30:21 -07001358 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001359}
1360
Paul Crowley14c8c072018-09-18 13:30:21 -07001361static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1362 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001363 SLOGI("Using pbkdf2 for cryptfs KDF");
1364
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001365 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001366 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1367 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001368}
1369
Paul Crowley14c8c072018-09-18 13:30:21 -07001370static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001371 SLOGI("Using scrypt for cryptfs KDF");
1372
Paul Crowley14c8c072018-09-18 13:30:21 -07001373 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001374
1375 int N = 1 << ftr->N_factor;
1376 int r = 1 << ftr->r_factor;
1377 int p = 1 << ftr->p_factor;
1378
1379 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001380 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001381 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001382
Paul Crowley14c8c072018-09-18 13:30:21 -07001383 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001384}
1385
Paul Crowley14c8c072018-09-18 13:30:21 -07001386static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1387 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001388 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1389
1390 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001391 size_t signature_size;
1392 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001393 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001394
1395 int N = 1 << ftr->N_factor;
1396 int r = 1 << ftr->r_factor;
1397 int p = 1 << ftr->p_factor;
1398
Paul Crowley14c8c072018-09-18 13:30:21 -07001399 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001400 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001401
1402 if (rc) {
1403 SLOGE("scrypt failed");
1404 return -1;
1405 }
1406
Paul Crowley14c8c072018-09-18 13:30:21 -07001407 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001408 SLOGE("Signing failed");
1409 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001410 }
1411
Paul Crowley14c8c072018-09-18 13:30:21 -07001412 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1413 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001414 free(signature);
1415
1416 if (rc) {
1417 SLOGE("scrypt failed");
1418 return -1;
1419 }
1420
1421 return 0;
1422}
1423
Paul Crowley14c8c072018-09-18 13:30:21 -07001424static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1425 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001426 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1427 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001428 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001429 EVP_CIPHER_CTX e_ctx;
1430 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001431 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001432
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001433 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001434 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001435
1436 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001437 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001438 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001439 SLOGE("keymaster_create_key failed");
1440 return -1;
1441 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001442
Paul Crowley14c8c072018-09-18 13:30:21 -07001443 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1444 SLOGE("scrypt failed");
1445 return -1;
1446 }
1447 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001448
Paul Crowley14c8c072018-09-18 13:30:21 -07001449 case KDF_SCRYPT:
1450 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1451 SLOGE("scrypt failed");
1452 return -1;
1453 }
1454 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001455
Paul Crowley14c8c072018-09-18 13:30:21 -07001456 default:
1457 SLOGE("Invalid kdf_type");
1458 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001459 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001460
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001461 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001462 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001463 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1464 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001465 SLOGE("EVP_EncryptInit failed\n");
1466 return -1;
1467 }
1468 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001469
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001470 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001471 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1472 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001473 SLOGE("EVP_EncryptUpdate failed\n");
1474 return -1;
1475 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001476 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001477 SLOGE("EVP_EncryptFinal failed\n");
1478 return -1;
1479 }
1480
Greg Kaiser59ad0182018-02-16 13:01:36 -08001481 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001482 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1483 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001484 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001485
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001486 /* Store the scrypt of the intermediate key, so we can validate if it's a
1487 password error or mount error when things go wrong.
1488 Note there's no need to check for errors, since if this is incorrect, we
1489 simply won't wipe userdata, which is the correct default behavior
1490 */
1491 int N = 1 << crypt_ftr->N_factor;
1492 int r = 1 << crypt_ftr->r_factor;
1493 int p = 1 << crypt_ftr->p_factor;
1494
Paul Crowley14c8c072018-09-18 13:30:21 -07001495 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1496 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001497 sizeof(crypt_ftr->scrypted_intermediate_key));
1498
1499 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001500 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001501 }
1502
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001503 EVP_CIPHER_CTX_cleanup(&e_ctx);
1504
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001505 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001506}
1507
Paul Crowley14c8c072018-09-18 13:30:21 -07001508static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1509 const unsigned char* encrypted_master_key, size_t keysize,
1510 unsigned char* decrypted_master_key, kdf_func kdf,
1511 void* kdf_params, unsigned char** intermediate_key,
1512 size_t* intermediate_key_size) {
1513 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1514 EVP_CIPHER_CTX d_ctx;
1515 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001516
Paul Crowley14c8c072018-09-18 13:30:21 -07001517 /* Turn the password into an intermediate key and IV that can decrypt the
1518 master key */
1519 if (kdf(passwd, salt, ikey, kdf_params)) {
1520 SLOGE("kdf failed");
1521 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001522 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001523
Paul Crowley14c8c072018-09-18 13:30:21 -07001524 /* Initialize the decryption engine */
1525 EVP_CIPHER_CTX_init(&d_ctx);
1526 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1527 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1528 return -1;
1529 }
1530 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1531 /* Decrypt the master key */
1532 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1533 keysize)) {
1534 return -1;
1535 }
1536 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1537 return -1;
1538 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001539
Paul Crowley14c8c072018-09-18 13:30:21 -07001540 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1541 return -1;
1542 }
1543
1544 /* Copy intermediate key if needed by params */
1545 if (intermediate_key && intermediate_key_size) {
1546 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1547 if (*intermediate_key) {
1548 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1549 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1550 }
1551 }
1552
1553 EVP_CIPHER_CTX_cleanup(&d_ctx);
1554
1555 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001556}
1557
Paul Crowley14c8c072018-09-18 13:30:21 -07001558static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001559 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001560 *kdf = scrypt_keymaster;
1561 *kdf_params = ftr;
1562 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001563 *kdf = scrypt;
1564 *kdf_params = ftr;
1565 } else {
1566 *kdf = pbkdf2;
1567 *kdf_params = NULL;
1568 }
1569}
1570
Paul Crowley14c8c072018-09-18 13:30:21 -07001571static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1572 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1573 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001574 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001575 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001576 int ret;
1577
1578 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001579 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1580 decrypted_master_key, kdf, kdf_params, intermediate_key,
1581 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001582 if (ret != 0) {
1583 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001584 }
1585
1586 return ret;
1587}
1588
Paul Crowley14c8c072018-09-18 13:30:21 -07001589static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1590 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001591 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001592 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001593
1594 /* Get some random bits for a key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001595 fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001596 read(fd, key_buf, sizeof(key_buf));
1597 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001598 close(fd);
1599
1600 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301601 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001602}
1603
Paul Crowley14c8c072018-09-18 13:30:21 -07001604int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001605 int i, err, rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301606#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001607
1608 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001609 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001610 if (umount(mountpoint) == 0) {
1611 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001612 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001613
1614 if (errno == EINVAL) {
1615 /* EINVAL is returned if the directory is not a mountpoint,
1616 * i.e. there is no filesystem mounted there. So just get out.
1617 */
1618 break;
1619 }
1620
1621 err = errno;
1622
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301623 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001624 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301625 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001626 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001627 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301628 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001629 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001630 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001631 }
1632 }
1633
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301634 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001635 }
1636
1637 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001638 SLOGD("unmounting %s succeeded\n", mountpoint);
1639 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001640 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001641 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1642 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1643 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001644 }
1645
1646 return rc;
1647}
1648
Paul Crowley14c8c072018-09-18 13:30:21 -07001649static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001650 // NOTE: post_fs_data results in init calling back around to vold, so all
1651 // callers to this method must be async
1652
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001653 /* Do the prep of the /data filesystem */
1654 property_set("vold.post_fs_data_done", "0");
1655 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001656 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001657
Ken Sumrallc5872692013-05-14 15:26:31 -07001658 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001659 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001660 /* We timed out to prep /data in time. Continue wait. */
1661 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001662 }
Wei Wang42e38102017-06-07 10:46:12 -07001663 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001664}
1665
Paul Crowley14c8c072018-09-18 13:30:21 -07001666static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001667 // Mark the footer as bad
1668 struct crypt_mnt_ftr crypt_ftr;
1669 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1670 SLOGE("Failed to get crypto footer - panic");
1671 return;
1672 }
1673
1674 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1675 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1676 SLOGE("Failed to set crypto footer - panic");
1677 return;
1678 }
1679}
1680
Paul Crowley14c8c072018-09-18 13:30:21 -07001681static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001682 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001683 SLOGE("Failed to mount tmpfs on data - panic");
1684 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001685 }
1686
1687 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1688 SLOGE("Failed to trigger post fs data - panic");
1689 return;
1690 }
1691
1692 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1693 SLOGE("Failed to trigger restart min framework - panic");
1694 return;
1695 }
1696}
1697
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001698/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001699static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001700 char crypto_blkdev[MAXPATHLEN];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301701#ifdef CONFIG_HW_DISK_ENCRYPTION
1702 char blkdev[MAXPATHLEN];
1703#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001704 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001705 static int restart_successful = 0;
1706
1707 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001708 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001709 SLOGE("Encrypted filesystem not validated, aborting");
1710 return -1;
1711 }
1712
1713 if (restart_successful) {
1714 SLOGE("System already restarted with encrypted disk, aborting");
1715 return -1;
1716 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717
Paul Lawrencef4faa572014-01-29 13:31:03 -08001718 if (restart_main) {
1719 /* Here is where we shut down the framework. The init scripts
1720 * start all services in one of three classes: core, main or late_start.
1721 * On boot, we start core and main. Now, we stop main, but not core,
1722 * as core includes vold and a few other really important things that
1723 * we need to keep running. Once main has stopped, we should be able
1724 * to umount the tmpfs /data, then mount the encrypted /data.
1725 * We then restart the class main, and also the class late_start.
1726 * At the moment, I've only put a few things in late_start that I know
1727 * are not needed to bring up the framework, and that also cause problems
1728 * with unmounting the tmpfs /data, but I hope to add add more services
1729 * to the late_start class as we optimize this to decrease the delay
1730 * till the user is asked for the password to the filesystem.
1731 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001732
Paul Lawrencef4faa572014-01-29 13:31:03 -08001733 /* The init files are setup to stop the class main when vold.decrypt is
1734 * set to trigger_reset_main.
1735 */
1736 property_set("vold.decrypt", "trigger_reset_main");
1737 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001738
Paul Lawrencef4faa572014-01-29 13:31:03 -08001739 /* Ugh, shutting down the framework is not synchronous, so until it
1740 * can be fixed, this horrible hack will wait a moment for it all to
1741 * shut down before proceeding. Without it, some devices cannot
1742 * restart the graphics services.
1743 */
1744 sleep(2);
1745 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001746
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001747 /* Now that the framework is shutdown, we should be able to umount()
1748 * the tmpfs filesystem, and mount the real one.
1749 */
1750
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301751#if defined(CONFIG_HW_DISK_ENCRYPTION)
1752#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1753 if (is_ice_enabled()) {
1754 fs_mgr_get_crypt_info(fstab_default, 0, blkdev, sizeof(blkdev));
1755 if (set_ice_param(START_ENCDEC)) {
1756 SLOGE("Failed to set ICE data");
1757 return -1;
1758 }
1759 }
1760#else
1761 property_get("ro.crypto.fs_crypto_blkdev", blkdev, "");
1762 if (strlen(blkdev) == 0) {
1763 SLOGE("fs_crypto_blkdev not set\n");
1764 return -1;
1765 }
1766 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1767#endif
1768#else
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001769 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1770 if (strlen(crypto_blkdev) == 0) {
1771 SLOGE("fs_crypto_blkdev not set\n");
1772 return -1;
1773 }
1774
Paul Crowley14c8c072018-09-18 13:30:21 -07001775 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301776#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001777 /* If ro.crypto.readonly is set to 1, mount the decrypted
1778 * filesystem readonly. This is used when /data is mounted by
1779 * recovery mode.
1780 */
1781 char ro_prop[PROPERTY_VALUE_MAX];
1782 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001783 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001784 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07001785 if (rec) {
1786 rec->flags |= MS_RDONLY;
1787 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001788 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001789
Ken Sumralle5032c42012-04-01 23:58:44 -07001790 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001791 int retries = RETRY_MOUNT_ATTEMPTS;
1792 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001793
1794 /*
1795 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1796 * partitions in the fsck domain.
1797 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001798 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001799 SLOGE("Failed to setexeccon");
1800 return -1;
1801 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001802 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301803#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001804 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, blkdev, 0,
1805 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301806#else
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001807 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1808 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301809#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001810 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1811 /* TODO: invoke something similar to
1812 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1813 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301814#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001815 SLOGI("Failed to mount %s because it is busy - waiting", blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301816#else
Paul Crowley14c8c072018-09-18 13:30:21 -07001817 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301818#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001819 if (--retries) {
1820 sleep(RETRY_MOUNT_DELAY_SECONDS);
1821 } else {
1822 /* Let's hope that a reboot clears away whatever is keeping
1823 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001824 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001825 }
1826 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301827#ifdef CONFIG_HW_DISK_ENCRYPTION
1828 if (--retries) {
1829 sleep(RETRY_MOUNT_DELAY_SECONDS);
1830 } else {
1831 SLOGE("Failed to mount decrypted data");
1832 cryptfs_set_corrupt();
1833 cryptfs_trigger_restart_min_framework();
1834 SLOGI("Started framework to offer wipe");
1835 return -1;
1836 }
1837#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001838 SLOGE("Failed to mount decrypted data");
1839 cryptfs_set_corrupt();
1840 cryptfs_trigger_restart_min_framework();
1841 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001842 if (setexeccon(NULL)) {
1843 SLOGE("Failed to setexeccon");
1844 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001845 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301846#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001847 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001848 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001849 if (setexeccon(NULL)) {
1850 SLOGE("Failed to setexeccon");
1851 return -1;
1852 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001853
Ken Sumralle5032c42012-04-01 23:58:44 -07001854 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001855 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001856 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001857
1858 /* startup service classes main and late_start */
1859 property_set("vold.decrypt", "trigger_restart_framework");
1860 SLOGD("Just triggered restart_framework\n");
1861
1862 /* Give it a few moments to get started */
1863 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301864#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001865 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301866#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001867
Ken Sumrall0cc16632011-01-18 20:32:26 -08001868 if (rc == 0) {
1869 restart_successful = 1;
1870 }
1871
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001872 return rc;
1873}
1874
Paul Crowley14c8c072018-09-18 13:30:21 -07001875int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001876 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001877 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001878 SLOGE("cryptfs_restart not valid for file encryption:");
1879 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001880 }
1881
Paul Lawrencef4faa572014-01-29 13:31:03 -08001882 /* Call internal implementation forcing a restart of main service group */
1883 return cryptfs_restart_internal(1);
1884}
1885
Paul Crowley14c8c072018-09-18 13:30:21 -07001886static int do_crypto_complete(const char* mount_point) {
1887 struct crypt_mnt_ftr crypt_ftr;
1888 char encrypted_state[PROPERTY_VALUE_MAX];
1889 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001890
Paul Crowley14c8c072018-09-18 13:30:21 -07001891 property_get("ro.crypto.state", encrypted_state, "");
1892 if (strcmp(encrypted_state, "encrypted")) {
1893 SLOGE("not running with encryption, aborting");
1894 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001895 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001896
Paul Crowley14c8c072018-09-18 13:30:21 -07001897 // crypto_complete is full disk encrypted status
1898 if (e4crypt_is_native()) {
1899 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1900 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001901
Paul Crowley14c8c072018-09-18 13:30:21 -07001902 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1903 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001904
Paul Crowley14c8c072018-09-18 13:30:21 -07001905 /*
1906 * Only report this error if key_loc is a file and it exists.
1907 * If the device was never encrypted, and /data is not mountable for
1908 * some reason, returning 1 should prevent the UI from presenting the
1909 * a "enter password" screen, or worse, a "press button to wipe the
1910 * device" screen.
1911 */
1912 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1913 SLOGE("master key file does not exist, aborting");
1914 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1915 } else {
1916 SLOGE("Error getting crypt footer and key\n");
1917 return CRYPTO_COMPLETE_BAD_METADATA;
1918 }
1919 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001920
Paul Crowley14c8c072018-09-18 13:30:21 -07001921 // Test for possible error flags
1922 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1923 SLOGE("Encryption process is partway completed\n");
1924 return CRYPTO_COMPLETE_PARTIAL;
1925 }
1926
1927 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1928 SLOGE("Encryption process was interrupted but cannot continue\n");
1929 return CRYPTO_COMPLETE_INCONSISTENT;
1930 }
1931
1932 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1933 SLOGE("Encryption is successful but data is corrupt\n");
1934 return CRYPTO_COMPLETE_CORRUPT;
1935 }
1936
1937 /* We passed the test! We shall diminish, and return to the west */
1938 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001939}
1940
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301941#ifdef CONFIG_HW_DISK_ENCRYPTION
1942static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1943 const char *passwd, const char *mount_point, const char *label)
1944{
Bill Peckham0db11972018-10-10 10:25:42 -07001945 /* Allocate enough space for a 256 bit key, but we may use less */
1946 unsigned char decrypted_master_key[32];
1947 char crypto_blkdev[MAXPATHLEN];
1948 char real_blkdev[MAXPATHLEN];
1949 unsigned int orig_failed_decrypt_count;
1950 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301951
Bill Peckham0db11972018-10-10 10:25:42 -07001952 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1953 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301954
Bill Peckham0db11972018-10-10 10:25:42 -07001955 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301956
Bill Peckham0db11972018-10-10 10:25:42 -07001957 int key_index = 0;
1958 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1959 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
1960 if (key_index < 0) {
1961 rc = crypt_ftr->failed_decrypt_count;
1962 goto errout;
1963 }
1964 else {
1965 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301966#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07001967 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
1968 real_blkdev, crypto_blkdev, label, 0)) {
1969 SLOGE("Error creating decrypted block device");
1970 rc = -1;
1971 goto errout;
1972 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301973#endif
Bill Peckham0db11972018-10-10 10:25:42 -07001974 } else {
1975 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1976 real_blkdev, crypto_blkdev, label, 0)) {
1977 SLOGE("Error creating decrypted block device");
1978 rc = -1;
1979 goto errout;
1980 }
1981 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301982 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301983 }
1984
Bill Peckham0db11972018-10-10 10:25:42 -07001985 if (rc == 0) {
1986 crypt_ftr->failed_decrypt_count = 0;
1987 if (orig_failed_decrypt_count != 0) {
1988 put_crypt_ftr_and_key(crypt_ftr);
1989 }
1990
1991 /* Save the name of the crypto block device
1992 * so we can mount it when restarting the framework. */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301993#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07001994 if (!is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301995#endif
Bill Peckham0db11972018-10-10 10:25:42 -07001996 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1997 master_key_saved = 1;
1998 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301999
Bill Peckham0db11972018-10-10 10:25:42 -07002000 errout:
2001 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302002}
2003#endif
2004
Paul Crowley14c8c072018-09-18 13:30:21 -07002005static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2006 const char* mount_point, const char* label) {
2007 unsigned char decrypted_master_key[MAX_KEY_LEN];
2008 char crypto_blkdev[MAXPATHLEN];
2009 char real_blkdev[MAXPATHLEN];
2010 char tmp_mount_point[64];
2011 unsigned int orig_failed_decrypt_count;
2012 int rc;
2013 int use_keymaster = 0;
2014 int upgrade = 0;
2015 unsigned char* intermediate_key = 0;
2016 size_t intermediate_key_size = 0;
2017 int N = 1 << crypt_ftr->N_factor;
2018 int r = 1 << crypt_ftr->r_factor;
2019 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302020
Paul Crowley14c8c072018-09-18 13:30:21 -07002021 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2022 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002023
Paul Crowley14c8c072018-09-18 13:30:21 -07002024 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2025 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2026 &intermediate_key_size)) {
2027 SLOGE("Failed to decrypt master key\n");
2028 rc = -1;
2029 goto errout;
2030 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002031 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002032
Paul Crowley14c8c072018-09-18 13:30:21 -07002033 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08002034
Paul Crowley14c8c072018-09-18 13:30:21 -07002035 // Create crypto block device - all (non fatal) code paths
2036 // need it
2037 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
2038 0)) {
2039 SLOGE("Error creating decrypted block device\n");
2040 rc = -1;
2041 goto errout;
2042 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002043
Paul Crowley14c8c072018-09-18 13:30:21 -07002044 /* Work out if the problem is the password or the data */
2045 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002046
Paul Crowley14c8c072018-09-18 13:30:21 -07002047 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2048 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2049 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002050
Paul Crowley14c8c072018-09-18 13:30:21 -07002051 // Does the key match the crypto footer?
2052 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2053 sizeof(scrypted_intermediate_key)) == 0) {
2054 SLOGI("Password matches");
2055 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002056 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002057 /* Try mounting the file system anyway, just in case the problem's with
2058 * the footer, not the key. */
2059 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2060 mkdir(tmp_mount_point, 0755);
2061 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
2062 SLOGE("Error temp mounting decrypted block device\n");
2063 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002064
Paul Crowley14c8c072018-09-18 13:30:21 -07002065 rc = ++crypt_ftr->failed_decrypt_count;
2066 put_crypt_ftr_and_key(crypt_ftr);
2067 } else {
2068 /* Success! */
2069 SLOGI("Password did not match but decrypted drive mounted - continue");
2070 umount(tmp_mount_point);
2071 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002072 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002073 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002074
Paul Crowley14c8c072018-09-18 13:30:21 -07002075 if (rc == 0) {
2076 crypt_ftr->failed_decrypt_count = 0;
2077 if (orig_failed_decrypt_count != 0) {
2078 put_crypt_ftr_and_key(crypt_ftr);
2079 }
2080
2081 /* Save the name of the crypto block device
2082 * so we can mount it when restarting the framework. */
2083 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2084
2085 /* Also save a the master key so we can reencrypted the key
2086 * the key when we want to change the password on it. */
2087 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2088 saved_mount_point = strdup(mount_point);
2089 master_key_saved = 1;
2090 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2091 rc = 0;
2092
2093 // Upgrade if we're not using the latest KDF.
2094 use_keymaster = keymaster_check_compatibility();
2095 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2096 // Don't allow downgrade
2097 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2098 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2099 upgrade = 1;
2100 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2101 crypt_ftr->kdf_type = KDF_SCRYPT;
2102 upgrade = 1;
2103 }
2104
2105 if (upgrade) {
2106 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002107 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002108 if (!rc) {
2109 rc = put_crypt_ftr_and_key(crypt_ftr);
2110 }
2111 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2112
2113 // Do not fail even if upgrade failed - machine is bootable
2114 // Note that if this code is ever hit, there is a *serious* problem
2115 // since KDFs should never fail. You *must* fix the kdf before
2116 // proceeding!
2117 if (rc) {
2118 SLOGW(
2119 "Upgrade failed with error %d,"
2120 " but continuing with previous state",
2121 rc);
2122 rc = 0;
2123 }
2124 }
2125 }
2126
2127errout:
2128 if (intermediate_key) {
2129 memset(intermediate_key, 0, intermediate_key_size);
2130 free(intermediate_key);
2131 }
2132 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002133}
2134
Ken Sumrall29d8da82011-05-18 17:20:07 -07002135/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002136 * Called by vold when it's asked to mount an encrypted external
2137 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002138 * as any metadata is been stored in a separate, small partition. We
2139 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07002140 *
2141 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002142 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002143int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
2144 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002145 uint64_t nr_sec = 0;
2146 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002147 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002148 return -1;
2149 }
2150
Jeff Sharkey9c484982015-03-31 10:35:33 -07002151 struct crypt_mnt_ftr ext_crypt_ftr;
2152 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2153 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002154 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07002155 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002156 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002157 uint32_t flags = 0;
2158 if (e4crypt_is_native() &&
2159 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2160 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002161
Paul Crowley385cb8c2018-03-29 13:27:23 -07002162 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07002163}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002164
Jeff Sharkey9c484982015-03-31 10:35:33 -07002165/*
2166 * Called by vold when it's asked to unmount an encrypted external
2167 * storage volume.
2168 */
2169int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002170 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002171}
2172
Paul Crowley14c8c072018-09-18 13:30:21 -07002173int cryptfs_crypto_complete(void) {
2174 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002175}
2176
Paul Crowley14c8c072018-09-18 13:30:21 -07002177int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002178 char encrypted_state[PROPERTY_VALUE_MAX];
2179 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002180 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2181 SLOGE(
2182 "encrypted fs already validated or not running with encryption,"
2183 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002184 return -1;
2185 }
2186
2187 if (get_crypt_ftr_and_key(crypt_ftr)) {
2188 SLOGE("Error getting crypt footer and key");
2189 return -1;
2190 }
2191
2192 return 0;
2193}
2194
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302195#ifdef CONFIG_HW_DISK_ENCRYPTION
2196int cryptfs_check_passwd_hw(const char* passwd)
2197{
2198 struct crypt_mnt_ftr crypt_ftr;
2199 int rc;
2200 unsigned char master_key[KEY_LEN_BYTES];
2201
2202 /* get key */
2203 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2204 SLOGE("Error getting crypt footer and key");
2205 return -1;
2206 }
2207
2208 /*
2209 * in case of manual encryption (from GUI), the encryption is done with
2210 * default password
2211 */
2212 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2213 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2214 * which was created with actual password before reboot.
2215 */
2216 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2217 if (rc) {
2218 SLOGE("password doesn't match");
2219 rc = ++crypt_ftr.failed_decrypt_count;
2220 put_crypt_ftr_and_key(&crypt_ftr);
2221 return rc;
2222 }
2223
2224 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2225 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2226
2227 if (rc) {
2228 SLOGE("Default password did not match on reboot encryption");
2229 return rc;
2230 }
2231
2232 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2233 put_crypt_ftr_and_key(&crypt_ftr);
2234 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2235 if (rc) {
2236 SLOGE("Could not change password on reboot encryption");
2237 return rc;
2238 }
2239 } else
2240 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2241 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2242
2243 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2244 cryptfs_clear_password();
2245 password = strdup(passwd);
2246 struct timespec now;
2247 clock_gettime(CLOCK_BOOTTIME, &now);
2248 password_expiry_time = now.tv_sec + password_max_age_seconds;
2249 }
2250
2251 return rc;
2252}
2253#endif
2254
Paul Crowley14c8c072018-09-18 13:30:21 -07002255int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002256 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00002257 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002258 SLOGE("cryptfs_check_passwd not valid for file encryption");
2259 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002260 }
2261
Paul Lawrencef4faa572014-01-29 13:31:03 -08002262 struct crypt_mnt_ftr crypt_ftr;
2263 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002264
Paul Lawrencef4faa572014-01-29 13:31:03 -08002265 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002266 if (rc) {
2267 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002268 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002269 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002270
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302271#ifdef CONFIG_HW_DISK_ENCRYPTION
2272 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2273 return cryptfs_check_passwd_hw(passwd);
2274#endif
2275
Paul Crowley14c8c072018-09-18 13:30:21 -07002276 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002277 if (rc) {
2278 SLOGE("Password did not match");
2279 return rc;
2280 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002281
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002282 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2283 // Here we have a default actual password but a real password
2284 // we must test against the scrypted value
2285 // First, we must delete the crypto block device that
2286 // test_mount_encrypted_fs leaves behind as a side effect
2287 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002288 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2289 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002290 if (rc) {
2291 SLOGE("Default password did not match on reboot encryption");
2292 return rc;
2293 }
2294
2295 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2296 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302297 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002298 if (rc) {
2299 SLOGE("Could not change password on reboot encryption");
2300 return rc;
2301 }
2302 }
2303
2304 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002305 cryptfs_clear_password();
2306 password = strdup(passwd);
2307 struct timespec now;
2308 clock_gettime(CLOCK_BOOTTIME, &now);
2309 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002310 }
2311
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002312 return rc;
2313}
2314
Paul Crowley14c8c072018-09-18 13:30:21 -07002315int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002316 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002317 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002318 char encrypted_state[PROPERTY_VALUE_MAX];
2319 int rc;
2320
2321 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002322 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002323 SLOGE("device not encrypted, aborting");
2324 return -2;
2325 }
2326
2327 if (!master_key_saved) {
2328 SLOGE("encrypted fs not yet mounted, aborting");
2329 return -1;
2330 }
2331
2332 if (!saved_mount_point) {
2333 SLOGE("encrypted fs failed to save mount point, aborting");
2334 return -1;
2335 }
2336
Ken Sumrall160b4d62013-04-22 12:15:39 -07002337 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002338 SLOGE("Error getting crypt footer and key\n");
2339 return -1;
2340 }
2341
2342 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2343 /* If the device has no password, then just say the password is valid */
2344 rc = 0;
2345 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302346#ifdef CONFIG_HW_DISK_ENCRYPTION
2347 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2348 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2349 rc = 0;
2350 else
2351 rc = -1;
2352 } else {
2353 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2354 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2355 /* They match, the password is correct */
2356 rc = 0;
2357 } else {
2358 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2359 sleep(1);
2360 rc = 1;
2361 }
2362 }
2363#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002364 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002365 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2366 /* They match, the password is correct */
2367 rc = 0;
2368 } else {
2369 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2370 sleep(1);
2371 rc = 1;
2372 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302373#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002374 }
2375
2376 return rc;
2377}
2378
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002379/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002380 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002381 * Presumably, at a minimum, the caller will update the
2382 * filesystem size and crypto_type_name after calling this function.
2383 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002384static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002385 off64_t off;
2386
2387 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002388 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002389 ftr->major_version = CURRENT_MAJOR_VERSION;
2390 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002391 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002392 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002393
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002394 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002395 case 1:
2396 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2397 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002398
Paul Crowley14c8c072018-09-18 13:30:21 -07002399 case 0:
2400 ftr->kdf_type = KDF_SCRYPT;
2401 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002402
Paul Crowley14c8c072018-09-18 13:30:21 -07002403 default:
2404 SLOGE("keymaster_check_compatibility failed");
2405 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002406 }
2407
Kenny Rootc4c70f12013-06-14 12:11:38 -07002408 get_device_scrypt_params(ftr);
2409
Ken Sumrall160b4d62013-04-22 12:15:39 -07002410 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2411 if (get_crypt_ftr_info(NULL, &off) == 0) {
2412 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002413 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002414 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002415
2416 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002417}
2418
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002419#define FRAMEWORK_BOOT_WAIT 60
2420
Paul Crowley14c8c072018-09-18 13:30:21 -07002421static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2422 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002423 if (fd == -1) {
2424 SLOGE("Error opening file %s", filename);
2425 return -1;
2426 }
2427
2428 char block[CRYPT_INPLACE_BUFSIZE];
2429 memset(block, 0, sizeof(block));
2430 if (unix_read(fd, block, sizeof(block)) < 0) {
2431 SLOGE("Error reading file %s", filename);
2432 close(fd);
2433 return -1;
2434 }
2435
2436 close(fd);
2437
2438 SHA256_CTX c;
2439 SHA256_Init(&c);
2440 SHA256_Update(&c, block, sizeof(block));
2441 SHA256_Final(buf, &c);
2442
2443 return 0;
2444}
2445
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002446static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2447 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002448 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002449 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002450
Paul Lawrence87999172014-02-20 12:21:31 -08002451 /* The size of the userdata partition, and add in the vold volumes below */
2452 tot_encryption_size = crypt_ftr->fs_size;
2453
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002454 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002455 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002456
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002457 if (rc == ENABLE_INPLACE_ERR_DEV) {
2458 /* Hack for b/17898962 */
2459 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2460 cryptfs_reboot(RebootType::reboot);
2461 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002462
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002463 if (!rc) {
2464 crypt_ftr->encrypted_upto = cur_encryption_done;
2465 }
Paul Lawrence87999172014-02-20 12:21:31 -08002466
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002467 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2468 /* The inplace routine never actually sets the progress to 100% due
2469 * to the round down nature of integer division, so set it here */
2470 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002471 }
2472
2473 return rc;
2474}
2475
Paul Crowleyb64933a2017-10-31 08:25:55 -07002476static int vold_unmountAll(void) {
2477 VolumeManager* vm = VolumeManager::Instance();
2478 return vm->unmountAll();
2479}
2480
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002481int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002482 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002483 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002484 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002485 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002486 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002487 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002488 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002489 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002490 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002491 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002492 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002493 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302494#ifdef CONFIG_HW_DISK_ENCRYPTION
2495 unsigned char newpw[32];
2496 int key_index = 0;
2497#endif
2498 int index = 0;
2499
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002500 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002501 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2502 /* An encryption was underway and was interrupted */
2503 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2504 crypt_ftr.encrypted_upto = 0;
2505 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002506
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002507 /* At this point, we are in an inconsistent state. Until we successfully
2508 complete encryption, a reboot will leave us broken. So mark the
2509 encryption failed in case that happens.
2510 On successfully completing encryption, remove this flag */
2511 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002512
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002513 put_crypt_ftr_and_key(&crypt_ftr);
2514 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2515 if (!check_ftr_sha(&crypt_ftr)) {
2516 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2517 put_crypt_ftr_and_key(&crypt_ftr);
2518 goto error_unencrypted;
2519 }
2520
2521 /* Doing a reboot-encryption*/
2522 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2523 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2524 rebootEncryption = true;
2525 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002526 } else {
2527 // We don't want to accidentally reference invalid data.
2528 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002529 }
2530
2531 property_get("ro.crypto.state", encrypted_state, "");
2532 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2533 SLOGE("Device is already running encrypted, aborting");
2534 goto error_unencrypted;
2535 }
2536
2537 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002538 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2539 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002540
Ken Sumrall3ed82362011-01-28 23:31:16 -08002541 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002542 uint64_t nr_sec;
2543 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002544 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2545 goto error_unencrypted;
2546 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002547
2548 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002549 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002550 uint64_t fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002551 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002552 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002553
Paul Lawrence87999172014-02-20 12:21:31 -08002554 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002555
2556 if (fs_size_sec > max_fs_size_sec) {
2557 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2558 goto error_unencrypted;
2559 }
2560 }
2561
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002562 /* Get a wakelock as this may take a while, and we don't want the
2563 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2564 * wants to keep the screen on, it can grab a full wakelock.
2565 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002566 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002567 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2568
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002569 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002570 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002571 */
2572 property_set("vold.decrypt", "trigger_shutdown_framework");
2573 SLOGD("Just asked init to shut down class main\n");
2574
Jeff Sharkey9c484982015-03-31 10:35:33 -07002575 /* Ask vold to unmount all devices that it manages */
2576 if (vold_unmountAll()) {
2577 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002578 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002579
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002580 /* no_ui means we are being called from init, not settings.
2581 Now we always reboot from settings, so !no_ui means reboot
2582 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002583 if (!no_ui) {
2584 /* Try fallback, which is to reboot and try there */
2585 onlyCreateHeader = true;
2586 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2587 if (breadcrumb == 0) {
2588 SLOGE("Failed to create breadcrumb file");
2589 goto error_shutting_down;
2590 }
2591 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002592 }
2593
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002594 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002595 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002596 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002597 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2598 goto error_shutting_down;
2599 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002600
Paul Lawrence87999172014-02-20 12:21:31 -08002601 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002602 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002603 } else {
2604 crypt_ftr.fs_size = nr_sec;
2605 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002606 /* At this point, we are in an inconsistent state. Until we successfully
2607 complete encryption, a reboot will leave us broken. So mark the
2608 encryption failed in case that happens.
2609 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002610 if (onlyCreateHeader) {
2611 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2612 } else {
2613 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2614 }
Paul Lawrence87999172014-02-20 12:21:31 -08002615 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302616#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002617 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2618 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302619#else
Paul Crowley14c8c072018-09-18 13:30:21 -07002620 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2621 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302622#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002623
Paul Lawrence87999172014-02-20 12:21:31 -08002624 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002625 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2626 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002627 SLOGE("Cannot create encrypted master key\n");
2628 goto error_shutting_down;
2629 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002630
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002631 /* Replace scrypted intermediate key if we are preparing for a reboot */
2632 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002633 unsigned char fake_master_key[MAX_KEY_LEN];
2634 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002635 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002636 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002637 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002638 }
2639
Paul Lawrence87999172014-02-20 12:21:31 -08002640 /* Write the key to the end of the partition */
2641 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002642
Paul Lawrence87999172014-02-20 12:21:31 -08002643 /* If any persistent data has been remembered, save it.
2644 * If none, create a valid empty table and save that.
2645 */
2646 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002647 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2648 if (pdata) {
2649 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2650 persist_data = pdata;
2651 }
Paul Lawrence87999172014-02-20 12:21:31 -08002652 }
2653 if (persist_data) {
2654 save_persistent_data();
2655 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002656 }
2657
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302658 /* When encryption triggered from settings, encryption starts after reboot.
2659 So set the encryption key when the actual encryption starts.
2660 */
2661#ifdef CONFIG_HW_DISK_ENCRYPTION
2662 if (previously_encrypted_upto == 0) {
2663 if (!rebootEncryption)
2664 clear_hw_device_encryption_key();
2665
2666 if (get_keymaster_hw_fde_passwd(
2667 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2668 newpw, crypt_ftr.salt, &crypt_ftr))
2669 key_index = set_hw_device_encryption_key(
2670 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2671 (char*)crypt_ftr.crypto_type_name);
2672 else
2673 key_index = set_hw_device_encryption_key((const char*)newpw,
2674 (char*) crypt_ftr.crypto_type_name);
2675 if (key_index < 0)
2676 goto error_shutting_down;
2677
2678 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2679 put_crypt_ftr_and_key(&crypt_ftr);
2680 }
2681#endif
2682
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002683 if (onlyCreateHeader) {
2684 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002685 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302686 } else {
2687 /* Do extra work for a better UX when doing the long inplace encryption */
2688 /* Now that /data is unmounted, we need to mount a tmpfs
2689 * /data, set a property saying we're doing inplace encryption,
2690 * and restart the framework.
2691 */
2692 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2693 goto error_shutting_down;
2694 }
2695 /* Tells the framework that inplace encryption is starting */
2696 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002697
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302698 /* restart the framework. */
2699 /* Create necessary paths on /data */
2700 prep_data_fs();
2701
2702 /* Ugh, shutting down the framework is not synchronous, so until it
2703 * can be fixed, this horrible hack will wait a moment for it all to
2704 * shut down before proceeding. Without it, some devices cannot
2705 * restart the graphics services.
2706 */
2707 sleep(2);
2708
Ajay Dudani87701e22014-09-17 21:02:52 -07002709 /* startup service classes main and late_start */
2710 property_set("vold.decrypt", "trigger_restart_min_framework");
2711 SLOGD("Just triggered restart_min_framework\n");
2712
2713 /* OK, the framework is restarted and will soon be showing a
2714 * progress bar. Time to setup an encrypted mapping, and
2715 * either write a new filesystem, or encrypt in place updating
2716 * the progress bar as we work.
2717 */
2718 }
2719
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002720 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302721#ifdef CONFIG_HW_DISK_ENCRYPTION
2722 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302723#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2724 strlcpy(crypto_blkdev, real_blkdev, sizeof(crypto_blkdev));
2725#else
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302726 create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev, crypto_blkdev,
2727 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302728#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302729 else
2730 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2731 CRYPTO_BLOCK_DEVICE, 0);
2732#else
Ken Sumrall29d8da82011-05-18 17:20:07 -07002733 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002734 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302735#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002736
Paul Lawrence87999172014-02-20 12:21:31 -08002737 /* If we are continuing, check checksums match */
2738 rc = 0;
2739 if (previously_encrypted_upto) {
2740 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302741#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2742 if (set_ice_param(START_ENCDEC)) {
2743 SLOGE("Failed to set ICE data");
2744 goto error_shutting_down;
2745 }
2746#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002747 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002748
Paul Crowley14c8c072018-09-18 13:30:21 -07002749 if (!rc &&
2750 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002751 SLOGE("Checksums do not match - trigger wipe");
2752 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002753 }
2754 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002755
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302756#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2757 if (set_ice_param(START_ENC)) {
2758 SLOGE("Failed to set ICE data");
2759 goto error_shutting_down;
2760 }
2761#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002762 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002763 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002764 previously_encrypted_upto);
2765 }
2766
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302767#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2768 if (set_ice_param(START_ENCDEC)) {
2769 SLOGE("Failed to set ICE data");
2770 goto error_shutting_down;
2771 }
2772#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002773 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002774 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002775 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002776 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002777 SLOGE("Error calculating checksum for continuing encryption");
2778 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002779 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002780 }
2781
2782 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302783#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2784 if (!is_ice_enabled())
2785 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2786#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002787 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302788#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002789
Paul Crowley14c8c072018-09-18 13:30:21 -07002790 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002791 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002792 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002793
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002794 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002795 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2796 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002797 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002798 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002799
Paul Lawrence6bfed202014-07-28 12:47:22 -07002800 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002801
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002802 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2803 char value[PROPERTY_VALUE_MAX];
2804 property_get("ro.crypto.state", value, "");
2805 if (!strcmp(value, "")) {
2806 /* default encryption - continue first boot sequence */
2807 property_set("ro.crypto.state", "encrypted");
2808 property_set("ro.crypto.type", "block");
2809 release_wake_lock(lockid);
2810 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2811 // Bring up cryptkeeper that will check the password and set it
2812 property_set("vold.decrypt", "trigger_shutdown_framework");
2813 sleep(2);
2814 property_set("vold.encrypt_progress", "");
2815 cryptfs_trigger_restart_min_framework();
2816 } else {
2817 cryptfs_check_passwd(DEFAULT_PASSWORD);
2818 cryptfs_restart_internal(1);
2819 }
2820 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002821 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002822 sleep(2); /* Give the UI a chance to show 100% progress */
2823 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002824 }
Paul Lawrence87999172014-02-20 12:21:31 -08002825 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002826 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002827 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002828 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002829 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002830 char value[PROPERTY_VALUE_MAX];
2831
Ken Sumrall319369a2012-06-27 16:30:18 -07002832 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002833 if (!strcmp(value, "1")) {
2834 /* wipe data if encryption failed */
2835 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002836 std::string err;
2837 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002838 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002839 if (!write_bootloader_message(options, &err)) {
2840 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002841 }
Josh Gaofec44372017-08-28 13:22:55 -07002842 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002843 } else {
2844 /* set property to trigger dialog */
2845 property_set("vold.encrypt_progress", "error_partially_encrypted");
2846 release_wake_lock(lockid);
2847 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002848 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002849 }
2850
Ken Sumrall3ed82362011-01-28 23:31:16 -08002851 /* hrm, the encrypt step claims success, but the reboot failed.
2852 * This should not happen.
2853 * Set the property and return. Hope the framework can deal with it.
2854 */
2855 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002856 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002857 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002858
2859error_unencrypted:
2860 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002861 if (lockid[0]) {
2862 release_wake_lock(lockid);
2863 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002864 return -1;
2865
2866error_shutting_down:
2867 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2868 * but the framework is stopped and not restarted to show the error, so it's up to
2869 * vold to restart the system.
2870 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002871 SLOGE(
2872 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2873 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002874 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002875
2876 /* shouldn't get here */
2877 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002878 if (lockid[0]) {
2879 release_wake_lock(lockid);
2880 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002881 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002882}
2883
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002884int cryptfs_enable(int type, const char* passwd, int no_ui) {
2885 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002886}
2887
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002888int cryptfs_enable_default(int no_ui) {
2889 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002890}
2891
Bill Peckham0db11972018-10-10 10:25:42 -07002892int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Paul Crowley38132a12016-02-09 09:50:32 +00002893 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002894 SLOGE("cryptfs_changepw not valid for file encryption");
2895 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002896 }
2897
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002898 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002899 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002900
2901 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002902 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002903 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002904 return -1;
2905 }
2906
Paul Lawrencef4faa572014-01-29 13:31:03 -08002907 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2908 SLOGE("Invalid crypt_type %d", crypt_type);
2909 return -1;
2910 }
2911
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002912 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002913 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002914 SLOGE("Error getting crypt footer and key");
2915 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002916 }
2917
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302918#ifdef CONFIG_HW_DISK_ENCRYPTION
2919 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2920 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
2921 else {
2922 crypt_ftr.crypt_type = crypt_type;
2923
2924 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
2925 DEFAULT_PASSWORD : newpw,
2926 crypt_ftr.salt,
2927 saved_master_key,
2928 crypt_ftr.master_key,
2929 &crypt_ftr, false);
2930 if (rc) {
2931 SLOGE("Encrypt master key failed: %d", rc);
2932 return -1;
2933 }
2934 /* save the key */
2935 put_crypt_ftr_and_key(&crypt_ftr);
2936
2937 return 0;
2938 }
2939#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08002940 crypt_ftr.crypt_type = crypt_type;
2941
Paul Crowley14c8c072018-09-18 13:30:21 -07002942 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07002943 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
2944 false);
JP Abgrall933216c2015-02-11 13:44:32 -08002945 if (rc) {
2946 SLOGE("Encrypt master key failed: %d", rc);
2947 return -1;
2948 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002949 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002950 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002951
2952 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302953#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002954}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002955
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302956#ifdef CONFIG_HW_DISK_ENCRYPTION
2957int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
2958{
2959 struct crypt_mnt_ftr crypt_ftr;
2960 int rc;
2961 int previous_type;
2962
2963 /* get key */
2964 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2965 SLOGE("Error getting crypt footer and key");
2966 return -1;
2967 }
2968
2969 previous_type = crypt_ftr.crypt_type;
2970 int rc1;
2971 unsigned char tmp_curpw[32] = {0};
2972 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
2973 DEFAULT_PASSWORD : currentpw, tmp_curpw,
2974 crypt_ftr.salt, &crypt_ftr);
2975
2976 crypt_ftr.crypt_type = crypt_type;
2977
2978 int ret, rc2;
2979 unsigned char tmp_newpw[32] = {0};
2980
2981 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
2982 DEFAULT_PASSWORD : newpw , tmp_newpw,
2983 crypt_ftr.salt, &crypt_ftr);
2984
2985 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2986 ret = update_hw_device_encryption_key(
2987 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
2988 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
2989 (char*)crypt_ftr.crypto_type_name);
2990 if (ret) {
2991 SLOGE("Error updating device encryption hardware key ret %d", ret);
2992 return -1;
2993 } else {
2994 SLOGI("Encryption hardware key updated");
2995 }
2996 }
2997
2998 /* save the key */
2999 put_crypt_ftr_and_key(&crypt_ftr);
3000 return 0;
3001}
3002#endif
3003
Rubin Xu85c01f92014-10-13 12:49:54 +01003004static unsigned int persist_get_max_entries(int encrypted) {
3005 struct crypt_mnt_ftr crypt_ftr;
3006 unsigned int dsize;
3007 unsigned int max_persistent_entries;
3008
3009 /* If encrypted, use the values from the crypt_ftr, otherwise
3010 * use the values for the current spec.
3011 */
3012 if (encrypted) {
3013 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3014 return -1;
3015 }
3016 dsize = crypt_ftr.persist_data_size;
3017 } else {
3018 dsize = CRYPT_PERSIST_DATA_SIZE;
3019 }
3020
Paul Crowley14c8c072018-09-18 13:30:21 -07003021 max_persistent_entries =
3022 (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
Rubin Xu85c01f92014-10-13 12:49:54 +01003023
3024 return max_persistent_entries;
3025}
3026
Paul Crowley14c8c072018-09-18 13:30:21 -07003027static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003028 unsigned int i;
3029
3030 if (persist_data == NULL) {
3031 return -1;
3032 }
3033 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3034 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3035 /* We found it! */
3036 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3037 return 0;
3038 }
3039 }
3040
3041 return -1;
3042}
3043
Paul Crowley14c8c072018-09-18 13:30:21 -07003044static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003045 unsigned int i;
3046 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003047 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003048
3049 if (persist_data == NULL) {
3050 return -1;
3051 }
3052
Rubin Xu85c01f92014-10-13 12:49:54 +01003053 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003054
3055 num = persist_data->persist_valid_entries;
3056
3057 for (i = 0; i < num; i++) {
3058 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3059 /* We found an existing entry, update it! */
3060 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3061 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3062 return 0;
3063 }
3064 }
3065
3066 /* We didn't find it, add it to the end, if there is room */
3067 if (persist_data->persist_valid_entries < max_persistent_entries) {
3068 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3069 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3070 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3071 persist_data->persist_valid_entries++;
3072 return 0;
3073 }
3074
3075 return -1;
3076}
3077
Rubin Xu85c01f92014-10-13 12:49:54 +01003078/**
3079 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3080 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3081 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003082int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003083 std::string key_ = key;
3084 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003085
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003086 std::string parsed_field;
3087 unsigned parsed_index;
3088
3089 std::string::size_type split = key_.find_last_of('_');
3090 if (split == std::string::npos) {
3091 parsed_field = key_;
3092 parsed_index = 0;
3093 } else {
3094 parsed_field = key_.substr(0, split);
3095 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003096 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003097
3098 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003099}
3100
3101/*
3102 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3103 * remaining entries starting from index will be deleted.
3104 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3105 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3106 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3107 *
3108 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003109static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003110 unsigned int i;
3111 unsigned int j;
3112 unsigned int num;
3113
3114 if (persist_data == NULL) {
3115 return PERSIST_DEL_KEY_ERROR_OTHER;
3116 }
3117
3118 num = persist_data->persist_valid_entries;
3119
Paul Crowley14c8c072018-09-18 13:30:21 -07003120 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003121 // Filter out to-be-deleted entries in place.
3122 for (i = 0; i < num; i++) {
3123 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3124 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3125 j++;
3126 }
3127 }
3128
3129 if (j < num) {
3130 persist_data->persist_valid_entries = j;
3131 // Zeroise the remaining entries
3132 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3133 return PERSIST_DEL_KEY_OK;
3134 } else {
3135 // Did not find an entry matching the given fieldname
3136 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3137 }
3138}
3139
Paul Crowley14c8c072018-09-18 13:30:21 -07003140static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003141 unsigned int i;
3142 unsigned int count;
3143
3144 if (persist_data == NULL) {
3145 return -1;
3146 }
3147
3148 count = 0;
3149 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3150 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3151 count++;
3152 }
3153 }
3154
3155 return count;
3156}
3157
Ken Sumrall160b4d62013-04-22 12:15:39 -07003158/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003159int cryptfs_getfield(const char* fieldname, char* value, int len) {
Paul Crowley38132a12016-02-09 09:50:32 +00003160 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003161 SLOGE("Cannot get field when file encrypted");
3162 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003163 }
3164
Ken Sumrall160b4d62013-04-22 12:15:39 -07003165 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003166 /* CRYPTO_GETFIELD_OK is success,
3167 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3168 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3169 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003170 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003171 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3172 int i;
3173 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003174
3175 if (persist_data == NULL) {
3176 load_persistent_data();
3177 if (persist_data == NULL) {
3178 SLOGE("Getfield error, cannot load persistent data");
3179 goto out;
3180 }
3181 }
3182
Rubin Xu85c01f92014-10-13 12:49:54 +01003183 // Read value from persistent entries. If the original value is split into multiple entries,
3184 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003185 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003186 // We found it, copy it to the caller's buffer and keep going until all entries are read.
Paul Crowley14c8c072018-09-18 13:30:21 -07003187 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003188 // value too small
3189 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3190 goto out;
3191 }
3192 rc = CRYPTO_GETFIELD_OK;
3193
3194 for (i = 1; /* break explicitly */; i++) {
3195 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003196 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003197 // If the fieldname is very long, we stop as soon as it begins to overflow the
3198 // maximum field length. At this point we have in fact fully read out the original
3199 // value because cryptfs_setfield would not allow fields with longer names to be
3200 // written in the first place.
3201 break;
3202 }
3203 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003204 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3205 // value too small.
3206 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3207 goto out;
3208 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003209 } else {
3210 // Exhaust all entries.
3211 break;
3212 }
3213 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003214 } else {
3215 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003216 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003217 }
3218
3219out:
3220 return rc;
3221}
3222
3223/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003224int cryptfs_setfield(const char* fieldname, const char* value) {
Paul Crowley38132a12016-02-09 09:50:32 +00003225 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003226 SLOGE("Cannot set field when file encrypted");
3227 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003228 }
3229
Ken Sumrall160b4d62013-04-22 12:15:39 -07003230 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003231 /* 0 is success, negative values are error */
3232 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003233 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003234 unsigned int field_id;
3235 char temp_field[PROPERTY_KEY_MAX];
3236 unsigned int num_entries;
3237 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003238
3239 if (persist_data == NULL) {
3240 load_persistent_data();
3241 if (persist_data == NULL) {
3242 SLOGE("Setfield error, cannot load persistent data");
3243 goto out;
3244 }
3245 }
3246
3247 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003248 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003249 encrypted = 1;
3250 }
3251
Rubin Xu85c01f92014-10-13 12:49:54 +01003252 // Compute the number of entries required to store value, each entry can store up to
3253 // (PROPERTY_VALUE_MAX - 1) chars
3254 if (strlen(value) == 0) {
3255 // Empty value also needs one entry to store.
3256 num_entries = 1;
3257 } else {
3258 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3259 }
3260
3261 max_keylen = strlen(fieldname);
3262 if (num_entries > 1) {
3263 // Need an extra "_%d" suffix.
3264 max_keylen += 1 + log10(num_entries);
3265 }
3266 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3267 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003268 goto out;
3269 }
3270
Rubin Xu85c01f92014-10-13 12:49:54 +01003271 // Make sure we have enough space to write the new value
3272 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3273 persist_get_max_entries(encrypted)) {
3274 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3275 goto out;
3276 }
3277
3278 // Now that we know persist_data has enough space for value, let's delete the old field first
3279 // to make up space.
3280 persist_del_keys(fieldname, 0);
3281
3282 if (persist_set_key(fieldname, value, encrypted)) {
3283 // fail to set key, should not happen as we have already checked the available space
3284 SLOGE("persist_set_key() error during setfield()");
3285 goto out;
3286 }
3287
3288 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003289 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003290
3291 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3292 // fail to set key, should not happen as we have already checked the available space.
3293 SLOGE("persist_set_key() error during setfield()");
3294 goto out;
3295 }
3296 }
3297
Ken Sumrall160b4d62013-04-22 12:15:39 -07003298 /* If we are running encrypted, save the persistent data now */
3299 if (encrypted) {
3300 if (save_persistent_data()) {
3301 SLOGE("Setfield error, cannot save persistent data");
3302 goto out;
3303 }
3304 }
3305
Rubin Xu85c01f92014-10-13 12:49:54 +01003306 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003307
3308out:
3309 return rc;
3310}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003311
3312/* Checks userdata. Attempt to mount the volume if default-
3313 * encrypted.
3314 * On success trigger next init phase and return 0.
3315 * Currently do not handle failure - see TODO below.
3316 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003317int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003318 int crypt_type = cryptfs_get_password_type();
3319 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3320 SLOGE("Bad crypt type - error");
3321 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003322 SLOGD(
3323 "Password is not default - "
3324 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003325 property_set("vold.decrypt", "trigger_restart_min_framework");
3326 return 0;
3327 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3328 SLOGD("Password is default - restarting filesystem");
3329 cryptfs_restart_internal(0);
3330 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003331 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003332 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003333 }
3334
Paul Lawrence6bfed202014-07-28 12:47:22 -07003335 /** Corrupt. Allow us to boot into framework, which will detect bad
3336 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003337 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003338 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003339 return 0;
3340}
3341
3342/* Returns type of the password, default, pattern, pin or password.
3343 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003344int cryptfs_get_password_type(void) {
Paul Crowley38132a12016-02-09 09:50:32 +00003345 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003346 SLOGE("cryptfs_get_password_type not valid for file encryption");
3347 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003348 }
3349
Paul Lawrencef4faa572014-01-29 13:31:03 -08003350 struct crypt_mnt_ftr crypt_ftr;
3351
3352 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3353 SLOGE("Error getting crypt footer and key\n");
3354 return -1;
3355 }
3356
Paul Lawrence6bfed202014-07-28 12:47:22 -07003357 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3358 return -1;
3359 }
3360
Paul Lawrencef4faa572014-01-29 13:31:03 -08003361 return crypt_ftr.crypt_type;
3362}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003363
Paul Crowley14c8c072018-09-18 13:30:21 -07003364const char* cryptfs_get_password() {
Paul Crowley38132a12016-02-09 09:50:32 +00003365 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003366 SLOGE("cryptfs_get_password not valid for file encryption");
3367 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003368 }
3369
Paul Lawrence399317e2014-03-10 13:20:50 -07003370 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003371 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003372 if (now.tv_sec < password_expiry_time) {
3373 return password;
3374 } else {
3375 cryptfs_clear_password();
3376 return 0;
3377 }
3378}
3379
Paul Crowley14c8c072018-09-18 13:30:21 -07003380void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003381 if (password) {
3382 size_t len = strlen(password);
3383 memset(password, 0, len);
3384 free(password);
3385 password = 0;
3386 password_expiry_time = 0;
3387 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003388}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003389
Paul Crowley14c8c072018-09-18 13:30:21 -07003390int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07003391 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07003392 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07003393}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303394
3395int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3396{
3397 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3398 SLOGE("Failed to initialize crypt_ftr");
3399 return -1;
3400 }
3401
3402 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3403 crypt_ftr->salt, crypt_ftr)) {
3404 SLOGE("Cannot create encrypted master key\n");
3405 return -1;
3406 }
3407
3408 //crypt_ftr->keysize = key_length / 8;
3409 return 0;
3410}
3411
3412int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3413 unsigned char* master_key)
3414{
3415 int rc;
3416
3417 unsigned char* intermediate_key = 0;
3418 size_t intermediate_key_size = 0;
3419
3420 if (password == 0 || *password == 0) {
3421 password = DEFAULT_PASSWORD;
3422 }
3423
3424 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3425 &intermediate_key_size);
3426
3427 if (rc) {
3428 SLOGE("Can't calculate intermediate key");
3429 return rc;
3430 }
3431
3432 int N = 1 << ftr->N_factor;
3433 int r = 1 << ftr->r_factor;
3434 int p = 1 << ftr->p_factor;
3435
3436 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3437
3438 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3439 ftr->salt, sizeof(ftr->salt), N, r, p,
3440 scrypted_intermediate_key,
3441 sizeof(scrypted_intermediate_key));
3442
3443 free(intermediate_key);
3444
3445 if (rc) {
3446 SLOGE("Can't scrypt intermediate key");
3447 return rc;
3448 }
3449
3450 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3451 intermediate_key_size);
3452}