blob: af98b95d1d2ec56e4f0dc51f1d9fb36bf4a3d4e0 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
Logan Chiend557d762018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
Daniel Rosenberg4f684712018-08-28 01:58:49 -070027#include "Checkpoint.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070029#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080030#include "Keymaster.h"
31#include "Process.h"
32#include "ScryptParameters.h"
Paul Crowley298fa322018-10-30 15:59:24 -070033#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080034#include "VoldUtil.h"
35#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080036
Eric Biggersed45ec32019-01-25 10:47:55 -080037#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080039#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080040#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070043#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070045#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070046#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070047#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080048#include <log/log.h>
Ken Sumralle550f782013-08-20 13:48:23 -070049#include <logwrap/logwrap.h>
Logan Chiend557d762018-05-02 11:36:45 +080050#include <openssl/evp.h>
51#include <openssl/sha.h>
Ken Sumrallc290eaf2011-03-07 23:40:35 -080052#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070053#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080054
55#include <ctype.h>
56#include <errno.h>
57#include <fcntl.h>
58#include <inttypes.h>
59#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080060#include <linux/kdev_t.h>
61#include <math.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080065#include <sys/mount.h>
66#include <sys/param.h>
67#include <sys/stat.h>
68#include <sys/types.h>
69#include <sys/wait.h>
70#include <time.h>
71#include <unistd.h>
72
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053073#ifdef CONFIG_HW_DISK_ENCRYPTION
74#include <cryptfs_hw.h>
75#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080076extern "C" {
77#include <crypto_scrypt.h>
78}
Mark Salyzyn3e971272014-01-21 13:27:04 -080079
Eric Biggersed45ec32019-01-25 10:47:55 -080080using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080081using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080082using android::fs_mgr::GetEntryForMountPoint;
David Andersonb9224732019-05-13 13:02:54 -070083using namespace android::dm;
Paul Crowley298fa322018-10-30 15:59:24 -070084using namespace std::chrono_literals;
85
Mark Salyzyn5eecc442014-02-12 14:16:14 -080086#define UNUSED __attribute__((unused))
87
Jason parks70a4b3f2011-01-28 10:10:47 -060088#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080089
90constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
91constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070092constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080093
94// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070095static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060096
Paul Crowley14c8c072018-09-18 13:30:21 -070097#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070098
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053099#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700100#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800101
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800102#define CRYPTO_BLOCK_DEVICE "userdata"
103
104#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
105
Ken Sumrall29d8da82011-05-18 17:20:07 -0700106#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700107#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700108
Ken Sumralle919efe2012-09-29 17:07:41 -0700109#define TABLE_LOAD_RETRIES 10
110
Shawn Willden47ba10d2014-09-03 17:07:06 -0600111#define RSA_KEY_SIZE 2048
112#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
113#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600114#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530115#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700116
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700117#define RETRY_MOUNT_ATTEMPTS 10
118#define RETRY_MOUNT_DELAY_SECONDS 1
119
Paul Crowley5afbc622017-11-27 09:42:17 -0800120#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
121
Paul Crowley73473332017-11-21 15:43:51 -0800122static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
123
Greg Kaiser59ad0182018-02-16 13:01:36 -0800124static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700125static char* saved_mount_point;
126static int master_key_saved = 0;
127static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800128
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530129static int previous_type;
130
131#ifdef CONFIG_HW_DISK_ENCRYPTION
132static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
133 unsigned char *ikey, void *params);
134static void convert_key_to_hex_ascii(const unsigned char *master_key,
135 unsigned int keysize, char *master_key_ascii);
136static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
137static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
138 const char *passwd, const char *mount_point, const char *label);
139int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
140 const char *newpw);
141int cryptfs_check_passwd_hw(char *passwd);
142int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
143 unsigned char* master_key);
144
145static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
146 unsigned int keysize, char *master_key_ascii)
147{
148 unsigned int i, a;
149 unsigned char nibble;
150
151 for (i = 0, a = 0; i < keysize; i++, a += 2) {
152 /* For each byte, write out two ascii hex digits */
153 nibble = (master_key[i] >> 4) & 0xf;
154 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
155
156 nibble = master_key[i] & 0xf;
157 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
158 }
159
160 /* Add the null termination */
161 master_key_ascii[a] = '\0';
162}
163
164static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
165 unsigned char* salt,
166 const struct crypt_mnt_ftr *ftr)
167{
168 /* if newpw updated, return 0
169 * if newpw not updated return -1
170 */
171 int rc = -1;
172
173 if (should_use_keymaster()) {
174 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
175 SLOGE("scrypt failed");
176 } else {
177 rc = 0;
178 }
179 }
180
181 return rc;
182}
183
184static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
185{
186 unsigned char newpw[32] = {0};
187 int key_index;
188 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
189 key_index = set_hw_device_encryption_key(passwd,
190 (char*) crypt_ftr->crypto_type_name);
191 else
192 key_index = set_hw_device_encryption_key((const char*)newpw,
193 (char*) crypt_ftr->crypto_type_name);
194 return key_index;
195}
196
197static int verify_and_update_hw_fde_passwd(const char *passwd,
198 struct crypt_mnt_ftr* crypt_ftr)
199{
200 char* new_passwd = NULL;
201 unsigned char newpw[32] = {0};
202 int key_index = -1;
203 int passwd_updated = -1;
204 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
205
206 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
207 if (key_index < 0) {
208 ++crypt_ftr->failed_decrypt_count;
209
210 if (ascii_passwd_updated) {
211 SLOGI("Ascii password was updated");
212 } else {
213 /* Code in else part would execute only once:
214 * When device is upgraded from L->M release.
215 * Once upgraded, code flow should never come here.
216 * L release passed actual password in hex, so try with hex
217 * Each nible of passwd was encoded as a byte, so allocate memory
218 * twice of password len plus one more byte for null termination
219 */
220 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
221 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
222 if (new_passwd == NULL) {
223 SLOGE("System out of memory. Password verification incomplete");
224 goto out;
225 }
226 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
227 } else {
228 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
229 if (new_passwd == NULL) {
230 SLOGE("System out of memory. Password verification incomplete");
231 goto out;
232 }
233 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
234 strlen(passwd), new_passwd);
235 }
236 key_index = set_hw_device_encryption_key((const char*)new_passwd,
237 (char*) crypt_ftr->crypto_type_name);
238 if (key_index >=0) {
239 crypt_ftr->failed_decrypt_count = 0;
240 SLOGI("Hex password verified...will try to update with Ascii value");
241 /* Before updating password, tie that with keymaster to tie with ROT */
242
243 if (get_keymaster_hw_fde_passwd(passwd, newpw,
244 crypt_ftr->salt, crypt_ftr)) {
245 passwd_updated = update_hw_device_encryption_key(new_passwd,
246 passwd, (char*)crypt_ftr->crypto_type_name);
247 } else {
248 passwd_updated = update_hw_device_encryption_key(new_passwd,
249 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
250 }
251
252 if (passwd_updated >= 0) {
253 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
254 SLOGI("Ascii password recorded and updated");
255 } else {
256 SLOGI("Passwd verified, could not update...Will try next time");
257 }
258 } else {
259 ++crypt_ftr->failed_decrypt_count;
260 }
261 free(new_passwd);
262 }
263 } else {
264 if (!ascii_passwd_updated)
265 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
266 }
267out:
268 // update footer before leaving
269 put_crypt_ftr_and_key(crypt_ftr);
270 return key_index;
271}
272#endif
273
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700274/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700275static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000276 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700277}
278
279/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700280static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800281 if (ftr->keymaster_blob_size) {
282 SLOGI("Already have key");
283 return 0;
284 }
285
Paul Crowley14c8c072018-09-18 13:30:21 -0700286 int rc = keymaster_create_key_for_cryptfs_scrypt(
287 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
288 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000289 if (rc) {
290 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800291 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000292 ftr->keymaster_blob_size = 0;
293 }
294 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700295 return -1;
296 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000297 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700298}
299
Shawn Willdene17a9c42014-09-08 13:04:08 -0600300/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700301static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
302 const size_t object_size, unsigned char** signature,
303 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600304 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600305 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600306 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600307
Shawn Willdene17a9c42014-09-08 13:04:08 -0600308 // To sign a message with RSA, the message must satisfy two
309 // constraints:
310 //
311 // 1. The message, when interpreted as a big-endian numeric value, must
312 // be strictly less than the public modulus of the RSA key. Note
313 // that because the most significant bit of the public modulus is
314 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
315 // key), an n-bit message with most significant bit 0 always
316 // satisfies this requirement.
317 //
318 // 2. The message must have the same length in bits as the public
319 // modulus of the RSA key. This requirement isn't mathematically
320 // necessary, but is necessary to ensure consistency in
321 // implementations.
322 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600323 case KDF_SCRYPT_KEYMASTER:
324 // This ensures the most significant byte of the signed message
325 // is zero. We could have zero-padded to the left instead, but
326 // this approach is slightly more robust against changes in
327 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600328 // so) because we really should be using a proper deterministic
329 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800330 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600331 SLOGI("Signing safely-padded object");
332 break;
333 default:
334 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000335 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600336 }
Paul Crowley73473332017-11-21 15:43:51 -0800337 for (;;) {
338 auto result = keymaster_sign_object_for_cryptfs_scrypt(
339 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
340 to_sign_size, signature, signature_size);
341 switch (result) {
342 case KeymasterSignResult::ok:
343 return 0;
344 case KeymasterSignResult::upgrade:
345 break;
346 default:
347 return -1;
348 }
349 SLOGD("Upgrading key");
350 if (keymaster_upgrade_key_for_cryptfs_scrypt(
351 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
352 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
353 &ftr->keymaster_blob_size) != 0) {
354 SLOGE("Failed to upgrade key");
355 return -1;
356 }
357 if (put_crypt_ftr_and_key(ftr) != 0) {
358 SLOGE("Failed to write upgraded key to disk");
359 }
360 SLOGD("Key upgraded successfully");
361 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600362}
363
Paul Lawrence399317e2014-03-10 13:20:50 -0700364/* Store password when userdata is successfully decrypted and mounted.
365 * Cleared by cryptfs_clear_password
366 *
367 * To avoid a double prompt at boot, we need to store the CryptKeeper
368 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
369 * Since the entire framework is torn down and rebuilt after encryption,
370 * we have to use a daemon or similar to store the password. Since vold
371 * is secured against IPC except from system processes, it seems a reasonable
372 * place to store this.
373 *
374 * password should be cleared once it has been used.
375 *
376 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800377 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700378static char* password = 0;
379static int password_expiry_time = 0;
380static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800381
Paul Crowley14c8c072018-09-18 13:30:21 -0700382enum class RebootType { reboot, recovery, shutdown };
383static void cryptfs_reboot(RebootType rt) {
384 switch (rt) {
385 case RebootType::reboot:
386 property_set(ANDROID_RB_PROPERTY, "reboot");
387 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800388
Paul Crowley14c8c072018-09-18 13:30:21 -0700389 case RebootType::recovery:
390 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
391 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800392
Paul Crowley14c8c072018-09-18 13:30:21 -0700393 case RebootType::shutdown:
394 property_set(ANDROID_RB_PROPERTY, "shutdown");
395 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700396 }
Paul Lawrence87999172014-02-20 12:21:31 -0800397
Ken Sumralladfba362013-06-04 16:37:52 -0700398 sleep(20);
399
400 /* Shouldn't get here, reboot should happen before sleep times out */
401 return;
402}
403
Greg Kaiser38723f22018-02-16 13:35:35 -0800404namespace {
405
406struct CryptoType;
407
408// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700409const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800410
411struct CryptoType {
412 // We should only be constructing CryptoTypes as part of
413 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
414 // which isn't pure or fully protected as a concession to being able to
415 // do it all at compile time. Add new CryptoTypes in
416 // supported_crypto_types[] below.
417 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
418 constexpr CryptoType set_keysize(uint32_t size) const {
419 return CryptoType(this->property_name, this->crypto_name, size);
420 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700421 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800422 return CryptoType(property, this->crypto_name, this->keysize);
423 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700424 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800425 return CryptoType(this->property_name, crypto, this->keysize);
426 }
427
Paul Crowley14c8c072018-09-18 13:30:21 -0700428 constexpr const char* get_property_name() const { return property_name; }
429 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800430 constexpr uint32_t get_keysize() const { return keysize; }
431
Paul Crowley14c8c072018-09-18 13:30:21 -0700432 private:
433 const char* property_name;
434 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800435 uint32_t keysize;
436
Paul Crowley14c8c072018-09-18 13:30:21 -0700437 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800438 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700439 friend const CryptoType& get_crypto_type();
440 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800441};
442
443// We only want to parse this read-only property once. But we need to wait
444// until the system is initialized before we can read it. So we use a static
445// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700446const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800447 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
448 return crypto_type;
449}
450
451constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700452 .set_property_name("AES-128-CBC")
453 .set_crypto_name("aes-cbc-essiv:sha256")
454 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800455
456constexpr CryptoType supported_crypto_types[] = {
457 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800458 CryptoType()
459 .set_property_name("adiantum")
460 .set_crypto_name("xchacha12,aes-adiantum-plain64")
461 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800462 // Add new CryptoTypes here. Order is not important.
463};
464
Greg Kaiser38723f22018-02-16 13:35:35 -0800465// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
466// We confirm all supported_crypto_types have a small enough keysize and
467// had both set_property_name() and set_crypto_name() called.
468
469template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700470constexpr size_t array_length(T (&)[N]) {
471 return N;
472}
Greg Kaiser38723f22018-02-16 13:35:35 -0800473
474constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
475 return (index >= array_length(supported_crypto_types));
476}
477
Paul Crowley14c8c072018-09-18 13:30:21 -0700478constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800479 return ((crypto_type.get_property_name() != nullptr) &&
480 (crypto_type.get_crypto_name() != nullptr) &&
481 (crypto_type.get_keysize() <= MAX_KEY_LEN));
482}
483
484// Note in C++11 that constexpr functions can only have a single line.
485// So our code is a bit convoluted (using recursion instead of a loop),
486// but it's asserting at compile time that all of our key lengths are valid.
487constexpr bool validateSupportedCryptoTypes(size_t index) {
488 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700489 (isValidCryptoType(supported_crypto_types[index]) &&
490 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800491}
492
493static_assert(validateSupportedCryptoTypes(0),
494 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
495 "incompletely constructed.");
496// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
497
Greg Kaiser38723f22018-02-16 13:35:35 -0800498// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700499const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800500 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
501 char paramstr[PROPERTY_VALUE_MAX];
502
Paul Crowley14c8c072018-09-18 13:30:21 -0700503 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
504 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800505 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
506 return ctype;
507 }
508 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700509 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
510 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800511 return default_crypto_type;
512}
513
514} // namespace
515
Kenny Rootc4c70f12013-06-14 12:11:38 -0700516/**
517 * Gets the default device scrypt parameters for key derivation time tuning.
518 * The parameters should lead to about one second derivation time for the
519 * given device.
520 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700521static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700522 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000523 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700524
Paul Crowley63c18d32016-02-10 14:02:47 +0000525 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
526 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
527 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
528 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700529 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000530 ftr->N_factor = Nf;
531 ftr->r_factor = rf;
532 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700533}
534
Greg Kaiser57f9af62018-02-16 13:13:58 -0800535uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800536 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800537}
538
Paul Crowley14c8c072018-09-18 13:30:21 -0700539const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800540 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800541}
542
Tom Cherry4c5bde22019-01-29 14:34:01 -0800543static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800544 int fd, block_size;
545 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200546 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800547
Paul Crowley14c8c072018-09-18 13:30:21 -0700548 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800549 SLOGE("Cannot open device to get filesystem size ");
550 return 0;
551 }
552
553 if (lseek64(fd, 1024, SEEK_SET) < 0) {
554 SLOGE("Cannot seek to superblock");
555 return 0;
556 }
557
558 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
559 SLOGE("Cannot read superblock");
560 return 0;
561 }
562
563 close(fd);
564
Daniel Rosenberge82df162014-08-15 22:19:23 +0000565 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
566 SLOGE("Not a valid ext4 superblock");
567 return 0;
568 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800569 block_size = 1024 << sb.s_log_block_size;
570 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200571 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800572
573 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200574 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800575}
576
Tom Cherry4c5bde22019-01-29 14:34:01 -0800577static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
578 for (const auto& entry : fstab_default) {
579 if (!entry.fs_mgr_flags.vold_managed &&
580 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
581 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
582 if (key_loc != nullptr) {
583 *key_loc = entry.key_loc;
584 }
585 if (real_blk_device != nullptr) {
586 *real_blk_device = entry.blk_device;
587 }
588 return;
589 }
590 }
591}
592
Paul Crowley14c8c072018-09-18 13:30:21 -0700593static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
594 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200595 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700596 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700597 char key_loc[PROPERTY_VALUE_MAX];
598 char real_blkdev[PROPERTY_VALUE_MAX];
599 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700600
Paul Crowley14c8c072018-09-18 13:30:21 -0700601 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800602 std::string key_loc;
603 std::string real_blkdev;
604 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700605
Tom Cherry4c5bde22019-01-29 14:34:01 -0800606 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200607 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700608 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
609 * encryption info footer and key, and plenty of bytes to spare for future
610 * growth.
611 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800612 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200613 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700614 cached_data = 1;
615 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800616 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700617 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700618 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800619 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700620 cached_off = 0;
621 cached_data = 1;
622 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700623 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700624
Paul Crowley14c8c072018-09-18 13:30:21 -0700625 if (cached_data) {
626 if (metadata_fname) {
627 *metadata_fname = cached_metadata_fname;
628 }
629 if (off) {
630 *off = cached_off;
631 }
632 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700633 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700634
Paul Crowley14c8c072018-09-18 13:30:21 -0700635 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700636}
637
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800638/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700639static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800640 SHA256_CTX c;
641 SHA256_Init(&c);
642 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
643 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
644 SHA256_Final(crypt_ftr->sha256, &c);
645}
646
Ken Sumralle8744072011-01-18 22:01:55 -0800647/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800648 * update the failed mount count but not change the key.
649 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700650static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
651 int fd;
652 unsigned int cnt;
653 /* starting_off is set to the SEEK_SET offset
654 * where the crypto structure starts
655 */
656 off64_t starting_off;
657 int rc = -1;
658 char* fname = NULL;
659 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800660
Paul Crowley14c8c072018-09-18 13:30:21 -0700661 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800662
Paul Crowley14c8c072018-09-18 13:30:21 -0700663 if (get_crypt_ftr_info(&fname, &starting_off)) {
664 SLOGE("Unable to get crypt_ftr_info\n");
665 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800666 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700667 if (fname[0] != '/') {
668 SLOGE("Unexpected value for crypto key location\n");
669 return -1;
670 }
671 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
672 SLOGE("Cannot open footer file %s for put\n", fname);
673 return -1;
674 }
Ken Sumralle8744072011-01-18 22:01:55 -0800675
Paul Crowley14c8c072018-09-18 13:30:21 -0700676 /* Seek to the start of the crypt footer */
677 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
678 SLOGE("Cannot seek to real block device footer\n");
679 goto errout;
680 }
681
682 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
683 SLOGE("Cannot write real block device footer\n");
684 goto errout;
685 }
686
687 fstat(fd, &statbuf);
688 /* If the keys are kept on a raw block device, do not try to truncate it. */
689 if (S_ISREG(statbuf.st_mode)) {
690 if (ftruncate(fd, 0x4000)) {
691 SLOGE("Cannot set footer file size\n");
692 goto errout;
693 }
694 }
695
696 /* Success! */
697 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800698
699errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700700 close(fd);
701 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800702}
703
Paul Crowley14c8c072018-09-18 13:30:21 -0700704static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800705 struct crypt_mnt_ftr copy;
706 memcpy(&copy, crypt_ftr, sizeof(copy));
707 set_ftr_sha(&copy);
708 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
709}
710
Paul Crowley14c8c072018-09-18 13:30:21 -0700711static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700712 return TEMP_FAILURE_RETRY(read(fd, buff, len));
713}
714
Paul Crowley14c8c072018-09-18 13:30:21 -0700715static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700716 return TEMP_FAILURE_RETRY(write(fd, buff, len));
717}
718
Paul Crowley14c8c072018-09-18 13:30:21 -0700719static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700720 memset(pdata, 0, len);
721 pdata->persist_magic = PERSIST_DATA_MAGIC;
722 pdata->persist_valid_entries = 0;
723}
724
725/* A routine to update the passed in crypt_ftr to the lastest version.
726 * fd is open read/write on the device that holds the crypto footer and persistent
727 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
728 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
729 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700730static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700731 int orig_major = crypt_ftr->major_version;
732 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700733
Kenny Root7434b312013-06-14 11:29:53 -0700734 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700735 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700736 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700737
Kenny Rootc4c70f12013-06-14 12:11:38 -0700738 SLOGW("upgrading crypto footer to 1.1");
739
Paul Crowley14c8c072018-09-18 13:30:21 -0700740 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700741 if (pdata == NULL) {
742 SLOGE("Cannot allocate persisent data\n");
743 return;
744 }
745 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
746
747 /* Need to initialize the persistent data area */
748 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
749 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100750 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700751 return;
752 }
753 /* Write all zeros to the first copy, making it invalid */
754 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
755
756 /* Write a valid but empty structure to the second copy */
757 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
758 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
759
760 /* Update the footer */
761 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
762 crypt_ftr->persist_data_offset[0] = pdata_offset;
763 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
764 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100765 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700766 }
767
Paul Lawrencef4faa572014-01-29 13:31:03 -0800768 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700769 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800770 /* But keep the old kdf_type.
771 * It will get updated later to KDF_SCRYPT after the password has been verified.
772 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700773 crypt_ftr->kdf_type = KDF_PBKDF2;
774 get_device_scrypt_params(crypt_ftr);
775 crypt_ftr->minor_version = 2;
776 }
777
Paul Lawrencef4faa572014-01-29 13:31:03 -0800778 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
779 SLOGW("upgrading crypto footer to 1.3");
780 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
781 crypt_ftr->minor_version = 3;
782 }
783
Kenny Root7434b312013-06-14 11:29:53 -0700784 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
785 if (lseek64(fd, offset, SEEK_SET) == -1) {
786 SLOGE("Cannot seek to crypt footer\n");
787 return;
788 }
789 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700790 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700791}
792
Paul Crowley14c8c072018-09-18 13:30:21 -0700793static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
794 int fd;
795 unsigned int cnt;
796 off64_t starting_off;
797 int rc = -1;
798 char* fname = NULL;
799 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700800
Paul Crowley14c8c072018-09-18 13:30:21 -0700801 if (get_crypt_ftr_info(&fname, &starting_off)) {
802 SLOGE("Unable to get crypt_ftr_info\n");
803 return -1;
804 }
805 if (fname[0] != '/') {
806 SLOGE("Unexpected value for crypto key location\n");
807 return -1;
808 }
809 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
810 SLOGE("Cannot open footer file %s for get\n", fname);
811 return -1;
812 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800813
Paul Crowley14c8c072018-09-18 13:30:21 -0700814 /* Make sure it's 16 Kbytes in length */
815 fstat(fd, &statbuf);
816 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
817 SLOGE("footer file %s is not the expected size!\n", fname);
818 goto errout;
819 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700820
Paul Crowley14c8c072018-09-18 13:30:21 -0700821 /* Seek to the start of the crypt footer */
822 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
823 SLOGE("Cannot seek to real block device footer\n");
824 goto errout;
825 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700826
Paul Crowley14c8c072018-09-18 13:30:21 -0700827 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
828 SLOGE("Cannot read real block device footer\n");
829 goto errout;
830 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800831
Paul Crowley14c8c072018-09-18 13:30:21 -0700832 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
833 SLOGE("Bad magic for real block device %s\n", fname);
834 goto errout;
835 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800836
Paul Crowley14c8c072018-09-18 13:30:21 -0700837 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
838 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
839 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
840 goto errout;
841 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800842
Paul Crowley14c8c072018-09-18 13:30:21 -0700843 // We risk buffer overflows with oversized keys, so we just reject them.
844 // 0-sized keys are problematic (essentially by-passing encryption), and
845 // AES-CBC key wrapping only works for multiples of 16 bytes.
846 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
847 (crypt_ftr->keysize > MAX_KEY_LEN)) {
848 SLOGE(
849 "Invalid keysize (%u) for block device %s; Must be non-zero, "
850 "divisible by 16, and <= %d\n",
851 crypt_ftr->keysize, fname, MAX_KEY_LEN);
852 goto errout;
853 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800854
Paul Crowley14c8c072018-09-18 13:30:21 -0700855 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
856 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
857 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
858 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800859
Paul Crowley14c8c072018-09-18 13:30:21 -0700860 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
861 * copy on disk before returning.
862 */
863 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
864 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
865 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800866
Paul Crowley14c8c072018-09-18 13:30:21 -0700867 /* Success! */
868 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800869
870errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700871 close(fd);
872 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800873}
874
Paul Crowley14c8c072018-09-18 13:30:21 -0700875static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700876 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
877 crypt_ftr->persist_data_offset[1]) {
878 SLOGE("Crypt_ftr persist data regions overlap");
879 return -1;
880 }
881
882 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
883 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
884 return -1;
885 }
886
887 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700888 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700889 CRYPT_FOOTER_OFFSET) {
890 SLOGE("Persistent data extends past crypto footer");
891 return -1;
892 }
893
894 return 0;
895}
896
Paul Crowley14c8c072018-09-18 13:30:21 -0700897static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700898 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700899 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700900 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700901 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700902 int found = 0;
903 int fd;
904 int ret;
905 int i;
906
907 if (persist_data) {
908 /* Nothing to do, we've already loaded or initialized it */
909 return 0;
910 }
911
Ken Sumrall160b4d62013-04-22 12:15:39 -0700912 /* If not encrypted, just allocate an empty table and initialize it */
913 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700914 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800915 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700916 if (pdata) {
917 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
918 persist_data = pdata;
919 return 0;
920 }
921 return -1;
922 }
923
Paul Crowley14c8c072018-09-18 13:30:21 -0700924 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700925 return -1;
926 }
927
Paul Crowley14c8c072018-09-18 13:30:21 -0700928 if ((crypt_ftr.major_version < 1) ||
929 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700930 SLOGE("Crypt_ftr version doesn't support persistent data");
931 return -1;
932 }
933
934 if (get_crypt_ftr_info(&fname, NULL)) {
935 return -1;
936 }
937
938 ret = validate_persistent_data_storage(&crypt_ftr);
939 if (ret) {
940 return -1;
941 }
942
Paul Crowley14c8c072018-09-18 13:30:21 -0700943 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700944 if (fd < 0) {
945 SLOGE("Cannot open %s metadata file", fname);
946 return -1;
947 }
948
Wei Wang4375f1b2017-02-24 17:43:01 -0800949 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800950 if (pdata == NULL) {
951 SLOGE("Cannot allocate memory for persistent data");
952 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700953 }
954
955 for (i = 0; i < 2; i++) {
956 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
957 SLOGE("Cannot seek to read persistent data on %s", fname);
958 goto err2;
959 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700960 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700961 SLOGE("Error reading persistent data on iteration %d", i);
962 goto err2;
963 }
964 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
965 found = 1;
966 break;
967 }
968 }
969
970 if (!found) {
971 SLOGI("Could not find valid persistent data, creating");
972 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
973 }
974
975 /* Success */
976 persist_data = pdata;
977 close(fd);
978 return 0;
979
980err2:
981 free(pdata);
982
983err:
984 close(fd);
985 return -1;
986}
987
Paul Crowley14c8c072018-09-18 13:30:21 -0700988static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700989 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700990 struct crypt_persist_data* pdata;
991 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700992 off64_t write_offset;
993 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700994 int fd;
995 int ret;
996
997 if (persist_data == NULL) {
998 SLOGE("No persistent data to save");
999 return -1;
1000 }
1001
Paul Crowley14c8c072018-09-18 13:30:21 -07001002 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001003 return -1;
1004 }
1005
Paul Crowley14c8c072018-09-18 13:30:21 -07001006 if ((crypt_ftr.major_version < 1) ||
1007 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001008 SLOGE("Crypt_ftr version doesn't support persistent data");
1009 return -1;
1010 }
1011
1012 ret = validate_persistent_data_storage(&crypt_ftr);
1013 if (ret) {
1014 return -1;
1015 }
1016
1017 if (get_crypt_ftr_info(&fname, NULL)) {
1018 return -1;
1019 }
1020
Paul Crowley14c8c072018-09-18 13:30:21 -07001021 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001022 if (fd < 0) {
1023 SLOGE("Cannot open %s metadata file", fname);
1024 return -1;
1025 }
1026
Wei Wang4375f1b2017-02-24 17:43:01 -08001027 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001028 if (pdata == NULL) {
1029 SLOGE("Cannot allocate persistant data");
1030 goto err;
1031 }
1032
1033 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1034 SLOGE("Cannot seek to read persistent data on %s", fname);
1035 goto err2;
1036 }
1037
1038 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001039 SLOGE("Error reading persistent data before save");
1040 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001041 }
1042
1043 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1044 /* The first copy is the curent valid copy, so write to
1045 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001046 write_offset = crypt_ftr.persist_data_offset[1];
1047 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001048 } else {
1049 /* The second copy must be the valid copy, so write to
1050 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001051 write_offset = crypt_ftr.persist_data_offset[0];
1052 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001053 }
1054
1055 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001056 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001057 SLOGE("Cannot seek to write persistent data");
1058 goto err2;
1059 }
1060 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001061 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001062 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001063 SLOGE("Cannot seek to erase previous persistent data");
1064 goto err2;
1065 }
1066 fsync(fd);
1067 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001068 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001069 SLOGE("Cannot write to erase previous persistent data");
1070 goto err2;
1071 }
1072 fsync(fd);
1073 } else {
1074 SLOGE("Cannot write to save persistent data");
1075 goto err2;
1076 }
1077
1078 /* Success */
1079 free(pdata);
1080 close(fd);
1081 return 0;
1082
1083err2:
1084 free(pdata);
1085err:
1086 close(fd);
1087 return -1;
1088}
1089
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001090/* Convert a binary key of specified length into an ascii hex string equivalent,
1091 * without the leading 0x and with null termination
1092 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001093static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1094 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001095 unsigned int i, a;
1096 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001097
Paul Crowley14c8c072018-09-18 13:30:21 -07001098 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001099 /* For each byte, write out two ascii hex digits */
1100 nibble = (master_key[i] >> 4) & 0xf;
1101 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001102
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001103 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001104 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001105 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001106
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001107 /* Add the null termination */
1108 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001109}
1110
Eric Biggersed45ec32019-01-25 10:47:55 -08001111/*
1112 * If the ro.crypto.fde_sector_size system property is set, append the
1113 * parameters to make dm-crypt use the specified crypto sector size and round
1114 * the crypto device size down to a crypto sector boundary.
1115 */
David Andersonb9224732019-05-13 13:02:54 -07001116static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001117 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001118 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001119
Eric Biggersed45ec32019-01-25 10:47:55 -08001120 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1121 unsigned int sector_size;
1122
1123 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1124 (sector_size & (sector_size - 1)) != 0) {
1125 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1126 DM_CRYPT_SECTOR_SIZE, value);
1127 return -1;
1128 }
1129
David Andersonb9224732019-05-13 13:02:54 -07001130 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001131
1132 // With this option, IVs will match the sector numbering, instead
1133 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001134 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001135
1136 // Round the crypto device size down to a crypto sector boundary.
1137 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001138 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001139 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001140}
1141
Paul Crowley5afbc622017-11-27 09:42:17 -08001142static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1143 const char* real_blk_name, char* crypto_blk_name, const char* name,
1144 uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001145 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001146
David Andersonb9224732019-05-13 13:02:54 -07001147 // We need two ASCII characters to represent each byte, and need space for
1148 // the '\0' terminator.
1149 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1150 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001151
David Andersonb9224732019-05-13 13:02:54 -07001152 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1153 (const char*)crypt_ftr->crypto_type_name,
1154 master_key_ascii, 0, real_blk_name, 0);
1155 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156
Paul Crowley5afbc622017-11-27 09:42:17 -08001157 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001158 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001159 }
David Andersonb9224732019-05-13 13:02:54 -07001160 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001161 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001162 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001163 }
David Andersonb9224732019-05-13 13:02:54 -07001164
1165 DmTable table;
1166 table.AddTarget(std::move(target));
1167
1168 int load_count = 1;
1169 while (load_count < TABLE_LOAD_RETRIES) {
1170 if (dm.CreateDevice(name, table)) {
1171 break;
1172 }
1173 load_count++;
1174 }
1175
1176 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001177 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001178 return -1;
1179 }
1180 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001181 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1182 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001183
David Andersonb9224732019-05-13 13:02:54 -07001184 std::string path;
1185 if (!dm.GetDmDevicePathByName(name, &path)) {
1186 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1187 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001188 }
David Andersonb9224732019-05-13 13:02:54 -07001189 snprintf(crypto_blk_name, MAXPATHLEN, "%s", path.c_str());
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001190
Paul Crowley298fa322018-10-30 15:59:24 -07001191 /* Ensure the dm device has been created before returning. */
1192 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1193 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001194 return -1;
Paul Crowley298fa322018-10-30 15:59:24 -07001195 }
David Andersonb9224732019-05-13 13:02:54 -07001196 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001197}
1198
David Andersonb9224732019-05-13 13:02:54 -07001199static int delete_crypto_blk_dev(const std::string& name) {
1200 auto& dm = DeviceMapper::Instance();
1201 if (!dm.DeleteDevice(name)) {
1202 SLOGE("Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
1203 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001204 }
David Andersonb9224732019-05-13 13:02:54 -07001205 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001206}
1207
Paul Crowley14c8c072018-09-18 13:30:21 -07001208static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1209 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001210 SLOGI("Using pbkdf2 for cryptfs KDF");
1211
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001213 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1214 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001215}
1216
Paul Crowley14c8c072018-09-18 13:30:21 -07001217static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001218 SLOGI("Using scrypt for cryptfs KDF");
1219
Paul Crowley14c8c072018-09-18 13:30:21 -07001220 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001221
1222 int N = 1 << ftr->N_factor;
1223 int r = 1 << ftr->r_factor;
1224 int p = 1 << ftr->p_factor;
1225
1226 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001227 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001228 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001229
Paul Crowley14c8c072018-09-18 13:30:21 -07001230 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001231}
1232
Paul Crowley14c8c072018-09-18 13:30:21 -07001233static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1234 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001235 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1236
1237 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001238 size_t signature_size;
1239 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001240 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001241
1242 int N = 1 << ftr->N_factor;
1243 int r = 1 << ftr->r_factor;
1244 int p = 1 << ftr->p_factor;
1245
Paul Crowley14c8c072018-09-18 13:30:21 -07001246 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001247 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001248
1249 if (rc) {
1250 SLOGE("scrypt failed");
1251 return -1;
1252 }
1253
Paul Crowley14c8c072018-09-18 13:30:21 -07001254 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001255 SLOGE("Signing failed");
1256 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001257 }
1258
Paul Crowley14c8c072018-09-18 13:30:21 -07001259 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1260 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001261 free(signature);
1262
1263 if (rc) {
1264 SLOGE("scrypt failed");
1265 return -1;
1266 }
1267
1268 return 0;
1269}
1270
Paul Crowley14c8c072018-09-18 13:30:21 -07001271static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1272 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001273 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1274 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001275 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001276 EVP_CIPHER_CTX e_ctx;
1277 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001278 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001279
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001280 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001281 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001282
1283 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001284 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001285 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001286 SLOGE("keymaster_create_key failed");
1287 return -1;
1288 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001289
Paul Crowley14c8c072018-09-18 13:30:21 -07001290 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1291 SLOGE("scrypt failed");
1292 return -1;
1293 }
1294 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001295
Paul Crowley14c8c072018-09-18 13:30:21 -07001296 case KDF_SCRYPT:
1297 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1298 SLOGE("scrypt failed");
1299 return -1;
1300 }
1301 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001302
Paul Crowley14c8c072018-09-18 13:30:21 -07001303 default:
1304 SLOGE("Invalid kdf_type");
1305 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001306 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001307
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001308 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001309 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001310 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1311 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001312 SLOGE("EVP_EncryptInit failed\n");
1313 return -1;
1314 }
1315 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001316
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001317 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001318 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1319 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001320 SLOGE("EVP_EncryptUpdate failed\n");
1321 return -1;
1322 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001323 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001324 SLOGE("EVP_EncryptFinal failed\n");
1325 return -1;
1326 }
1327
Greg Kaiser59ad0182018-02-16 13:01:36 -08001328 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001329 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1330 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001331 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001332
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001333 /* Store the scrypt of the intermediate key, so we can validate if it's a
1334 password error or mount error when things go wrong.
1335 Note there's no need to check for errors, since if this is incorrect, we
1336 simply won't wipe userdata, which is the correct default behavior
1337 */
1338 int N = 1 << crypt_ftr->N_factor;
1339 int r = 1 << crypt_ftr->r_factor;
1340 int p = 1 << crypt_ftr->p_factor;
1341
Paul Crowley14c8c072018-09-18 13:30:21 -07001342 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1343 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001344 sizeof(crypt_ftr->scrypted_intermediate_key));
1345
1346 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001347 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001348 }
1349
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001350 EVP_CIPHER_CTX_cleanup(&e_ctx);
1351
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001352 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001353}
1354
Paul Crowley14c8c072018-09-18 13:30:21 -07001355static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1356 const unsigned char* encrypted_master_key, size_t keysize,
1357 unsigned char* decrypted_master_key, kdf_func kdf,
1358 void* kdf_params, unsigned char** intermediate_key,
1359 size_t* intermediate_key_size) {
1360 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1361 EVP_CIPHER_CTX d_ctx;
1362 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001363
Paul Crowley14c8c072018-09-18 13:30:21 -07001364 /* Turn the password into an intermediate key and IV that can decrypt the
1365 master key */
1366 if (kdf(passwd, salt, ikey, kdf_params)) {
1367 SLOGE("kdf failed");
1368 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001369 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001370
Paul Crowley14c8c072018-09-18 13:30:21 -07001371 /* Initialize the decryption engine */
1372 EVP_CIPHER_CTX_init(&d_ctx);
1373 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1374 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1375 return -1;
1376 }
1377 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1378 /* Decrypt the master key */
1379 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1380 keysize)) {
1381 return -1;
1382 }
1383 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1384 return -1;
1385 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001386
Paul Crowley14c8c072018-09-18 13:30:21 -07001387 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1388 return -1;
1389 }
1390
1391 /* Copy intermediate key if needed by params */
1392 if (intermediate_key && intermediate_key_size) {
1393 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1394 if (*intermediate_key) {
1395 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1396 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1397 }
1398 }
1399
1400 EVP_CIPHER_CTX_cleanup(&d_ctx);
1401
1402 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001403}
1404
Paul Crowley14c8c072018-09-18 13:30:21 -07001405static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001406 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001407 *kdf = scrypt_keymaster;
1408 *kdf_params = ftr;
1409 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001410 *kdf = scrypt;
1411 *kdf_params = ftr;
1412 } else {
1413 *kdf = pbkdf2;
1414 *kdf_params = NULL;
1415 }
1416}
1417
Paul Crowley14c8c072018-09-18 13:30:21 -07001418static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1419 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1420 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001421 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001422 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001423 int ret;
1424
1425 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001426 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1427 decrypted_master_key, kdf, kdf_params, intermediate_key,
1428 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001429 if (ret != 0) {
1430 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001431 }
1432
1433 return ret;
1434}
1435
Paul Crowley14c8c072018-09-18 13:30:21 -07001436static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1437 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001438 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001439
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001440 /* Get some random bits for a key and salt */
1441 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1442 return -1;
1443 }
1444 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1445 return -1;
1446 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001447
1448 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301449 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001450}
1451
Paul Crowley14c8c072018-09-18 13:30:21 -07001452int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001453 int i, err, rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301454#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001455
1456 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001457 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001458 if (umount(mountpoint) == 0) {
1459 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001460 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001461
1462 if (errno == EINVAL) {
1463 /* EINVAL is returned if the directory is not a mountpoint,
1464 * i.e. there is no filesystem mounted there. So just get out.
1465 */
1466 break;
1467 }
1468
1469 err = errno;
1470
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301471 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001472 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301473 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001474 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001475 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301476 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001477 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001478 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001479 }
1480 }
1481
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301482 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001483 }
1484
1485 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001486 SLOGD("unmounting %s succeeded\n", mountpoint);
1487 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001488 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001489 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1490 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1491 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001492 }
1493
1494 return rc;
1495}
1496
Paul Crowley14c8c072018-09-18 13:30:21 -07001497static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001498 // NOTE: post_fs_data results in init calling back around to vold, so all
1499 // callers to this method must be async
1500
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001501 /* Do the prep of the /data filesystem */
1502 property_set("vold.post_fs_data_done", "0");
1503 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001504 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001505
Ken Sumrallc5872692013-05-14 15:26:31 -07001506 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001507 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001508 /* We timed out to prep /data in time. Continue wait. */
1509 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001510 }
Wei Wang42e38102017-06-07 10:46:12 -07001511 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001512}
1513
Paul Crowley14c8c072018-09-18 13:30:21 -07001514static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001515 // Mark the footer as bad
1516 struct crypt_mnt_ftr crypt_ftr;
1517 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1518 SLOGE("Failed to get crypto footer - panic");
1519 return;
1520 }
1521
1522 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1523 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1524 SLOGE("Failed to set crypto footer - panic");
1525 return;
1526 }
1527}
1528
Paul Crowley14c8c072018-09-18 13:30:21 -07001529static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001530 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001531 SLOGE("Failed to mount tmpfs on data - panic");
1532 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001533 }
1534
1535 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1536 SLOGE("Failed to trigger post fs data - panic");
1537 return;
1538 }
1539
1540 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1541 SLOGE("Failed to trigger restart min framework - panic");
1542 return;
1543 }
1544}
1545
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001546/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001547static int cryptfs_restart_internal(int restart_main) {
Yifan Hong804afe12019-02-07 12:56:47 -08001548 std::string crypto_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301549#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001550 std::string blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301551#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001552 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001553 static int restart_successful = 0;
1554
1555 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001556 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001557 SLOGE("Encrypted filesystem not validated, aborting");
1558 return -1;
1559 }
1560
1561 if (restart_successful) {
1562 SLOGE("System already restarted with encrypted disk, aborting");
1563 return -1;
1564 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001565
Paul Lawrencef4faa572014-01-29 13:31:03 -08001566 if (restart_main) {
1567 /* Here is where we shut down the framework. The init scripts
Martijn Coenenf629b002019-04-24 10:41:11 +02001568 * start all services in one of these classes: core, early_hal, hal,
1569 * main and late_start. To get to the minimal UI for PIN entry, we
1570 * need to start core, early_hal, hal and main. When we want to
1571 * shutdown the framework again, we need to stop most of the services in
1572 * these classes, but only those services that were started after
1573 * /data was mounted. This excludes critical services like vold and
1574 * ueventd, which need to keep running. We could possible stop
1575 * even fewer services, but because we want services to pick up APEX
1576 * libraries from the real /data, restarting is better, as it makes
1577 * these devices consistent with FBE devices and lets them use the
1578 * most recent code.
1579 *
1580 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001581 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenf629b002019-04-24 10:41:11 +02001582 * We then restart the class core, hal, main, and also the class
1583 * late_start.
1584 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001585 * At the moment, I've only put a few things in late_start that I know
1586 * are not needed to bring up the framework, and that also cause problems
1587 * with unmounting the tmpfs /data, but I hope to add add more services
1588 * to the late_start class as we optimize this to decrease the delay
1589 * till the user is asked for the password to the filesystem.
1590 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001591
Martijn Coenenf629b002019-04-24 10:41:11 +02001592 /* The init files are setup to stop the right set of services when
1593 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001594 */
Martijn Coenenf629b002019-04-24 10:41:11 +02001595 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001596 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001597
Paul Lawrencef4faa572014-01-29 13:31:03 -08001598 /* Ugh, shutting down the framework is not synchronous, so until it
1599 * can be fixed, this horrible hack will wait a moment for it all to
1600 * shut down before proceeding. Without it, some devices cannot
1601 * restart the graphics services.
1602 */
1603 sleep(2);
1604 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001605
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001606 /* Now that the framework is shutdown, we should be able to umount()
1607 * the tmpfs filesystem, and mount the real one.
1608 */
1609
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301610#if defined(CONFIG_HW_DISK_ENCRYPTION)
1611#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1612 if (is_ice_enabled()) {
Yifan Hong804afe12019-02-07 12:56:47 -08001613 get_crypt_info(nullptr, &blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301614 if (set_ice_param(START_ENCDEC)) {
1615 SLOGE("Failed to set ICE data");
1616 return -1;
1617 }
1618 }
1619#else
Yifan Hong804afe12019-02-07 12:56:47 -08001620 blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1621 if (blkdev.empty()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301622 SLOGE("fs_crypto_blkdev not set\n");
1623 return -1;
1624 }
1625 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1626#endif
1627#else
Yifan Hong804afe12019-02-07 12:56:47 -08001628 crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1629 if (crypto_blkdev.empty()) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001630 SLOGE("fs_crypto_blkdev not set\n");
1631 return -1;
1632 }
1633
Paul Crowley14c8c072018-09-18 13:30:21 -07001634 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301635#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001636 /* If ro.crypto.readonly is set to 1, mount the decrypted
1637 * filesystem readonly. This is used when /data is mounted by
1638 * recovery mode.
1639 */
1640 char ro_prop[PROPERTY_VALUE_MAX];
1641 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001642 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001643 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1644 if (entry != nullptr) {
1645 entry->flags |= MS_RDONLY;
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07001646 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001647 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001648
Ken Sumralle5032c42012-04-01 23:58:44 -07001649 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001650 int retries = RETRY_MOUNT_ATTEMPTS;
1651 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001652
1653 /*
1654 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1655 * partitions in the fsck domain.
1656 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001657 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001658 SLOGE("Failed to setexeccon");
1659 return -1;
1660 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001661 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301662#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001663 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, blkdev.data(), 0,
Bill Peckham0db11972018-10-10 10:25:42 -07001664 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301665#else
Yifan Hong804afe12019-02-07 12:56:47 -08001666 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev.data(), 0,
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001667 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301668#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001669 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1670 /* TODO: invoke something similar to
1671 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1672 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301673#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001674 SLOGI("Failed to mount %s because it is busy - waiting", blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301675#else
Yifan Hong804afe12019-02-07 12:56:47 -08001676 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301677#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001678 if (--retries) {
1679 sleep(RETRY_MOUNT_DELAY_SECONDS);
1680 } else {
1681 /* Let's hope that a reboot clears away whatever is keeping
1682 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001683 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001684 }
1685 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301686#ifdef CONFIG_HW_DISK_ENCRYPTION
1687 if (--retries) {
1688 sleep(RETRY_MOUNT_DELAY_SECONDS);
1689 } else {
1690 SLOGE("Failed to mount decrypted data");
1691 cryptfs_set_corrupt();
1692 cryptfs_trigger_restart_min_framework();
1693 SLOGI("Started framework to offer wipe");
1694 return -1;
1695 }
1696#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001697 SLOGE("Failed to mount decrypted data");
1698 cryptfs_set_corrupt();
1699 cryptfs_trigger_restart_min_framework();
1700 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001701 if (setexeccon(NULL)) {
1702 SLOGE("Failed to setexeccon");
1703 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001704 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301705#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001706 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001707 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001708 if (setexeccon(NULL)) {
1709 SLOGE("Failed to setexeccon");
1710 return -1;
1711 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001712
Ken Sumralle5032c42012-04-01 23:58:44 -07001713 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001714 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001715 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001716
1717 /* startup service classes main and late_start */
1718 property_set("vold.decrypt", "trigger_restart_framework");
1719 SLOGD("Just triggered restart_framework\n");
1720
1721 /* Give it a few moments to get started */
1722 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301723#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301725#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001726
Ken Sumrall0cc16632011-01-18 20:32:26 -08001727 if (rc == 0) {
1728 restart_successful = 1;
1729 }
1730
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001731 return rc;
1732}
1733
Paul Crowley14c8c072018-09-18 13:30:21 -07001734int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001735 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001736 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001737 SLOGE("cryptfs_restart not valid for file encryption:");
1738 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001739 }
1740
Paul Lawrencef4faa572014-01-29 13:31:03 -08001741 /* Call internal implementation forcing a restart of main service group */
1742 return cryptfs_restart_internal(1);
1743}
1744
Paul Crowley14c8c072018-09-18 13:30:21 -07001745static int do_crypto_complete(const char* mount_point) {
1746 struct crypt_mnt_ftr crypt_ftr;
1747 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001748
Paul Crowley14c8c072018-09-18 13:30:21 -07001749 property_get("ro.crypto.state", encrypted_state, "");
1750 if (strcmp(encrypted_state, "encrypted")) {
1751 SLOGE("not running with encryption, aborting");
1752 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001753 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001754
Paul Crowley14c8c072018-09-18 13:30:21 -07001755 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001756 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001757 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1758 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001759
Paul Crowley14c8c072018-09-18 13:30:21 -07001760 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001761 std::string key_loc;
1762 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001763
Paul Crowley14c8c072018-09-18 13:30:21 -07001764 /*
1765 * Only report this error if key_loc is a file and it exists.
1766 * If the device was never encrypted, and /data is not mountable for
1767 * some reason, returning 1 should prevent the UI from presenting the
1768 * a "enter password" screen, or worse, a "press button to wipe the
1769 * device" screen.
1770 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001771 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001772 SLOGE("master key file does not exist, aborting");
1773 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1774 } else {
1775 SLOGE("Error getting crypt footer and key\n");
1776 return CRYPTO_COMPLETE_BAD_METADATA;
1777 }
1778 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001779
Paul Crowley14c8c072018-09-18 13:30:21 -07001780 // Test for possible error flags
1781 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1782 SLOGE("Encryption process is partway completed\n");
1783 return CRYPTO_COMPLETE_PARTIAL;
1784 }
1785
1786 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1787 SLOGE("Encryption process was interrupted but cannot continue\n");
1788 return CRYPTO_COMPLETE_INCONSISTENT;
1789 }
1790
1791 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1792 SLOGE("Encryption is successful but data is corrupt\n");
1793 return CRYPTO_COMPLETE_CORRUPT;
1794 }
1795
1796 /* We passed the test! We shall diminish, and return to the west */
1797 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001798}
1799
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301800#ifdef CONFIG_HW_DISK_ENCRYPTION
1801static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1802 const char *passwd, const char *mount_point, const char *label)
1803{
Bill Peckham0db11972018-10-10 10:25:42 -07001804 /* Allocate enough space for a 256 bit key, but we may use less */
1805 unsigned char decrypted_master_key[32];
1806 char crypto_blkdev[MAXPATHLEN];
Yifan Hong804afe12019-02-07 12:56:47 -08001807 std::string real_blkdev;
Bill Peckham0db11972018-10-10 10:25:42 -07001808 unsigned int orig_failed_decrypt_count;
1809 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301810
Bill Peckham0db11972018-10-10 10:25:42 -07001811 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1812 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301813
Yifan Hong804afe12019-02-07 12:56:47 -08001814 get_crypt_info(nullptr, &real_blkdev);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301815
Bill Peckham0db11972018-10-10 10:25:42 -07001816 int key_index = 0;
1817 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1818 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
1819 if (key_index < 0) {
1820 rc = crypt_ftr->failed_decrypt_count;
1821 goto errout;
1822 }
1823 else {
1824 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301825#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07001826 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
Yifan Hong804afe12019-02-07 12:56:47 -08001827 real_blkdev.c_str(), crypto_blkdev, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07001828 SLOGE("Error creating decrypted block device");
1829 rc = -1;
1830 goto errout;
1831 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301832#endif
Bill Peckham0db11972018-10-10 10:25:42 -07001833 } else {
1834 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
Yifan Hong804afe12019-02-07 12:56:47 -08001835 real_blkdev.c_str(), crypto_blkdev, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07001836 SLOGE("Error creating decrypted block device");
1837 rc = -1;
1838 goto errout;
1839 }
1840 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301841 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301842 }
1843
Bill Peckham0db11972018-10-10 10:25:42 -07001844 if (rc == 0) {
1845 crypt_ftr->failed_decrypt_count = 0;
1846 if (orig_failed_decrypt_count != 0) {
1847 put_crypt_ftr_and_key(crypt_ftr);
1848 }
1849
1850 /* Save the name of the crypto block device
1851 * so we can mount it when restarting the framework. */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301852#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07001853 if (!is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301854#endif
Bill Peckham0db11972018-10-10 10:25:42 -07001855 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1856 master_key_saved = 1;
1857 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301858
Bill Peckham0db11972018-10-10 10:25:42 -07001859 errout:
1860 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301861}
1862#endif
1863
Paul Crowley14c8c072018-09-18 13:30:21 -07001864static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1865 const char* mount_point, const char* label) {
1866 unsigned char decrypted_master_key[MAX_KEY_LEN];
1867 char crypto_blkdev[MAXPATHLEN];
Tom Cherry4c5bde22019-01-29 14:34:01 -08001868 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001869 char tmp_mount_point[64];
1870 unsigned int orig_failed_decrypt_count;
1871 int rc;
1872 int use_keymaster = 0;
1873 int upgrade = 0;
1874 unsigned char* intermediate_key = 0;
1875 size_t intermediate_key_size = 0;
1876 int N = 1 << crypt_ftr->N_factor;
1877 int r = 1 << crypt_ftr->r_factor;
1878 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301879
Paul Crowley14c8c072018-09-18 13:30:21 -07001880 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1881 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001882
Paul Crowley14c8c072018-09-18 13:30:21 -07001883 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1884 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1885 &intermediate_key_size)) {
1886 SLOGE("Failed to decrypt master key\n");
1887 rc = -1;
1888 goto errout;
1889 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001890 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001891
Tom Cherry4c5bde22019-01-29 14:34:01 -08001892 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001893
Paul Crowley14c8c072018-09-18 13:30:21 -07001894 // Create crypto block device - all (non fatal) code paths
1895 // need it
Tom Cherry4c5bde22019-01-29 14:34:01 -08001896 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
1897 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001898 SLOGE("Error creating decrypted block device\n");
1899 rc = -1;
1900 goto errout;
1901 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001902
Paul Crowley14c8c072018-09-18 13:30:21 -07001903 /* Work out if the problem is the password or the data */
1904 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001905
Paul Crowley14c8c072018-09-18 13:30:21 -07001906 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1907 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1908 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001909
Paul Crowley14c8c072018-09-18 13:30:21 -07001910 // Does the key match the crypto footer?
1911 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1912 sizeof(scrypted_intermediate_key)) == 0) {
1913 SLOGI("Password matches");
1914 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001915 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001916 /* Try mounting the file system anyway, just in case the problem's with
1917 * the footer, not the key. */
1918 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1919 mkdir(tmp_mount_point, 0755);
Tom Cherry4c5bde22019-01-29 14:34:01 -08001920 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001921 SLOGE("Error temp mounting decrypted block device\n");
1922 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001923
Paul Crowley14c8c072018-09-18 13:30:21 -07001924 rc = ++crypt_ftr->failed_decrypt_count;
1925 put_crypt_ftr_and_key(crypt_ftr);
1926 } else {
1927 /* Success! */
1928 SLOGI("Password did not match but decrypted drive mounted - continue");
1929 umount(tmp_mount_point);
1930 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001931 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001932 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001933
Paul Crowley14c8c072018-09-18 13:30:21 -07001934 if (rc == 0) {
1935 crypt_ftr->failed_decrypt_count = 0;
1936 if (orig_failed_decrypt_count != 0) {
1937 put_crypt_ftr_and_key(crypt_ftr);
1938 }
1939
1940 /* Save the name of the crypto block device
1941 * so we can mount it when restarting the framework. */
1942 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1943
1944 /* Also save a the master key so we can reencrypted the key
1945 * the key when we want to change the password on it. */
1946 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1947 saved_mount_point = strdup(mount_point);
1948 master_key_saved = 1;
1949 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1950 rc = 0;
1951
1952 // Upgrade if we're not using the latest KDF.
1953 use_keymaster = keymaster_check_compatibility();
1954 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1955 // Don't allow downgrade
1956 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1957 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1958 upgrade = 1;
1959 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1960 crypt_ftr->kdf_type = KDF_SCRYPT;
1961 upgrade = 1;
1962 }
1963
1964 if (upgrade) {
1965 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001966 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07001967 if (!rc) {
1968 rc = put_crypt_ftr_and_key(crypt_ftr);
1969 }
1970 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1971
1972 // Do not fail even if upgrade failed - machine is bootable
1973 // Note that if this code is ever hit, there is a *serious* problem
1974 // since KDFs should never fail. You *must* fix the kdf before
1975 // proceeding!
1976 if (rc) {
1977 SLOGW(
1978 "Upgrade failed with error %d,"
1979 " but continuing with previous state",
1980 rc);
1981 rc = 0;
1982 }
1983 }
1984 }
1985
1986errout:
1987 if (intermediate_key) {
1988 memset(intermediate_key, 0, intermediate_key_size);
1989 free(intermediate_key);
1990 }
1991 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001992}
1993
Ken Sumrall29d8da82011-05-18 17:20:07 -07001994/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001995 * Called by vold when it's asked to mount an encrypted external
1996 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001997 * as any metadata is been stored in a separate, small partition. We
1998 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001999 *
2000 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002001 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002002int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
2003 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002004 uint64_t nr_sec = 0;
2005 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002006 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002007 return -1;
2008 }
2009
Jeff Sharkey9c484982015-03-31 10:35:33 -07002010 struct crypt_mnt_ftr ext_crypt_ftr;
2011 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2012 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002013 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07002014 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002015 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002016 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002017 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002018 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2019 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002020
Paul Crowley385cb8c2018-03-29 13:27:23 -07002021 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07002022}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002023
Jeff Sharkey9c484982015-03-31 10:35:33 -07002024/*
2025 * Called by vold when it's asked to unmount an encrypted external
2026 * storage volume.
2027 */
2028int cryptfs_revert_ext_volume(const char* label) {
David Andersonb9224732019-05-13 13:02:54 -07002029 return delete_crypto_blk_dev(label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002030}
2031
Paul Crowley14c8c072018-09-18 13:30:21 -07002032int cryptfs_crypto_complete(void) {
2033 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002034}
2035
Paul Crowley14c8c072018-09-18 13:30:21 -07002036int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002037 char encrypted_state[PROPERTY_VALUE_MAX];
2038 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002039 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2040 SLOGE(
2041 "encrypted fs already validated or not running with encryption,"
2042 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002043 return -1;
2044 }
2045
2046 if (get_crypt_ftr_and_key(crypt_ftr)) {
2047 SLOGE("Error getting crypt footer and key");
2048 return -1;
2049 }
2050
2051 return 0;
2052}
2053
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302054#ifdef CONFIG_HW_DISK_ENCRYPTION
2055int cryptfs_check_passwd_hw(const char* passwd)
2056{
2057 struct crypt_mnt_ftr crypt_ftr;
2058 int rc;
2059 unsigned char master_key[KEY_LEN_BYTES];
2060
2061 /* get key */
2062 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2063 SLOGE("Error getting crypt footer and key");
2064 return -1;
2065 }
2066
2067 /*
2068 * in case of manual encryption (from GUI), the encryption is done with
2069 * default password
2070 */
2071 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2072 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2073 * which was created with actual password before reboot.
2074 */
2075 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2076 if (rc) {
2077 SLOGE("password doesn't match");
2078 rc = ++crypt_ftr.failed_decrypt_count;
2079 put_crypt_ftr_and_key(&crypt_ftr);
2080 return rc;
2081 }
2082
2083 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2084 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2085
2086 if (rc) {
2087 SLOGE("Default password did not match on reboot encryption");
2088 return rc;
2089 }
2090
2091 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2092 put_crypt_ftr_and_key(&crypt_ftr);
2093 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2094 if (rc) {
2095 SLOGE("Could not change password on reboot encryption");
2096 return rc;
2097 }
2098 } else
2099 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2100 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2101
2102 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2103 cryptfs_clear_password();
2104 password = strdup(passwd);
2105 struct timespec now;
2106 clock_gettime(CLOCK_BOOTTIME, &now);
2107 password_expiry_time = now.tv_sec + password_max_age_seconds;
2108 }
2109
2110 return rc;
2111}
2112#endif
2113
Paul Crowley14c8c072018-09-18 13:30:21 -07002114int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002115 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002116 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002117 SLOGE("cryptfs_check_passwd not valid for file encryption");
2118 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002119 }
2120
Paul Lawrencef4faa572014-01-29 13:31:03 -08002121 struct crypt_mnt_ftr crypt_ftr;
2122 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002123
Paul Lawrencef4faa572014-01-29 13:31:03 -08002124 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002125 if (rc) {
2126 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002127 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002128 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002129
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302130#ifdef CONFIG_HW_DISK_ENCRYPTION
2131 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2132 return cryptfs_check_passwd_hw(passwd);
2133#endif
2134
Paul Crowley14c8c072018-09-18 13:30:21 -07002135 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002136 if (rc) {
2137 SLOGE("Password did not match");
2138 return rc;
2139 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002140
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002141 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2142 // Here we have a default actual password but a real password
2143 // we must test against the scrypted value
2144 // First, we must delete the crypto block device that
2145 // test_mount_encrypted_fs leaves behind as a side effect
2146 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002147 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2148 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002149 if (rc) {
2150 SLOGE("Default password did not match on reboot encryption");
2151 return rc;
2152 }
2153
2154 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2155 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302156 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002157 if (rc) {
2158 SLOGE("Could not change password on reboot encryption");
2159 return rc;
2160 }
2161 }
2162
2163 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002164 cryptfs_clear_password();
2165 password = strdup(passwd);
2166 struct timespec now;
2167 clock_gettime(CLOCK_BOOTTIME, &now);
2168 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002169 }
2170
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002171 return rc;
2172}
2173
Paul Crowley14c8c072018-09-18 13:30:21 -07002174int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002175 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002176 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002177 char encrypted_state[PROPERTY_VALUE_MAX];
2178 int rc;
2179
2180 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002181 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002182 SLOGE("device not encrypted, aborting");
2183 return -2;
2184 }
2185
2186 if (!master_key_saved) {
2187 SLOGE("encrypted fs not yet mounted, aborting");
2188 return -1;
2189 }
2190
2191 if (!saved_mount_point) {
2192 SLOGE("encrypted fs failed to save mount point, aborting");
2193 return -1;
2194 }
2195
Ken Sumrall160b4d62013-04-22 12:15:39 -07002196 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002197 SLOGE("Error getting crypt footer and key\n");
2198 return -1;
2199 }
2200
2201 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2202 /* If the device has no password, then just say the password is valid */
2203 rc = 0;
2204 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302205#ifdef CONFIG_HW_DISK_ENCRYPTION
2206 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2207 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2208 rc = 0;
2209 else
2210 rc = -1;
2211 } else {
2212 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2213 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2214 /* They match, the password is correct */
2215 rc = 0;
2216 } else {
2217 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2218 sleep(1);
2219 rc = 1;
2220 }
2221 }
2222#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002223 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002224 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2225 /* They match, the password is correct */
2226 rc = 0;
2227 } else {
2228 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2229 sleep(1);
2230 rc = 1;
2231 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302232#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002233 }
2234
2235 return rc;
2236}
2237
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002238/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002239 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002240 * Presumably, at a minimum, the caller will update the
2241 * filesystem size and crypto_type_name after calling this function.
2242 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002243static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002244 off64_t off;
2245
2246 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002247 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002248 ftr->major_version = CURRENT_MAJOR_VERSION;
2249 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002250 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002251 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002252
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002253 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002254 case 1:
2255 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2256 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002257
Paul Crowley14c8c072018-09-18 13:30:21 -07002258 case 0:
2259 ftr->kdf_type = KDF_SCRYPT;
2260 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002261
Paul Crowley14c8c072018-09-18 13:30:21 -07002262 default:
2263 SLOGE("keymaster_check_compatibility failed");
2264 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002265 }
2266
Kenny Rootc4c70f12013-06-14 12:11:38 -07002267 get_device_scrypt_params(ftr);
2268
Ken Sumrall160b4d62013-04-22 12:15:39 -07002269 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2270 if (get_crypt_ftr_info(NULL, &off) == 0) {
2271 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002272 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002273 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002274
2275 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002276}
2277
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002278#define FRAMEWORK_BOOT_WAIT 60
2279
Paul Crowley14c8c072018-09-18 13:30:21 -07002280static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2281 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002282 if (fd == -1) {
2283 SLOGE("Error opening file %s", filename);
2284 return -1;
2285 }
2286
2287 char block[CRYPT_INPLACE_BUFSIZE];
2288 memset(block, 0, sizeof(block));
2289 if (unix_read(fd, block, sizeof(block)) < 0) {
2290 SLOGE("Error reading file %s", filename);
2291 close(fd);
2292 return -1;
2293 }
2294
2295 close(fd);
2296
2297 SHA256_CTX c;
2298 SHA256_Init(&c);
2299 SHA256_Update(&c, block, sizeof(block));
2300 SHA256_Final(buf, &c);
2301
2302 return 0;
2303}
2304
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002305static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2306 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002307 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002308 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002309
Paul Lawrence87999172014-02-20 12:21:31 -08002310 /* The size of the userdata partition, and add in the vold volumes below */
2311 tot_encryption_size = crypt_ftr->fs_size;
2312
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002313 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002314 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002315
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002316 if (rc == ENABLE_INPLACE_ERR_DEV) {
2317 /* Hack for b/17898962 */
2318 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2319 cryptfs_reboot(RebootType::reboot);
2320 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002321
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002322 if (!rc) {
2323 crypt_ftr->encrypted_upto = cur_encryption_done;
2324 }
Paul Lawrence87999172014-02-20 12:21:31 -08002325
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002326 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2327 /* The inplace routine never actually sets the progress to 100% due
2328 * to the round down nature of integer division, so set it here */
2329 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002330 }
2331
2332 return rc;
2333}
2334
Paul Crowleyb64933a2017-10-31 08:25:55 -07002335static int vold_unmountAll(void) {
2336 VolumeManager* vm = VolumeManager::Instance();
2337 return vm->unmountAll();
2338}
2339
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002340int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002341 char crypto_blkdev[MAXPATHLEN];
2342 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002343 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002344 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002345 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002346 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002347 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002348 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002349 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002350 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002351 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002352 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002353 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302354#ifdef CONFIG_HW_DISK_ENCRYPTION
2355 unsigned char newpw[32];
2356 int key_index = 0;
2357#endif
2358 int index = 0;
Tri Vo15bbe222019-06-21 12:21:48 -07002359 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302360
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002361 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002362 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2363 /* An encryption was underway and was interrupted */
2364 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2365 crypt_ftr.encrypted_upto = 0;
2366 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002367
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002368 /* At this point, we are in an inconsistent state. Until we successfully
2369 complete encryption, a reboot will leave us broken. So mark the
2370 encryption failed in case that happens.
2371 On successfully completing encryption, remove this flag */
2372 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002373
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002374 put_crypt_ftr_and_key(&crypt_ftr);
2375 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2376 if (!check_ftr_sha(&crypt_ftr)) {
2377 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2378 put_crypt_ftr_and_key(&crypt_ftr);
2379 goto error_unencrypted;
2380 }
2381
2382 /* Doing a reboot-encryption*/
2383 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2384 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2385 rebootEncryption = true;
2386 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002387 } else {
2388 // We don't want to accidentally reference invalid data.
2389 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002390 }
2391
2392 property_get("ro.crypto.state", encrypted_state, "");
2393 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2394 SLOGE("Device is already running encrypted, aborting");
2395 goto error_unencrypted;
2396 }
2397
Tom Cherry4c5bde22019-01-29 14:34:01 -08002398 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002399
Ken Sumrall3ed82362011-01-28 23:31:16 -08002400 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002401 uint64_t nr_sec;
2402 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002403 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002404 goto error_unencrypted;
2405 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002406
2407 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002408 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002409 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002410 fs_size_sec = get_fs_size(real_blkdev.c_str());
2411 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002412
Paul Lawrence87999172014-02-20 12:21:31 -08002413 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002414
2415 if (fs_size_sec > max_fs_size_sec) {
2416 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2417 goto error_unencrypted;
2418 }
2419 }
2420
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002421 /* Get a wakelock as this may take a while, and we don't want the
2422 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2423 * wants to keep the screen on, it can grab a full wakelock.
2424 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002425 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002426 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002427
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002428 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002429 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002430 */
2431 property_set("vold.decrypt", "trigger_shutdown_framework");
2432 SLOGD("Just asked init to shut down class main\n");
2433
Jeff Sharkey9c484982015-03-31 10:35:33 -07002434 /* Ask vold to unmount all devices that it manages */
2435 if (vold_unmountAll()) {
2436 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002437 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002438
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002439 /* no_ui means we are being called from init, not settings.
2440 Now we always reboot from settings, so !no_ui means reboot
2441 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002442 if (!no_ui) {
2443 /* Try fallback, which is to reboot and try there */
2444 onlyCreateHeader = true;
2445 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2446 if (breadcrumb == 0) {
2447 SLOGE("Failed to create breadcrumb file");
2448 goto error_shutting_down;
2449 }
2450 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002451 }
2452
2453 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002454 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002455 /* Now that /data is unmounted, we need to mount a tmpfs
2456 * /data, set a property saying we're doing inplace encryption,
2457 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002458 */
xzj7e38a3a2018-10-12 10:17:11 +08002459 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002460 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002461 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002462 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002463 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002464 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002465
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002466 /* restart the framework. */
2467 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002468 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002469
Ken Sumrall92736ef2012-10-17 20:57:14 -07002470 /* Ugh, shutting down the framework is not synchronous, so until it
2471 * can be fixed, this horrible hack will wait a moment for it all to
2472 * shut down before proceeding. Without it, some devices cannot
2473 * restart the graphics services.
2474 */
2475 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002476 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002477
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002478 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002479 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002480 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002481 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2482 goto error_shutting_down;
2483 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002484
Tom Cherry4c5bde22019-01-29 14:34:01 -08002485 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002486 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002487 } else {
2488 crypt_ftr.fs_size = nr_sec;
2489 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002490 /* At this point, we are in an inconsistent state. Until we successfully
2491 complete encryption, a reboot will leave us broken. So mark the
2492 encryption failed in case that happens.
2493 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002494 if (onlyCreateHeader) {
2495 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2496 } else {
2497 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2498 }
Paul Lawrence87999172014-02-20 12:21:31 -08002499 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302500#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002501 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2502 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302503#else
Paul Crowley14c8c072018-09-18 13:30:21 -07002504 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2505 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302506#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002507
Paul Lawrence87999172014-02-20 12:21:31 -08002508 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002509 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2510 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002511 SLOGE("Cannot create encrypted master key\n");
2512 goto error_shutting_down;
2513 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002514
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002515 /* Replace scrypted intermediate key if we are preparing for a reboot */
2516 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002517 unsigned char fake_master_key[MAX_KEY_LEN];
2518 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002519 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002520 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002521 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002522 }
2523
Paul Lawrence87999172014-02-20 12:21:31 -08002524 /* Write the key to the end of the partition */
2525 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002526
Paul Lawrence87999172014-02-20 12:21:31 -08002527 /* If any persistent data has been remembered, save it.
2528 * If none, create a valid empty table and save that.
2529 */
2530 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002531 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2532 if (pdata) {
2533 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2534 persist_data = pdata;
2535 }
Paul Lawrence87999172014-02-20 12:21:31 -08002536 }
2537 if (persist_data) {
2538 save_persistent_data();
2539 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002540 }
2541
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302542 /* When encryption triggered from settings, encryption starts after reboot.
2543 So set the encryption key when the actual encryption starts.
2544 */
2545#ifdef CONFIG_HW_DISK_ENCRYPTION
2546 if (previously_encrypted_upto == 0) {
2547 if (!rebootEncryption)
2548 clear_hw_device_encryption_key();
2549
2550 if (get_keymaster_hw_fde_passwd(
2551 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2552 newpw, crypt_ftr.salt, &crypt_ftr))
2553 key_index = set_hw_device_encryption_key(
2554 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2555 (char*)crypt_ftr.crypto_type_name);
2556 else
2557 key_index = set_hw_device_encryption_key((const char*)newpw,
2558 (char*) crypt_ftr.crypto_type_name);
2559 if (key_index < 0)
2560 goto error_shutting_down;
2561
2562 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2563 put_crypt_ftr_and_key(&crypt_ftr);
2564 }
2565#endif
2566
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002567 if (onlyCreateHeader) {
2568 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002569 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302570 } else {
2571 /* Do extra work for a better UX when doing the long inplace encryption */
2572 /* Now that /data is unmounted, we need to mount a tmpfs
2573 * /data, set a property saying we're doing inplace encryption,
2574 * and restart the framework.
2575 */
2576 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2577 goto error_shutting_down;
2578 }
2579 /* Tells the framework that inplace encryption is starting */
2580 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002581
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302582 /* restart the framework. */
2583 /* Create necessary paths on /data */
2584 prep_data_fs();
2585
2586 /* Ugh, shutting down the framework is not synchronous, so until it
2587 * can be fixed, this horrible hack will wait a moment for it all to
2588 * shut down before proceeding. Without it, some devices cannot
2589 * restart the graphics services.
2590 */
2591 sleep(2);
2592
Ajay Dudani87701e22014-09-17 21:02:52 -07002593 /* startup service classes main and late_start */
2594 property_set("vold.decrypt", "trigger_restart_min_framework");
2595 SLOGD("Just triggered restart_min_framework\n");
2596
2597 /* OK, the framework is restarted and will soon be showing a
2598 * progress bar. Time to setup an encrypted mapping, and
2599 * either write a new filesystem, or encrypt in place updating
2600 * the progress bar as we work.
2601 */
2602 }
2603
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002604 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302605#ifdef CONFIG_HW_DISK_ENCRYPTION
2606 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302607#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Yifan Hong804afe12019-02-07 12:56:47 -08002608 strlcpy(crypto_blkdev, real_blkdev.c_str(), sizeof(crypto_blkdev));
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302609#else
Eric Arseneau2f8ce652019-02-06 14:23:39 -08002610 create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev.c_str(), crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302611 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302612#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302613 else
Eric Arseneau2f8ce652019-02-06 14:23:39 -08002614 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302615 CRYPTO_BLOCK_DEVICE, 0);
2616#else
Tom Cherry4c5bde22019-01-29 14:34:01 -08002617 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002618 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302619#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002620
Paul Lawrence87999172014-02-20 12:21:31 -08002621 /* If we are continuing, check checksums match */
2622 rc = 0;
2623 if (previously_encrypted_upto) {
2624 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302625#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2626 if (set_ice_param(START_ENCDEC)) {
2627 SLOGE("Failed to set ICE data");
2628 goto error_shutting_down;
2629 }
2630#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002631 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002632
Paul Crowley14c8c072018-09-18 13:30:21 -07002633 if (!rc &&
2634 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002635 SLOGE("Checksums do not match - trigger wipe");
2636 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002637 }
2638 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002639
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302640#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2641 if (set_ice_param(START_ENC)) {
2642 SLOGE("Failed to set ICE data");
2643 goto error_shutting_down;
2644 }
2645#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002646 if (!rc) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002647 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002648 previously_encrypted_upto);
2649 }
2650
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302651#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2652 if (set_ice_param(START_ENCDEC)) {
2653 SLOGE("Failed to set ICE data");
2654 goto error_shutting_down;
2655 }
2656#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002657 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002658 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002659 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002660 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002661 SLOGE("Error calculating checksum for continuing encryption");
2662 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002663 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002664 }
2665
2666 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302667#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2668 if (!is_ice_enabled())
2669 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2670#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002671 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302672#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002673
Paul Crowley14c8c072018-09-18 13:30:21 -07002674 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002675 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002676 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002677
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002678 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002679 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2680 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002681 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002682 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002683
Paul Lawrence6bfed202014-07-28 12:47:22 -07002684 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002685
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002686 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2687 char value[PROPERTY_VALUE_MAX];
2688 property_get("ro.crypto.state", value, "");
2689 if (!strcmp(value, "")) {
2690 /* default encryption - continue first boot sequence */
2691 property_set("ro.crypto.state", "encrypted");
2692 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002693 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002694 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2695 // Bring up cryptkeeper that will check the password and set it
2696 property_set("vold.decrypt", "trigger_shutdown_framework");
2697 sleep(2);
2698 property_set("vold.encrypt_progress", "");
2699 cryptfs_trigger_restart_min_framework();
2700 } else {
2701 cryptfs_check_passwd(DEFAULT_PASSWORD);
2702 cryptfs_restart_internal(1);
2703 }
2704 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002705 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002706 sleep(2); /* Give the UI a chance to show 100% progress */
2707 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002708 }
Paul Lawrence87999172014-02-20 12:21:31 -08002709 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002710 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002711 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002712 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002713 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002714 char value[PROPERTY_VALUE_MAX];
2715
Ken Sumrall319369a2012-06-27 16:30:18 -07002716 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002717 if (!strcmp(value, "1")) {
2718 /* wipe data if encryption failed */
2719 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002720 std::string err;
2721 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002722 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002723 if (!write_bootloader_message(options, &err)) {
2724 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002725 }
Josh Gaofec44372017-08-28 13:22:55 -07002726 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002727 } else {
2728 /* set property to trigger dialog */
2729 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002730 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002731 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002732 }
2733
Ken Sumrall3ed82362011-01-28 23:31:16 -08002734 /* hrm, the encrypt step claims success, but the reboot failed.
2735 * This should not happen.
2736 * Set the property and return. Hope the framework can deal with it.
2737 */
2738 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002739 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002740
2741error_unencrypted:
2742 property_set("vold.encrypt_progress", "error_not_encrypted");
2743 return -1;
2744
2745error_shutting_down:
2746 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2747 * but the framework is stopped and not restarted to show the error, so it's up to
2748 * vold to restart the system.
2749 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002750 SLOGE(
2751 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2752 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002753 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002754
2755 /* shouldn't get here */
2756 property_set("vold.encrypt_progress", "error_shutting_down");
2757 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002758}
2759
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002760int cryptfs_enable(int type, const char* passwd, int no_ui) {
2761 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002762}
2763
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002764int cryptfs_enable_default(int no_ui) {
2765 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002766}
2767
Bill Peckham0db11972018-10-10 10:25:42 -07002768int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002769 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002770 SLOGE("cryptfs_changepw not valid for file encryption");
2771 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002772 }
2773
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002774 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002775 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002776
2777 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002778 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002779 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002780 return -1;
2781 }
2782
Paul Lawrencef4faa572014-01-29 13:31:03 -08002783 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2784 SLOGE("Invalid crypt_type %d", crypt_type);
2785 return -1;
2786 }
2787
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002788 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002789 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002790 SLOGE("Error getting crypt footer and key");
2791 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002792 }
2793
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302794#ifdef CONFIG_HW_DISK_ENCRYPTION
2795 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2796 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
2797 else {
2798 crypt_ftr.crypt_type = crypt_type;
2799
2800 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
2801 DEFAULT_PASSWORD : newpw,
2802 crypt_ftr.salt,
2803 saved_master_key,
2804 crypt_ftr.master_key,
2805 &crypt_ftr, false);
2806 if (rc) {
2807 SLOGE("Encrypt master key failed: %d", rc);
2808 return -1;
2809 }
2810 /* save the key */
2811 put_crypt_ftr_and_key(&crypt_ftr);
2812
2813 return 0;
2814 }
2815#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08002816 crypt_ftr.crypt_type = crypt_type;
2817
Paul Crowley14c8c072018-09-18 13:30:21 -07002818 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07002819 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
2820 false);
JP Abgrall933216c2015-02-11 13:44:32 -08002821 if (rc) {
2822 SLOGE("Encrypt master key failed: %d", rc);
2823 return -1;
2824 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002825 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002826 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002827
2828 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302829#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002830}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002831
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302832#ifdef CONFIG_HW_DISK_ENCRYPTION
2833int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
2834{
2835 struct crypt_mnt_ftr crypt_ftr;
2836 int rc;
2837 int previous_type;
2838
2839 /* get key */
2840 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2841 SLOGE("Error getting crypt footer and key");
2842 return -1;
2843 }
2844
2845 previous_type = crypt_ftr.crypt_type;
2846 int rc1;
2847 unsigned char tmp_curpw[32] = {0};
2848 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
2849 DEFAULT_PASSWORD : currentpw, tmp_curpw,
2850 crypt_ftr.salt, &crypt_ftr);
2851
2852 crypt_ftr.crypt_type = crypt_type;
2853
2854 int ret, rc2;
2855 unsigned char tmp_newpw[32] = {0};
2856
2857 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
2858 DEFAULT_PASSWORD : newpw , tmp_newpw,
2859 crypt_ftr.salt, &crypt_ftr);
2860
2861 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2862 ret = update_hw_device_encryption_key(
2863 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
2864 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
2865 (char*)crypt_ftr.crypto_type_name);
2866 if (ret) {
2867 SLOGE("Error updating device encryption hardware key ret %d", ret);
2868 return -1;
2869 } else {
2870 SLOGI("Encryption hardware key updated");
2871 }
2872 }
2873
2874 /* save the key */
2875 put_crypt_ftr_and_key(&crypt_ftr);
2876 return 0;
2877}
2878#endif
2879
Rubin Xu85c01f92014-10-13 12:49:54 +01002880static unsigned int persist_get_max_entries(int encrypted) {
2881 struct crypt_mnt_ftr crypt_ftr;
2882 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002883
2884 /* If encrypted, use the values from the crypt_ftr, otherwise
2885 * use the values for the current spec.
2886 */
2887 if (encrypted) {
2888 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01002889 /* Something is wrong, assume no space for entries */
2890 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002891 }
2892 dsize = crypt_ftr.persist_data_size;
2893 } else {
2894 dsize = CRYPT_PERSIST_DATA_SIZE;
2895 }
2896
Rubin Xud78181b2018-10-09 16:13:38 +01002897 if (dsize > sizeof(struct crypt_persist_data)) {
2898 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2899 } else {
2900 return 0;
2901 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002902}
2903
Paul Crowley14c8c072018-09-18 13:30:21 -07002904static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002905 unsigned int i;
2906
2907 if (persist_data == NULL) {
2908 return -1;
2909 }
2910 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2911 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2912 /* We found it! */
2913 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2914 return 0;
2915 }
2916 }
2917
2918 return -1;
2919}
2920
Paul Crowley14c8c072018-09-18 13:30:21 -07002921static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002922 unsigned int i;
2923 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002924 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002925
2926 if (persist_data == NULL) {
2927 return -1;
2928 }
2929
Rubin Xu85c01f92014-10-13 12:49:54 +01002930 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002931
2932 num = persist_data->persist_valid_entries;
2933
2934 for (i = 0; i < num; i++) {
2935 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2936 /* We found an existing entry, update it! */
2937 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2938 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2939 return 0;
2940 }
2941 }
2942
2943 /* We didn't find it, add it to the end, if there is room */
2944 if (persist_data->persist_valid_entries < max_persistent_entries) {
2945 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2946 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2947 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2948 persist_data->persist_valid_entries++;
2949 return 0;
2950 }
2951
2952 return -1;
2953}
2954
Rubin Xu85c01f92014-10-13 12:49:54 +01002955/**
2956 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2957 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2958 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002959int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002960 std::string key_ = key;
2961 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002962
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002963 std::string parsed_field;
2964 unsigned parsed_index;
2965
2966 std::string::size_type split = key_.find_last_of('_');
2967 if (split == std::string::npos) {
2968 parsed_field = key_;
2969 parsed_index = 0;
2970 } else {
2971 parsed_field = key_.substr(0, split);
2972 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002973 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002974
2975 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002976}
2977
2978/*
2979 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2980 * remaining entries starting from index will be deleted.
2981 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2982 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2983 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2984 *
2985 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002986static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002987 unsigned int i;
2988 unsigned int j;
2989 unsigned int num;
2990
2991 if (persist_data == NULL) {
2992 return PERSIST_DEL_KEY_ERROR_OTHER;
2993 }
2994
2995 num = persist_data->persist_valid_entries;
2996
Paul Crowley14c8c072018-09-18 13:30:21 -07002997 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002998 // Filter out to-be-deleted entries in place.
2999 for (i = 0; i < num; i++) {
3000 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3001 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3002 j++;
3003 }
3004 }
3005
3006 if (j < num) {
3007 persist_data->persist_valid_entries = j;
3008 // Zeroise the remaining entries
3009 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3010 return PERSIST_DEL_KEY_OK;
3011 } else {
3012 // Did not find an entry matching the given fieldname
3013 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3014 }
3015}
3016
Paul Crowley14c8c072018-09-18 13:30:21 -07003017static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003018 unsigned int i;
3019 unsigned int count;
3020
3021 if (persist_data == NULL) {
3022 return -1;
3023 }
3024
3025 count = 0;
3026 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3027 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3028 count++;
3029 }
3030 }
3031
3032 return count;
3033}
3034
Ken Sumrall160b4d62013-04-22 12:15:39 -07003035/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003036int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003037 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003038 SLOGE("Cannot get field when file encrypted");
3039 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003040 }
3041
Ken Sumrall160b4d62013-04-22 12:15:39 -07003042 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003043 /* CRYPTO_GETFIELD_OK is success,
3044 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3045 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3046 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003047 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003048 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3049 int i;
3050 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003051
3052 if (persist_data == NULL) {
3053 load_persistent_data();
3054 if (persist_data == NULL) {
3055 SLOGE("Getfield error, cannot load persistent data");
3056 goto out;
3057 }
3058 }
3059
Rubin Xu85c01f92014-10-13 12:49:54 +01003060 // Read value from persistent entries. If the original value is split into multiple entries,
3061 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003062 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003063 // 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 -07003064 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003065 // value too small
3066 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3067 goto out;
3068 }
3069 rc = CRYPTO_GETFIELD_OK;
3070
3071 for (i = 1; /* break explicitly */; i++) {
3072 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003073 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003074 // If the fieldname is very long, we stop as soon as it begins to overflow the
3075 // maximum field length. At this point we have in fact fully read out the original
3076 // value because cryptfs_setfield would not allow fields with longer names to be
3077 // written in the first place.
3078 break;
3079 }
3080 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003081 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3082 // value too small.
3083 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3084 goto out;
3085 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003086 } else {
3087 // Exhaust all entries.
3088 break;
3089 }
3090 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003091 } else {
3092 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003093 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003094 }
3095
3096out:
3097 return rc;
3098}
3099
3100/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003101int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003102 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003103 SLOGE("Cannot set field when file encrypted");
3104 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003105 }
3106
Ken Sumrall160b4d62013-04-22 12:15:39 -07003107 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003108 /* 0 is success, negative values are error */
3109 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003110 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003111 unsigned int field_id;
3112 char temp_field[PROPERTY_KEY_MAX];
3113 unsigned int num_entries;
3114 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003115
3116 if (persist_data == NULL) {
3117 load_persistent_data();
3118 if (persist_data == NULL) {
3119 SLOGE("Setfield error, cannot load persistent data");
3120 goto out;
3121 }
3122 }
3123
3124 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003125 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003126 encrypted = 1;
3127 }
3128
Rubin Xu85c01f92014-10-13 12:49:54 +01003129 // Compute the number of entries required to store value, each entry can store up to
3130 // (PROPERTY_VALUE_MAX - 1) chars
3131 if (strlen(value) == 0) {
3132 // Empty value also needs one entry to store.
3133 num_entries = 1;
3134 } else {
3135 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3136 }
3137
3138 max_keylen = strlen(fieldname);
3139 if (num_entries > 1) {
3140 // Need an extra "_%d" suffix.
3141 max_keylen += 1 + log10(num_entries);
3142 }
3143 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3144 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003145 goto out;
3146 }
3147
Rubin Xu85c01f92014-10-13 12:49:54 +01003148 // Make sure we have enough space to write the new value
3149 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3150 persist_get_max_entries(encrypted)) {
3151 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3152 goto out;
3153 }
3154
3155 // Now that we know persist_data has enough space for value, let's delete the old field first
3156 // to make up space.
3157 persist_del_keys(fieldname, 0);
3158
3159 if (persist_set_key(fieldname, value, encrypted)) {
3160 // fail to set key, should not happen as we have already checked the available space
3161 SLOGE("persist_set_key() error during setfield()");
3162 goto out;
3163 }
3164
3165 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003166 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003167
3168 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3169 // fail to set key, should not happen as we have already checked the available space.
3170 SLOGE("persist_set_key() error during setfield()");
3171 goto out;
3172 }
3173 }
3174
Ken Sumrall160b4d62013-04-22 12:15:39 -07003175 /* If we are running encrypted, save the persistent data now */
3176 if (encrypted) {
3177 if (save_persistent_data()) {
3178 SLOGE("Setfield error, cannot save persistent data");
3179 goto out;
3180 }
3181 }
3182
Rubin Xu85c01f92014-10-13 12:49:54 +01003183 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003184
3185out:
3186 return rc;
3187}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003188
3189/* Checks userdata. Attempt to mount the volume if default-
3190 * encrypted.
3191 * On success trigger next init phase and return 0.
3192 * Currently do not handle failure - see TODO below.
3193 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003194int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003195 int crypt_type = cryptfs_get_password_type();
3196 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3197 SLOGE("Bad crypt type - error");
3198 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003199 SLOGD(
3200 "Password is not default - "
3201 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003202 property_set("vold.decrypt", "trigger_restart_min_framework");
3203 return 0;
3204 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3205 SLOGD("Password is default - restarting filesystem");
3206 cryptfs_restart_internal(0);
3207 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003208 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003209 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003210 }
3211
Paul Lawrence6bfed202014-07-28 12:47:22 -07003212 /** Corrupt. Allow us to boot into framework, which will detect bad
3213 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003214 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003215 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003216 return 0;
3217}
3218
3219/* Returns type of the password, default, pattern, pin or password.
3220 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003221int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003222 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003223 SLOGE("cryptfs_get_password_type not valid for file encryption");
3224 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003225 }
3226
Paul Lawrencef4faa572014-01-29 13:31:03 -08003227 struct crypt_mnt_ftr crypt_ftr;
3228
3229 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3230 SLOGE("Error getting crypt footer and key\n");
3231 return -1;
3232 }
3233
Paul Lawrence6bfed202014-07-28 12:47:22 -07003234 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3235 return -1;
3236 }
3237
Paul Lawrencef4faa572014-01-29 13:31:03 -08003238 return crypt_ftr.crypt_type;
3239}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003240
Paul Crowley14c8c072018-09-18 13:30:21 -07003241const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003242 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003243 SLOGE("cryptfs_get_password not valid for file encryption");
3244 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003245 }
3246
Paul Lawrence399317e2014-03-10 13:20:50 -07003247 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003248 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003249 if (now.tv_sec < password_expiry_time) {
3250 return password;
3251 } else {
3252 cryptfs_clear_password();
3253 return 0;
3254 }
3255}
3256
Paul Crowley14c8c072018-09-18 13:30:21 -07003257void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003258 if (password) {
3259 size_t len = strlen(password);
3260 memset(password, 0, len);
3261 free(password);
3262 password = 0;
3263 password_expiry_time = 0;
3264 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003265}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003266
Paul Crowley14c8c072018-09-18 13:30:21 -07003267int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08003268 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
3269 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07003270}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303271
3272int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3273{
3274 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3275 SLOGE("Failed to initialize crypt_ftr");
3276 return -1;
3277 }
3278
3279 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3280 crypt_ftr->salt, crypt_ftr)) {
3281 SLOGE("Cannot create encrypted master key\n");
3282 return -1;
3283 }
3284
3285 //crypt_ftr->keysize = key_length / 8;
3286 return 0;
3287}
3288
3289int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3290 unsigned char* master_key)
3291{
3292 int rc;
3293
3294 unsigned char* intermediate_key = 0;
3295 size_t intermediate_key_size = 0;
3296
3297 if (password == 0 || *password == 0) {
3298 password = DEFAULT_PASSWORD;
3299 }
3300
3301 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3302 &intermediate_key_size);
3303
3304 if (rc) {
3305 SLOGE("Can't calculate intermediate key");
3306 return rc;
3307 }
3308
3309 int N = 1 << ftr->N_factor;
3310 int r = 1 << ftr->r_factor;
3311 int p = 1 << ftr->p_factor;
3312
3313 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3314
3315 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3316 ftr->salt, sizeof(ftr->salt), N, r, p,
3317 scrypted_intermediate_key,
3318 sizeof(scrypted_intermediate_key));
3319
3320 free(intermediate_key);
3321
3322 if (rc) {
3323 SLOGE("Can't scrypt intermediate key");
3324 return rc;
3325 }
3326
3327 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3328 intermediate_key_size);
3329}