blob: 5d88a49f7794ca625d8b20bf275bd93cafd88e9c [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"
36#include "secontext.h"
37
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080039#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080040#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070043#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070045#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070046#include <fscrypt/fscrypt.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080047#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080048#include <log/log.h>
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>
Logan Chiend557d762018-05-02 11:36:45 +080053
54#include <ctype.h>
55#include <errno.h>
56#include <fcntl.h>
57#include <inttypes.h>
58#include <libgen.h>
59#include <linux/dm-ioctl.h>
60#include <linux/kdev_t.h>
61#include <math.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <sys/ioctl.h>
66#include <sys/mount.h>
67#include <sys/param.h>
68#include <sys/stat.h>
69#include <sys/types.h>
70#include <sys/wait.h>
71#include <time.h>
72#include <unistd.h>
73
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053074#ifdef CONFIG_HW_DISK_ENCRYPTION
75#include <cryptfs_hw.h>
76#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080077extern "C" {
78#include <crypto_scrypt.h>
79}
Mark Salyzyn3e971272014-01-21 13:27:04 -080080
Greg Kaiserab1e84a2018-12-11 12:40:51 -080081using android::base::StringPrintf;
Paul Crowley298fa322018-10-30 15:59:24 -070082using namespace std::chrono_literals;
83
Mark Salyzyn5eecc442014-02-12 14:16:14 -080084#define UNUSED __attribute__((unused))
85
Ken Sumrall8f869aa2010-12-03 03:47:09 -080086#define DM_CRYPT_BUF_SIZE 4096
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
Paul Crowley14c8c072018-09-18 13:30:21 -0700404static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800405 memset(io, 0, dataSize);
406 io->data_size = dataSize;
407 io->data_start = sizeof(struct dm_ioctl);
408 io->version[0] = 4;
409 io->version[1] = 0;
410 io->version[2] = 0;
411 io->flags = flags;
412 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100413 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800414 }
415}
416
Greg Kaiser38723f22018-02-16 13:35:35 -0800417namespace {
418
419struct CryptoType;
420
421// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700422const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800423
424struct CryptoType {
425 // We should only be constructing CryptoTypes as part of
426 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
427 // which isn't pure or fully protected as a concession to being able to
428 // do it all at compile time. Add new CryptoTypes in
429 // supported_crypto_types[] below.
430 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
431 constexpr CryptoType set_keysize(uint32_t size) const {
432 return CryptoType(this->property_name, this->crypto_name, size);
433 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700434 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800435 return CryptoType(property, this->crypto_name, this->keysize);
436 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700437 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800438 return CryptoType(this->property_name, crypto, this->keysize);
439 }
440
Paul Crowley14c8c072018-09-18 13:30:21 -0700441 constexpr const char* get_property_name() const { return property_name; }
442 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800443 constexpr uint32_t get_keysize() const { return keysize; }
444
Paul Crowley14c8c072018-09-18 13:30:21 -0700445 private:
446 const char* property_name;
447 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800448 uint32_t keysize;
449
Paul Crowley14c8c072018-09-18 13:30:21 -0700450 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800451 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700452 friend const CryptoType& get_crypto_type();
453 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800454};
455
456// We only want to parse this read-only property once. But we need to wait
457// until the system is initialized before we can read it. So we use a static
458// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700459const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800460 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
461 return crypto_type;
462}
463
464constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700465 .set_property_name("AES-128-CBC")
466 .set_crypto_name("aes-cbc-essiv:sha256")
467 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800468
469constexpr CryptoType supported_crypto_types[] = {
470 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800471 CryptoType()
472 .set_property_name("adiantum")
473 .set_crypto_name("xchacha12,aes-adiantum-plain64")
474 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800475 // Add new CryptoTypes here. Order is not important.
476};
477
Greg Kaiser38723f22018-02-16 13:35:35 -0800478// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
479// We confirm all supported_crypto_types have a small enough keysize and
480// had both set_property_name() and set_crypto_name() called.
481
482template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700483constexpr size_t array_length(T (&)[N]) {
484 return N;
485}
Greg Kaiser38723f22018-02-16 13:35:35 -0800486
487constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
488 return (index >= array_length(supported_crypto_types));
489}
490
Paul Crowley14c8c072018-09-18 13:30:21 -0700491constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800492 return ((crypto_type.get_property_name() != nullptr) &&
493 (crypto_type.get_crypto_name() != nullptr) &&
494 (crypto_type.get_keysize() <= MAX_KEY_LEN));
495}
496
497// Note in C++11 that constexpr functions can only have a single line.
498// So our code is a bit convoluted (using recursion instead of a loop),
499// but it's asserting at compile time that all of our key lengths are valid.
500constexpr bool validateSupportedCryptoTypes(size_t index) {
501 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700502 (isValidCryptoType(supported_crypto_types[index]) &&
503 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800504}
505
506static_assert(validateSupportedCryptoTypes(0),
507 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
508 "incompletely constructed.");
509// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
510
Greg Kaiser38723f22018-02-16 13:35:35 -0800511// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700512const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800513 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
514 char paramstr[PROPERTY_VALUE_MAX];
515
Paul Crowley14c8c072018-09-18 13:30:21 -0700516 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
517 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800518 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
519 return ctype;
520 }
521 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700522 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
523 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800524 return default_crypto_type;
525}
526
527} // namespace
528
Kenny Rootc4c70f12013-06-14 12:11:38 -0700529/**
530 * Gets the default device scrypt parameters for key derivation time tuning.
531 * The parameters should lead to about one second derivation time for the
532 * given device.
533 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700534static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700535 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000536 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700537
Paul Crowley63c18d32016-02-10 14:02:47 +0000538 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
539 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
540 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
541 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700542 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000543 ftr->N_factor = Nf;
544 ftr->r_factor = rf;
545 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700546}
547
Greg Kaiser57f9af62018-02-16 13:13:58 -0800548uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800549 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800550}
551
Paul Crowley14c8c072018-09-18 13:30:21 -0700552const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800553 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800554}
555
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200556static uint64_t get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800557 int fd, block_size;
558 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200559 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800560
Paul Crowley14c8c072018-09-18 13:30:21 -0700561 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800562 SLOGE("Cannot open device to get filesystem size ");
563 return 0;
564 }
565
566 if (lseek64(fd, 1024, SEEK_SET) < 0) {
567 SLOGE("Cannot seek to superblock");
568 return 0;
569 }
570
571 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
572 SLOGE("Cannot read superblock");
573 return 0;
574 }
575
576 close(fd);
577
Daniel Rosenberge82df162014-08-15 22:19:23 +0000578 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
579 SLOGE("Not a valid ext4 superblock");
580 return 0;
581 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800582 block_size = 1024 << sb.s_log_block_size;
583 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200584 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800585
586 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200587 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800588}
589
Paul Crowley14c8c072018-09-18 13:30:21 -0700590static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
591 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200592 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700593 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700594 char key_loc[PROPERTY_VALUE_MAX];
595 char real_blkdev[PROPERTY_VALUE_MAX];
596 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700597
Paul Crowley14c8c072018-09-18 13:30:21 -0700598 if (!cached_data) {
599 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700600
Paul Crowley14c8c072018-09-18 13:30:21 -0700601 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200602 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700603 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
604 * encryption info footer and key, and plenty of bytes to spare for future
605 * growth.
606 */
607 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200608 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700609 cached_data = 1;
610 } else {
611 SLOGE("Cannot get size of block device %s\n", real_blkdev);
612 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700613 } else {
614 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
615 cached_off = 0;
616 cached_data = 1;
617 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700618 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619
Paul Crowley14c8c072018-09-18 13:30:21 -0700620 if (cached_data) {
621 if (metadata_fname) {
622 *metadata_fname = cached_metadata_fname;
623 }
624 if (off) {
625 *off = cached_off;
626 }
627 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700628 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700629
Paul Crowley14c8c072018-09-18 13:30:21 -0700630 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700631}
632
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800633/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700634static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800635 SHA256_CTX c;
636 SHA256_Init(&c);
637 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
638 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
639 SHA256_Final(crypt_ftr->sha256, &c);
640}
641
Ken Sumralle8744072011-01-18 22:01:55 -0800642/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800643 * update the failed mount count but not change the key.
644 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700645static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
646 int fd;
647 unsigned int cnt;
648 /* starting_off is set to the SEEK_SET offset
649 * where the crypto structure starts
650 */
651 off64_t starting_off;
652 int rc = -1;
653 char* fname = NULL;
654 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800655
Paul Crowley14c8c072018-09-18 13:30:21 -0700656 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800657
Paul Crowley14c8c072018-09-18 13:30:21 -0700658 if (get_crypt_ftr_info(&fname, &starting_off)) {
659 SLOGE("Unable to get crypt_ftr_info\n");
660 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800661 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700662 if (fname[0] != '/') {
663 SLOGE("Unexpected value for crypto key location\n");
664 return -1;
665 }
666 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
667 SLOGE("Cannot open footer file %s for put\n", fname);
668 return -1;
669 }
Ken Sumralle8744072011-01-18 22:01:55 -0800670
Paul Crowley14c8c072018-09-18 13:30:21 -0700671 /* Seek to the start of the crypt footer */
672 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
673 SLOGE("Cannot seek to real block device footer\n");
674 goto errout;
675 }
676
677 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
678 SLOGE("Cannot write real block device footer\n");
679 goto errout;
680 }
681
682 fstat(fd, &statbuf);
683 /* If the keys are kept on a raw block device, do not try to truncate it. */
684 if (S_ISREG(statbuf.st_mode)) {
685 if (ftruncate(fd, 0x4000)) {
686 SLOGE("Cannot set footer file size\n");
687 goto errout;
688 }
689 }
690
691 /* Success! */
692 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800693
694errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700695 close(fd);
696 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800697}
698
Paul Crowley14c8c072018-09-18 13:30:21 -0700699static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800700 struct crypt_mnt_ftr copy;
701 memcpy(&copy, crypt_ftr, sizeof(copy));
702 set_ftr_sha(&copy);
703 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
704}
705
Paul Crowley14c8c072018-09-18 13:30:21 -0700706static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700707 return TEMP_FAILURE_RETRY(read(fd, buff, len));
708}
709
Paul Crowley14c8c072018-09-18 13:30:21 -0700710static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700711 return TEMP_FAILURE_RETRY(write(fd, buff, len));
712}
713
Paul Crowley14c8c072018-09-18 13:30:21 -0700714static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700715 memset(pdata, 0, len);
716 pdata->persist_magic = PERSIST_DATA_MAGIC;
717 pdata->persist_valid_entries = 0;
718}
719
720/* A routine to update the passed in crypt_ftr to the lastest version.
721 * fd is open read/write on the device that holds the crypto footer and persistent
722 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
723 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
724 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700725static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700726 int orig_major = crypt_ftr->major_version;
727 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700728
Kenny Root7434b312013-06-14 11:29:53 -0700729 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700730 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700731 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700732
Kenny Rootc4c70f12013-06-14 12:11:38 -0700733 SLOGW("upgrading crypto footer to 1.1");
734
Paul Crowley14c8c072018-09-18 13:30:21 -0700735 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700736 if (pdata == NULL) {
737 SLOGE("Cannot allocate persisent data\n");
738 return;
739 }
740 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
741
742 /* Need to initialize the persistent data area */
743 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
744 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100745 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700746 return;
747 }
748 /* Write all zeros to the first copy, making it invalid */
749 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
750
751 /* Write a valid but empty structure to the second copy */
752 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
753 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
754
755 /* Update the footer */
756 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
757 crypt_ftr->persist_data_offset[0] = pdata_offset;
758 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
759 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100760 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700761 }
762
Paul Lawrencef4faa572014-01-29 13:31:03 -0800763 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700764 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800765 /* But keep the old kdf_type.
766 * It will get updated later to KDF_SCRYPT after the password has been verified.
767 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700768 crypt_ftr->kdf_type = KDF_PBKDF2;
769 get_device_scrypt_params(crypt_ftr);
770 crypt_ftr->minor_version = 2;
771 }
772
Paul Lawrencef4faa572014-01-29 13:31:03 -0800773 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
774 SLOGW("upgrading crypto footer to 1.3");
775 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
776 crypt_ftr->minor_version = 3;
777 }
778
Kenny Root7434b312013-06-14 11:29:53 -0700779 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
780 if (lseek64(fd, offset, SEEK_SET) == -1) {
781 SLOGE("Cannot seek to crypt footer\n");
782 return;
783 }
784 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700785 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700786}
787
Paul Crowley14c8c072018-09-18 13:30:21 -0700788static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
789 int fd;
790 unsigned int cnt;
791 off64_t starting_off;
792 int rc = -1;
793 char* fname = NULL;
794 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700795
Paul Crowley14c8c072018-09-18 13:30:21 -0700796 if (get_crypt_ftr_info(&fname, &starting_off)) {
797 SLOGE("Unable to get crypt_ftr_info\n");
798 return -1;
799 }
800 if (fname[0] != '/') {
801 SLOGE("Unexpected value for crypto key location\n");
802 return -1;
803 }
804 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
805 SLOGE("Cannot open footer file %s for get\n", fname);
806 return -1;
807 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800808
Paul Crowley14c8c072018-09-18 13:30:21 -0700809 /* Make sure it's 16 Kbytes in length */
810 fstat(fd, &statbuf);
811 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
812 SLOGE("footer file %s is not the expected size!\n", fname);
813 goto errout;
814 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815
Paul Crowley14c8c072018-09-18 13:30:21 -0700816 /* Seek to the start of the crypt footer */
817 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
818 SLOGE("Cannot seek to real block device footer\n");
819 goto errout;
820 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700821
Paul Crowley14c8c072018-09-18 13:30:21 -0700822 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
823 SLOGE("Cannot read real block device footer\n");
824 goto errout;
825 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800826
Paul Crowley14c8c072018-09-18 13:30:21 -0700827 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
828 SLOGE("Bad magic for real block device %s\n", fname);
829 goto errout;
830 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800831
Paul Crowley14c8c072018-09-18 13:30:21 -0700832 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
833 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
834 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
835 goto errout;
836 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800837
Paul Crowley14c8c072018-09-18 13:30:21 -0700838 // We risk buffer overflows with oversized keys, so we just reject them.
839 // 0-sized keys are problematic (essentially by-passing encryption), and
840 // AES-CBC key wrapping only works for multiples of 16 bytes.
841 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
842 (crypt_ftr->keysize > MAX_KEY_LEN)) {
843 SLOGE(
844 "Invalid keysize (%u) for block device %s; Must be non-zero, "
845 "divisible by 16, and <= %d\n",
846 crypt_ftr->keysize, fname, MAX_KEY_LEN);
847 goto errout;
848 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800849
Paul Crowley14c8c072018-09-18 13:30:21 -0700850 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
851 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
852 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
853 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800854
Paul Crowley14c8c072018-09-18 13:30:21 -0700855 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
856 * copy on disk before returning.
857 */
858 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
859 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
860 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800861
Paul Crowley14c8c072018-09-18 13:30:21 -0700862 /* Success! */
863 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800864
865errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700866 close(fd);
867 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800868}
869
Paul Crowley14c8c072018-09-18 13:30:21 -0700870static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700871 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
872 crypt_ftr->persist_data_offset[1]) {
873 SLOGE("Crypt_ftr persist data regions overlap");
874 return -1;
875 }
876
877 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
878 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
879 return -1;
880 }
881
882 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700883 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700884 CRYPT_FOOTER_OFFSET) {
885 SLOGE("Persistent data extends past crypto footer");
886 return -1;
887 }
888
889 return 0;
890}
891
Paul Crowley14c8c072018-09-18 13:30:21 -0700892static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700893 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700894 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700895 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700896 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700897 int found = 0;
898 int fd;
899 int ret;
900 int i;
901
902 if (persist_data) {
903 /* Nothing to do, we've already loaded or initialized it */
904 return 0;
905 }
906
Ken Sumrall160b4d62013-04-22 12:15:39 -0700907 /* If not encrypted, just allocate an empty table and initialize it */
908 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700909 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800910 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700911 if (pdata) {
912 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
913 persist_data = pdata;
914 return 0;
915 }
916 return -1;
917 }
918
Paul Crowley14c8c072018-09-18 13:30:21 -0700919 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700920 return -1;
921 }
922
Paul Crowley14c8c072018-09-18 13:30:21 -0700923 if ((crypt_ftr.major_version < 1) ||
924 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700925 SLOGE("Crypt_ftr version doesn't support persistent data");
926 return -1;
927 }
928
929 if (get_crypt_ftr_info(&fname, NULL)) {
930 return -1;
931 }
932
933 ret = validate_persistent_data_storage(&crypt_ftr);
934 if (ret) {
935 return -1;
936 }
937
Paul Crowley14c8c072018-09-18 13:30:21 -0700938 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700939 if (fd < 0) {
940 SLOGE("Cannot open %s metadata file", fname);
941 return -1;
942 }
943
Wei Wang4375f1b2017-02-24 17:43:01 -0800944 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800945 if (pdata == NULL) {
946 SLOGE("Cannot allocate memory for persistent data");
947 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700948 }
949
950 for (i = 0; i < 2; i++) {
951 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
952 SLOGE("Cannot seek to read persistent data on %s", fname);
953 goto err2;
954 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700955 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700956 SLOGE("Error reading persistent data on iteration %d", i);
957 goto err2;
958 }
959 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
960 found = 1;
961 break;
962 }
963 }
964
965 if (!found) {
966 SLOGI("Could not find valid persistent data, creating");
967 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
968 }
969
970 /* Success */
971 persist_data = pdata;
972 close(fd);
973 return 0;
974
975err2:
976 free(pdata);
977
978err:
979 close(fd);
980 return -1;
981}
982
Paul Crowley14c8c072018-09-18 13:30:21 -0700983static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700984 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700985 struct crypt_persist_data* pdata;
986 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700987 off64_t write_offset;
988 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700989 int fd;
990 int ret;
991
992 if (persist_data == NULL) {
993 SLOGE("No persistent data to save");
994 return -1;
995 }
996
Paul Crowley14c8c072018-09-18 13:30:21 -0700997 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700998 return -1;
999 }
1000
Paul Crowley14c8c072018-09-18 13:30:21 -07001001 if ((crypt_ftr.major_version < 1) ||
1002 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001003 SLOGE("Crypt_ftr version doesn't support persistent data");
1004 return -1;
1005 }
1006
1007 ret = validate_persistent_data_storage(&crypt_ftr);
1008 if (ret) {
1009 return -1;
1010 }
1011
1012 if (get_crypt_ftr_info(&fname, NULL)) {
1013 return -1;
1014 }
1015
Paul Crowley14c8c072018-09-18 13:30:21 -07001016 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001017 if (fd < 0) {
1018 SLOGE("Cannot open %s metadata file", fname);
1019 return -1;
1020 }
1021
Wei Wang4375f1b2017-02-24 17:43:01 -08001022 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001023 if (pdata == NULL) {
1024 SLOGE("Cannot allocate persistant data");
1025 goto err;
1026 }
1027
1028 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1029 SLOGE("Cannot seek to read persistent data on %s", fname);
1030 goto err2;
1031 }
1032
1033 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001034 SLOGE("Error reading persistent data before save");
1035 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001036 }
1037
1038 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1039 /* The first copy is the curent valid copy, so write to
1040 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001041 write_offset = crypt_ftr.persist_data_offset[1];
1042 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001043 } else {
1044 /* The second copy must be the valid copy, so write to
1045 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001046 write_offset = crypt_ftr.persist_data_offset[0];
1047 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001048 }
1049
1050 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001051 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001052 SLOGE("Cannot seek to write persistent data");
1053 goto err2;
1054 }
1055 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001056 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001057 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001058 SLOGE("Cannot seek to erase previous persistent data");
1059 goto err2;
1060 }
1061 fsync(fd);
1062 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001063 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001064 SLOGE("Cannot write to erase previous persistent data");
1065 goto err2;
1066 }
1067 fsync(fd);
1068 } else {
1069 SLOGE("Cannot write to save persistent data");
1070 goto err2;
1071 }
1072
1073 /* Success */
1074 free(pdata);
1075 close(fd);
1076 return 0;
1077
1078err2:
1079 free(pdata);
1080err:
1081 close(fd);
1082 return -1;
1083}
1084
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001085/* Convert a binary key of specified length into an ascii hex string equivalent,
1086 * without the leading 0x and with null termination
1087 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001088static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1089 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001090 unsigned int i, a;
1091 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001092
Paul Crowley14c8c072018-09-18 13:30:21 -07001093 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001094 /* For each byte, write out two ascii hex digits */
1095 nibble = (master_key[i] >> 4) & 0xf;
1096 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001097
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001098 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001099 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001100 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001101
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001102 /* Add the null termination */
1103 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001104}
1105
Paul Crowley14c8c072018-09-18 13:30:21 -07001106static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
1107 const unsigned char* master_key, const char* real_blk_name,
1108 const char* name, int fd, const char* extra_params) {
1109 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1110 struct dm_ioctl* io;
1111 struct dm_target_spec* tgt;
1112 char* crypt_params;
1113 // We need two ASCII characters to represent each byte, and need space for
1114 // the '\0' terminator.
1115 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1116 size_t buff_offset;
1117 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001118
Paul Crowley14c8c072018-09-18 13:30:21 -07001119 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001120
Paul Crowley14c8c072018-09-18 13:30:21 -07001121 /* Load the mapping table for this device */
1122 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001123
Paul Crowley14c8c072018-09-18 13:30:21 -07001124 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1125 io->target_count = 1;
1126 tgt->status = 0;
1127 tgt->sector_start = 0;
1128 tgt->length = crypt_ftr->fs_size;
Paul Crowley14c8c072018-09-18 13:30:21 -07001129 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
Paul Crowley14c8c072018-09-18 13:30:21 -07001130 buff_offset = crypt_params - buffer;
1131 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301132
1133#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001134 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1135 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1136 if (is_ice_enabled())
1137 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1138 else
1139 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1140 }
1141 else {
1142 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1143 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1144 }
1145 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1146 crypt_ftr->crypto_type_name, master_key_ascii,
1147 real_blk_name, extra_params);
1148
1149 SLOGI("target_type = %s", tgt->target_type);
1150 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1151#else
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301152 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1153 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Paul Crowley14c8c072018-09-18 13:30:21 -07001154 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
1155 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301156#endif
1157
Paul Crowley14c8c072018-09-18 13:30:21 -07001158 crypt_params += strlen(crypt_params) + 1;
1159 crypt_params =
1160 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1161 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001162
Paul Crowley14c8c072018-09-18 13:30:21 -07001163 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1164 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
1165 break;
1166 }
1167 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001168 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001169
Paul Crowley14c8c072018-09-18 13:30:21 -07001170 if (i == TABLE_LOAD_RETRIES) {
1171 /* We failed to load the table, return an error */
1172 return -1;
1173 } else {
1174 return i + 1;
1175 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001176}
1177
Paul Crowley14c8c072018-09-18 13:30:21 -07001178static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001179 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001180 struct dm_ioctl* io;
1181 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001182
Paul Crowley14c8c072018-09-18 13:30:21 -07001183 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001184
1185 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1186
1187 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1188 return -1;
1189 }
1190
1191 /* Iterate over the returned versions, looking for name of "crypt".
1192 * When found, get and return the version.
1193 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001194 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001195 while (v->next) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301196#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001197 if (!strcmp(v->name, "crypt") || !strcmp(v->name, "req-crypt")) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301198#else
Paul Crowley14c8c072018-09-18 13:30:21 -07001199 if (!strcmp(v->name, "crypt")) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301200#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001201 /* We found the crypt driver, return the version, and get out */
1202 version[0] = v->version[0];
1203 version[1] = v->version[1];
1204 version[2] = v->version[2];
1205 return 0;
1206 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001207 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001208 }
1209
1210 return -1;
1211}
1212
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301213#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Crowley5afbc622017-11-27 09:42:17 -08001214static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1215 if (extra_params_vec.empty()) return "";
1216 std::string extra_params = std::to_string(extra_params_vec.size());
1217 for (const auto& p : extra_params_vec) {
1218 extra_params.append(" ");
1219 extra_params.append(p);
1220 }
1221 return extra_params;
1222}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301223#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001224
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001225// Only adds parameters if the property is set.
1226static void add_sector_size_param(std::vector<std::string>* extra_params_vec) {
1227 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
1228 char sector_size[PROPERTY_VALUE_MAX];
1229
1230 if (property_get(DM_CRYPT_SECTOR_SIZE, sector_size, "") > 0) {
1231 std::string param = StringPrintf("sector_size:%s", sector_size);
1232 extra_params_vec->push_back(std::move(param));
1233
1234 // With this option, IVs will match the sector numbering, instead
1235 // of being hard-coded to being based on 512-byte sectors.
1236 extra_params_vec->emplace_back("iv_large_sectors");
1237 }
1238}
1239
Paul Crowley5afbc622017-11-27 09:42:17 -08001240static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1241 const char* real_blk_name, char* crypto_blk_name, const char* name,
1242 uint32_t flags) {
1243 char buffer[DM_CRYPT_BUF_SIZE];
1244 struct dm_ioctl* io;
1245 unsigned int minor;
1246 int fd = 0;
1247 int err;
1248 int retval = -1;
1249 int version[3];
1250 int load_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301251#ifdef CONFIG_HW_DISK_ENCRYPTION
1252 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1253 char progress[PROPERTY_VALUE_MAX] = {0};
1254 const char *extra_params;
1255#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001256 std::vector<std::string> extra_params_vec;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301257#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001258
Paul Crowley5afbc622017-11-27 09:42:17 -08001259 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1260 SLOGE("Cannot open device-mapper\n");
1261 goto errout;
1262 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001263
Paul Crowley5afbc622017-11-27 09:42:17 -08001264 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001265
Paul Crowley5afbc622017-11-27 09:42:17 -08001266 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1267 err = ioctl(fd, DM_DEV_CREATE, io);
1268 if (err) {
1269 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1270 goto errout;
1271 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001272
Paul Crowley5afbc622017-11-27 09:42:17 -08001273 /* Get the device status, in particular, the name of it's device file */
1274 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1275 if (ioctl(fd, DM_DEV_STATUS, io)) {
1276 SLOGE("Cannot retrieve dm-crypt device status\n");
1277 goto errout;
1278 }
1279 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1280 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001281
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301282#ifdef CONFIG_HW_DISK_ENCRYPTION
1283 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1284 /* Set fde_enabled if either FDE completed or in-progress */
1285 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1286 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1287 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1288 if (is_ice_enabled()) {
1289 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1290 extra_params = "fde_enabled ice allow_encrypt_override";
1291 else
1292 extra_params = "fde_enabled ice";
1293 } else {
1294 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1295 extra_params = "fde_enabled allow_encrypt_override";
1296 else
1297 extra_params = "fde_enabled";
1298 }
1299 } else {
1300 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1301 extra_params = "fde_enabled allow_encrypt_override";
1302 else
1303 extra_params = "fde_enabled";
1304 }
1305 } else {
1306 extra_params = "";
1307 if (! get_dm_crypt_version(fd, name, version)) {
1308 /* Support for allow_discards was added in version 1.11.0 */
1309 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1310 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1311 extra_params = "2 allow_discards allow_encrypt_override";
1312 else
1313 extra_params = "1 allow_discards";
1314 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1315 }
1316 }
1317 }
1318 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1319 extra_params);
1320#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001321 if (!get_dm_crypt_version(fd, name, version)) {
1322 /* Support for allow_discards was added in version 1.11.0 */
1323 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1324 extra_params_vec.emplace_back("allow_discards");
1325 }
1326 }
1327 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1328 extra_params_vec.emplace_back("allow_encrypt_override");
1329 }
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001330 add_sector_size_param(&extra_params_vec);
Paul Crowley5afbc622017-11-27 09:42:17 -08001331 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1332 extra_params_as_string(extra_params_vec).c_str());
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301333#endif
Paul Crowley5afbc622017-11-27 09:42:17 -08001334 if (load_count < 0) {
1335 SLOGE("Cannot load dm-crypt mapping table.\n");
1336 goto errout;
1337 } else if (load_count > 1) {
1338 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1339 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001340
Paul Crowley5afbc622017-11-27 09:42:17 -08001341 /* Resume this device to activate it */
1342 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001343
Paul Crowley5afbc622017-11-27 09:42:17 -08001344 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1345 SLOGE("Cannot resume the dm-crypt device\n");
1346 goto errout;
1347 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001348
Paul Crowley298fa322018-10-30 15:59:24 -07001349 /* Ensure the dm device has been created before returning. */
1350 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1351 // WaitForFile generates a suitable log message
1352 goto errout;
1353 }
1354
Paul Crowley5afbc622017-11-27 09:42:17 -08001355 /* We made it here with no errors. Woot! */
1356 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001357
1358errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001359 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001360
Paul Crowley14c8c072018-09-18 13:30:21 -07001361 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001362}
1363
Paul Crowley14c8c072018-09-18 13:30:21 -07001364static int delete_crypto_blk_dev(const char* name) {
1365 int fd;
1366 char buffer[DM_CRYPT_BUF_SIZE];
1367 struct dm_ioctl* io;
1368 int retval = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001369
Paul Crowley14c8c072018-09-18 13:30:21 -07001370 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1371 SLOGE("Cannot open device-mapper\n");
1372 goto errout;
1373 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001374
Paul Crowley14c8c072018-09-18 13:30:21 -07001375 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001376
Paul Crowley14c8c072018-09-18 13:30:21 -07001377 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1378 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1379 SLOGE("Cannot remove dm-crypt device\n");
1380 goto errout;
1381 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001382
Paul Crowley14c8c072018-09-18 13:30:21 -07001383 /* We made it here with no errors. Woot! */
1384 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001385
1386errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001387 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001388
Paul Crowley14c8c072018-09-18 13:30:21 -07001389 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001390}
1391
Paul Crowley14c8c072018-09-18 13:30:21 -07001392static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1393 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001394 SLOGI("Using pbkdf2 for cryptfs KDF");
1395
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001396 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001397 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1398 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001399}
1400
Paul Crowley14c8c072018-09-18 13:30:21 -07001401static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001402 SLOGI("Using scrypt for cryptfs KDF");
1403
Paul Crowley14c8c072018-09-18 13:30:21 -07001404 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001405
1406 int N = 1 << ftr->N_factor;
1407 int r = 1 << ftr->r_factor;
1408 int p = 1 << ftr->p_factor;
1409
1410 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001411 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001412 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001413
Paul Crowley14c8c072018-09-18 13:30:21 -07001414 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001415}
1416
Paul Crowley14c8c072018-09-18 13:30:21 -07001417static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1418 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001419 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1420
1421 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001422 size_t signature_size;
1423 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001424 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001425
1426 int N = 1 << ftr->N_factor;
1427 int r = 1 << ftr->r_factor;
1428 int p = 1 << ftr->p_factor;
1429
Paul Crowley14c8c072018-09-18 13:30:21 -07001430 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001431 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001432
1433 if (rc) {
1434 SLOGE("scrypt failed");
1435 return -1;
1436 }
1437
Paul Crowley14c8c072018-09-18 13:30:21 -07001438 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001439 SLOGE("Signing failed");
1440 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001441 }
1442
Paul Crowley14c8c072018-09-18 13:30:21 -07001443 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1444 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001445 free(signature);
1446
1447 if (rc) {
1448 SLOGE("scrypt failed");
1449 return -1;
1450 }
1451
1452 return 0;
1453}
1454
Paul Crowley14c8c072018-09-18 13:30:21 -07001455static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1456 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001457 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1458 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001459 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001460 EVP_CIPHER_CTX e_ctx;
1461 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001462 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001463
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001464 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001465 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001466
1467 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001468 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001469 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001470 SLOGE("keymaster_create_key failed");
1471 return -1;
1472 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001473
Paul Crowley14c8c072018-09-18 13:30:21 -07001474 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1475 SLOGE("scrypt failed");
1476 return -1;
1477 }
1478 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001479
Paul Crowley14c8c072018-09-18 13:30:21 -07001480 case KDF_SCRYPT:
1481 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1482 SLOGE("scrypt failed");
1483 return -1;
1484 }
1485 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001486
Paul Crowley14c8c072018-09-18 13:30:21 -07001487 default:
1488 SLOGE("Invalid kdf_type");
1489 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001490 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001491
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001492 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001493 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001494 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1495 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001496 SLOGE("EVP_EncryptInit failed\n");
1497 return -1;
1498 }
1499 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001500
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001501 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001502 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1503 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001504 SLOGE("EVP_EncryptUpdate failed\n");
1505 return -1;
1506 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001507 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001508 SLOGE("EVP_EncryptFinal failed\n");
1509 return -1;
1510 }
1511
Greg Kaiser59ad0182018-02-16 13:01:36 -08001512 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001513 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1514 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001515 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001516
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001517 /* Store the scrypt of the intermediate key, so we can validate if it's a
1518 password error or mount error when things go wrong.
1519 Note there's no need to check for errors, since if this is incorrect, we
1520 simply won't wipe userdata, which is the correct default behavior
1521 */
1522 int N = 1 << crypt_ftr->N_factor;
1523 int r = 1 << crypt_ftr->r_factor;
1524 int p = 1 << crypt_ftr->p_factor;
1525
Paul Crowley14c8c072018-09-18 13:30:21 -07001526 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1527 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001528 sizeof(crypt_ftr->scrypted_intermediate_key));
1529
1530 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001531 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001532 }
1533
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001534 EVP_CIPHER_CTX_cleanup(&e_ctx);
1535
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001536 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001537}
1538
Paul Crowley14c8c072018-09-18 13:30:21 -07001539static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1540 const unsigned char* encrypted_master_key, size_t keysize,
1541 unsigned char* decrypted_master_key, kdf_func kdf,
1542 void* kdf_params, unsigned char** intermediate_key,
1543 size_t* intermediate_key_size) {
1544 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1545 EVP_CIPHER_CTX d_ctx;
1546 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001547
Paul Crowley14c8c072018-09-18 13:30:21 -07001548 /* Turn the password into an intermediate key and IV that can decrypt the
1549 master key */
1550 if (kdf(passwd, salt, ikey, kdf_params)) {
1551 SLOGE("kdf failed");
1552 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001553 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001554
Paul Crowley14c8c072018-09-18 13:30:21 -07001555 /* Initialize the decryption engine */
1556 EVP_CIPHER_CTX_init(&d_ctx);
1557 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1558 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1559 return -1;
1560 }
1561 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1562 /* Decrypt the master key */
1563 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1564 keysize)) {
1565 return -1;
1566 }
1567 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1568 return -1;
1569 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001570
Paul Crowley14c8c072018-09-18 13:30:21 -07001571 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1572 return -1;
1573 }
1574
1575 /* Copy intermediate key if needed by params */
1576 if (intermediate_key && intermediate_key_size) {
1577 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1578 if (*intermediate_key) {
1579 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1580 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1581 }
1582 }
1583
1584 EVP_CIPHER_CTX_cleanup(&d_ctx);
1585
1586 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001587}
1588
Paul Crowley14c8c072018-09-18 13:30:21 -07001589static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001590 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001591 *kdf = scrypt_keymaster;
1592 *kdf_params = ftr;
1593 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001594 *kdf = scrypt;
1595 *kdf_params = ftr;
1596 } else {
1597 *kdf = pbkdf2;
1598 *kdf_params = NULL;
1599 }
1600}
1601
Paul Crowley14c8c072018-09-18 13:30:21 -07001602static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1603 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1604 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001605 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001606 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001607 int ret;
1608
1609 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001610 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1611 decrypted_master_key, kdf, kdf_params, intermediate_key,
1612 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001613 if (ret != 0) {
1614 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001615 }
1616
1617 return ret;
1618}
1619
Paul Crowley14c8c072018-09-18 13:30:21 -07001620static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1621 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001622 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001623 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001624
1625 /* Get some random bits for a key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001626 fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001627 read(fd, key_buf, sizeof(key_buf));
1628 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001629 close(fd);
1630
1631 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301632 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001633}
1634
Paul Crowley14c8c072018-09-18 13:30:21 -07001635int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001636 int i, err, rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301637#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001638
1639 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001640 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001641 if (umount(mountpoint) == 0) {
1642 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001643 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001644
1645 if (errno == EINVAL) {
1646 /* EINVAL is returned if the directory is not a mountpoint,
1647 * i.e. there is no filesystem mounted there. So just get out.
1648 */
1649 break;
1650 }
1651
1652 err = errno;
1653
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301654 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001655 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301656 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001657 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001658 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301659 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001660 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001661 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001662 }
1663 }
1664
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301665 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001666 }
1667
1668 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001669 SLOGD("unmounting %s succeeded\n", mountpoint);
1670 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001671 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001672 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1673 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1674 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001675 }
1676
1677 return rc;
1678}
1679
Paul Crowley14c8c072018-09-18 13:30:21 -07001680static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001681 // NOTE: post_fs_data results in init calling back around to vold, so all
1682 // callers to this method must be async
1683
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001684 /* Do the prep of the /data filesystem */
1685 property_set("vold.post_fs_data_done", "0");
1686 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001687 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001688
Ken Sumrallc5872692013-05-14 15:26:31 -07001689 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001690 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001691 /* We timed out to prep /data in time. Continue wait. */
1692 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001693 }
Wei Wang42e38102017-06-07 10:46:12 -07001694 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001695}
1696
Paul Crowley14c8c072018-09-18 13:30:21 -07001697static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001698 // Mark the footer as bad
1699 struct crypt_mnt_ftr crypt_ftr;
1700 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1701 SLOGE("Failed to get crypto footer - panic");
1702 return;
1703 }
1704
1705 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1706 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1707 SLOGE("Failed to set crypto footer - panic");
1708 return;
1709 }
1710}
1711
Paul Crowley14c8c072018-09-18 13:30:21 -07001712static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001713 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001714 SLOGE("Failed to mount tmpfs on data - panic");
1715 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001716 }
1717
1718 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1719 SLOGE("Failed to trigger post fs data - panic");
1720 return;
1721 }
1722
1723 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1724 SLOGE("Failed to trigger restart min framework - panic");
1725 return;
1726 }
1727}
1728
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001729/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001730static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001731 char crypto_blkdev[MAXPATHLEN];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301732#ifdef CONFIG_HW_DISK_ENCRYPTION
1733 char blkdev[MAXPATHLEN];
1734#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001735 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001736 static int restart_successful = 0;
1737
1738 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001739 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001740 SLOGE("Encrypted filesystem not validated, aborting");
1741 return -1;
1742 }
1743
1744 if (restart_successful) {
1745 SLOGE("System already restarted with encrypted disk, aborting");
1746 return -1;
1747 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001748
Paul Lawrencef4faa572014-01-29 13:31:03 -08001749 if (restart_main) {
1750 /* Here is where we shut down the framework. The init scripts
1751 * start all services in one of three classes: core, main or late_start.
1752 * On boot, we start core and main. Now, we stop main, but not core,
1753 * as core includes vold and a few other really important things that
1754 * we need to keep running. Once main has stopped, we should be able
1755 * to umount the tmpfs /data, then mount the encrypted /data.
1756 * We then restart the class main, and also the class late_start.
1757 * At the moment, I've only put a few things in late_start that I know
1758 * are not needed to bring up the framework, and that also cause problems
1759 * with unmounting the tmpfs /data, but I hope to add add more services
1760 * to the late_start class as we optimize this to decrease the delay
1761 * till the user is asked for the password to the filesystem.
1762 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001763
Paul Lawrencef4faa572014-01-29 13:31:03 -08001764 /* The init files are setup to stop the class main when vold.decrypt is
1765 * set to trigger_reset_main.
1766 */
1767 property_set("vold.decrypt", "trigger_reset_main");
1768 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001769
Paul Lawrencef4faa572014-01-29 13:31:03 -08001770 /* Ugh, shutting down the framework is not synchronous, so until it
1771 * can be fixed, this horrible hack will wait a moment for it all to
1772 * shut down before proceeding. Without it, some devices cannot
1773 * restart the graphics services.
1774 */
1775 sleep(2);
1776 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001777
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001778 /* Now that the framework is shutdown, we should be able to umount()
1779 * the tmpfs filesystem, and mount the real one.
1780 */
1781
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301782#if defined(CONFIG_HW_DISK_ENCRYPTION)
1783#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1784 if (is_ice_enabled()) {
1785 fs_mgr_get_crypt_info(fstab_default, 0, blkdev, sizeof(blkdev));
1786 if (set_ice_param(START_ENCDEC)) {
1787 SLOGE("Failed to set ICE data");
1788 return -1;
1789 }
1790 }
1791#else
1792 property_get("ro.crypto.fs_crypto_blkdev", blkdev, "");
1793 if (strlen(blkdev) == 0) {
1794 SLOGE("fs_crypto_blkdev not set\n");
1795 return -1;
1796 }
1797 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1798#endif
1799#else
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001800 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1801 if (strlen(crypto_blkdev) == 0) {
1802 SLOGE("fs_crypto_blkdev not set\n");
1803 return -1;
1804 }
1805
Paul Crowley14c8c072018-09-18 13:30:21 -07001806 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301807#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001808 /* If ro.crypto.readonly is set to 1, mount the decrypted
1809 * filesystem readonly. This is used when /data is mounted by
1810 * recovery mode.
1811 */
1812 char ro_prop[PROPERTY_VALUE_MAX];
1813 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001814 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001815 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07001816 if (rec) {
1817 rec->flags |= MS_RDONLY;
1818 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001819 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001820
Ken Sumralle5032c42012-04-01 23:58:44 -07001821 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001822 int retries = RETRY_MOUNT_ATTEMPTS;
1823 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001824
1825 /*
1826 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1827 * partitions in the fsck domain.
1828 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001829 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001830 SLOGE("Failed to setexeccon");
1831 return -1;
1832 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001833 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301834#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001835 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, blkdev, 0,
1836 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301837#else
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001838 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1839 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301840#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001841 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1842 /* TODO: invoke something similar to
1843 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1844 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301845#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001846 SLOGI("Failed to mount %s because it is busy - waiting", blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301847#else
Paul Crowley14c8c072018-09-18 13:30:21 -07001848 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301849#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001850 if (--retries) {
1851 sleep(RETRY_MOUNT_DELAY_SECONDS);
1852 } else {
1853 /* Let's hope that a reboot clears away whatever is keeping
1854 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001855 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001856 }
1857 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301858#ifdef CONFIG_HW_DISK_ENCRYPTION
1859 if (--retries) {
1860 sleep(RETRY_MOUNT_DELAY_SECONDS);
1861 } else {
1862 SLOGE("Failed to mount decrypted data");
1863 cryptfs_set_corrupt();
1864 cryptfs_trigger_restart_min_framework();
1865 SLOGI("Started framework to offer wipe");
1866 return -1;
1867 }
1868#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001869 SLOGE("Failed to mount decrypted data");
1870 cryptfs_set_corrupt();
1871 cryptfs_trigger_restart_min_framework();
1872 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001873 if (setexeccon(NULL)) {
1874 SLOGE("Failed to setexeccon");
1875 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001876 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301877#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001878 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001879 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001880 if (setexeccon(NULL)) {
1881 SLOGE("Failed to setexeccon");
1882 return -1;
1883 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001884
Ken Sumralle5032c42012-04-01 23:58:44 -07001885 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001886 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001887 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001888
1889 /* startup service classes main and late_start */
1890 property_set("vold.decrypt", "trigger_restart_framework");
1891 SLOGD("Just triggered restart_framework\n");
1892
1893 /* Give it a few moments to get started */
1894 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301895#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001896 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301897#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001898
Ken Sumrall0cc16632011-01-18 20:32:26 -08001899 if (rc == 0) {
1900 restart_successful = 1;
1901 }
1902
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903 return rc;
1904}
1905
Paul Crowley14c8c072018-09-18 13:30:21 -07001906int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001907 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001908 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001909 SLOGE("cryptfs_restart not valid for file encryption:");
1910 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001911 }
1912
Paul Lawrencef4faa572014-01-29 13:31:03 -08001913 /* Call internal implementation forcing a restart of main service group */
1914 return cryptfs_restart_internal(1);
1915}
1916
Paul Crowley14c8c072018-09-18 13:30:21 -07001917static int do_crypto_complete(const char* mount_point) {
1918 struct crypt_mnt_ftr crypt_ftr;
1919 char encrypted_state[PROPERTY_VALUE_MAX];
1920 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001921
Paul Crowley14c8c072018-09-18 13:30:21 -07001922 property_get("ro.crypto.state", encrypted_state, "");
1923 if (strcmp(encrypted_state, "encrypted")) {
1924 SLOGE("not running with encryption, aborting");
1925 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001926 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001927
Paul Crowley14c8c072018-09-18 13:30:21 -07001928 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001929 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001930 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1931 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001932
Paul Crowley14c8c072018-09-18 13:30:21 -07001933 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1934 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001935
Paul Crowley14c8c072018-09-18 13:30:21 -07001936 /*
1937 * Only report this error if key_loc is a file and it exists.
1938 * If the device was never encrypted, and /data is not mountable for
1939 * some reason, returning 1 should prevent the UI from presenting the
1940 * a "enter password" screen, or worse, a "press button to wipe the
1941 * device" screen.
1942 */
1943 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1944 SLOGE("master key file does not exist, aborting");
1945 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1946 } else {
1947 SLOGE("Error getting crypt footer and key\n");
1948 return CRYPTO_COMPLETE_BAD_METADATA;
1949 }
1950 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001951
Paul Crowley14c8c072018-09-18 13:30:21 -07001952 // Test for possible error flags
1953 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1954 SLOGE("Encryption process is partway completed\n");
1955 return CRYPTO_COMPLETE_PARTIAL;
1956 }
1957
1958 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1959 SLOGE("Encryption process was interrupted but cannot continue\n");
1960 return CRYPTO_COMPLETE_INCONSISTENT;
1961 }
1962
1963 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1964 SLOGE("Encryption is successful but data is corrupt\n");
1965 return CRYPTO_COMPLETE_CORRUPT;
1966 }
1967
1968 /* We passed the test! We shall diminish, and return to the west */
1969 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001970}
1971
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301972#ifdef CONFIG_HW_DISK_ENCRYPTION
1973static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1974 const char *passwd, const char *mount_point, const char *label)
1975{
Bill Peckham0db11972018-10-10 10:25:42 -07001976 /* Allocate enough space for a 256 bit key, but we may use less */
1977 unsigned char decrypted_master_key[32];
1978 char crypto_blkdev[MAXPATHLEN];
1979 char real_blkdev[MAXPATHLEN];
1980 unsigned int orig_failed_decrypt_count;
1981 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301982
Bill Peckham0db11972018-10-10 10:25:42 -07001983 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1984 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301985
Bill Peckham0db11972018-10-10 10:25:42 -07001986 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301987
Bill Peckham0db11972018-10-10 10:25:42 -07001988 int key_index = 0;
1989 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1990 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
1991 if (key_index < 0) {
1992 rc = crypt_ftr->failed_decrypt_count;
1993 goto errout;
1994 }
1995 else {
1996 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301997#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07001998 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
1999 real_blkdev, crypto_blkdev, label, 0)) {
2000 SLOGE("Error creating decrypted block device");
2001 rc = -1;
2002 goto errout;
2003 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302004#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002005 } else {
2006 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
2007 real_blkdev, crypto_blkdev, label, 0)) {
2008 SLOGE("Error creating decrypted block device");
2009 rc = -1;
2010 goto errout;
2011 }
2012 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302013 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302014 }
2015
Bill Peckham0db11972018-10-10 10:25:42 -07002016 if (rc == 0) {
2017 crypt_ftr->failed_decrypt_count = 0;
2018 if (orig_failed_decrypt_count != 0) {
2019 put_crypt_ftr_and_key(crypt_ftr);
2020 }
2021
2022 /* Save the name of the crypto block device
2023 * so we can mount it when restarting the framework. */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302024#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07002025 if (!is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302026#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002027 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2028 master_key_saved = 1;
2029 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302030
Bill Peckham0db11972018-10-10 10:25:42 -07002031 errout:
2032 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302033}
2034#endif
2035
Paul Crowley14c8c072018-09-18 13:30:21 -07002036static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2037 const char* mount_point, const char* label) {
2038 unsigned char decrypted_master_key[MAX_KEY_LEN];
2039 char crypto_blkdev[MAXPATHLEN];
2040 char real_blkdev[MAXPATHLEN];
2041 char tmp_mount_point[64];
2042 unsigned int orig_failed_decrypt_count;
2043 int rc;
2044 int use_keymaster = 0;
2045 int upgrade = 0;
2046 unsigned char* intermediate_key = 0;
2047 size_t intermediate_key_size = 0;
2048 int N = 1 << crypt_ftr->N_factor;
2049 int r = 1 << crypt_ftr->r_factor;
2050 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302051
Paul Crowley14c8c072018-09-18 13:30:21 -07002052 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2053 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002054
Paul Crowley14c8c072018-09-18 13:30:21 -07002055 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2056 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2057 &intermediate_key_size)) {
2058 SLOGE("Failed to decrypt master key\n");
2059 rc = -1;
2060 goto errout;
2061 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002062 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002063
Paul Crowley14c8c072018-09-18 13:30:21 -07002064 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08002065
Paul Crowley14c8c072018-09-18 13:30:21 -07002066 // Create crypto block device - all (non fatal) code paths
2067 // need it
2068 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
2069 0)) {
2070 SLOGE("Error creating decrypted block device\n");
2071 rc = -1;
2072 goto errout;
2073 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002074
Paul Crowley14c8c072018-09-18 13:30:21 -07002075 /* Work out if the problem is the password or the data */
2076 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002077
Paul Crowley14c8c072018-09-18 13:30:21 -07002078 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2079 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2080 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002081
Paul Crowley14c8c072018-09-18 13:30:21 -07002082 // Does the key match the crypto footer?
2083 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2084 sizeof(scrypted_intermediate_key)) == 0) {
2085 SLOGI("Password matches");
2086 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002087 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002088 /* Try mounting the file system anyway, just in case the problem's with
2089 * the footer, not the key. */
2090 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2091 mkdir(tmp_mount_point, 0755);
2092 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
2093 SLOGE("Error temp mounting decrypted block device\n");
2094 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002095
Paul Crowley14c8c072018-09-18 13:30:21 -07002096 rc = ++crypt_ftr->failed_decrypt_count;
2097 put_crypt_ftr_and_key(crypt_ftr);
2098 } else {
2099 /* Success! */
2100 SLOGI("Password did not match but decrypted drive mounted - continue");
2101 umount(tmp_mount_point);
2102 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002103 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002104 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002105
Paul Crowley14c8c072018-09-18 13:30:21 -07002106 if (rc == 0) {
2107 crypt_ftr->failed_decrypt_count = 0;
2108 if (orig_failed_decrypt_count != 0) {
2109 put_crypt_ftr_and_key(crypt_ftr);
2110 }
2111
2112 /* Save the name of the crypto block device
2113 * so we can mount it when restarting the framework. */
2114 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2115
2116 /* Also save a the master key so we can reencrypted the key
2117 * the key when we want to change the password on it. */
2118 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2119 saved_mount_point = strdup(mount_point);
2120 master_key_saved = 1;
2121 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2122 rc = 0;
2123
2124 // Upgrade if we're not using the latest KDF.
2125 use_keymaster = keymaster_check_compatibility();
2126 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2127 // Don't allow downgrade
2128 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2129 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2130 upgrade = 1;
2131 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2132 crypt_ftr->kdf_type = KDF_SCRYPT;
2133 upgrade = 1;
2134 }
2135
2136 if (upgrade) {
2137 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002138 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002139 if (!rc) {
2140 rc = put_crypt_ftr_and_key(crypt_ftr);
2141 }
2142 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2143
2144 // Do not fail even if upgrade failed - machine is bootable
2145 // Note that if this code is ever hit, there is a *serious* problem
2146 // since KDFs should never fail. You *must* fix the kdf before
2147 // proceeding!
2148 if (rc) {
2149 SLOGW(
2150 "Upgrade failed with error %d,"
2151 " but continuing with previous state",
2152 rc);
2153 rc = 0;
2154 }
2155 }
2156 }
2157
2158errout:
2159 if (intermediate_key) {
2160 memset(intermediate_key, 0, intermediate_key_size);
2161 free(intermediate_key);
2162 }
2163 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002164}
2165
Ken Sumrall29d8da82011-05-18 17:20:07 -07002166/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002167 * Called by vold when it's asked to mount an encrypted external
2168 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002169 * as any metadata is been stored in a separate, small partition. We
2170 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07002171 *
2172 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002173 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002174int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
2175 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002176 uint64_t nr_sec = 0;
2177 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002178 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002179 return -1;
2180 }
2181
Jeff Sharkey9c484982015-03-31 10:35:33 -07002182 struct crypt_mnt_ftr ext_crypt_ftr;
2183 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2184 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002185 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07002186 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002187 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002188 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002189 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002190 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2191 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002192
Paul Crowley385cb8c2018-03-29 13:27:23 -07002193 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07002194}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002195
Jeff Sharkey9c484982015-03-31 10:35:33 -07002196/*
2197 * Called by vold when it's asked to unmount an encrypted external
2198 * storage volume.
2199 */
2200int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002201 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002202}
2203
Paul Crowley14c8c072018-09-18 13:30:21 -07002204int cryptfs_crypto_complete(void) {
2205 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002206}
2207
Paul Crowley14c8c072018-09-18 13:30:21 -07002208int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002209 char encrypted_state[PROPERTY_VALUE_MAX];
2210 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002211 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2212 SLOGE(
2213 "encrypted fs already validated or not running with encryption,"
2214 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002215 return -1;
2216 }
2217
2218 if (get_crypt_ftr_and_key(crypt_ftr)) {
2219 SLOGE("Error getting crypt footer and key");
2220 return -1;
2221 }
2222
2223 return 0;
2224}
2225
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302226#ifdef CONFIG_HW_DISK_ENCRYPTION
2227int cryptfs_check_passwd_hw(const char* passwd)
2228{
2229 struct crypt_mnt_ftr crypt_ftr;
2230 int rc;
2231 unsigned char master_key[KEY_LEN_BYTES];
2232
2233 /* get key */
2234 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2235 SLOGE("Error getting crypt footer and key");
2236 return -1;
2237 }
2238
2239 /*
2240 * in case of manual encryption (from GUI), the encryption is done with
2241 * default password
2242 */
2243 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2244 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2245 * which was created with actual password before reboot.
2246 */
2247 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2248 if (rc) {
2249 SLOGE("password doesn't match");
2250 rc = ++crypt_ftr.failed_decrypt_count;
2251 put_crypt_ftr_and_key(&crypt_ftr);
2252 return rc;
2253 }
2254
2255 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2256 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2257
2258 if (rc) {
2259 SLOGE("Default password did not match on reboot encryption");
2260 return rc;
2261 }
2262
2263 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2264 put_crypt_ftr_and_key(&crypt_ftr);
2265 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2266 if (rc) {
2267 SLOGE("Could not change password on reboot encryption");
2268 return rc;
2269 }
2270 } else
2271 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2272 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2273
2274 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2275 cryptfs_clear_password();
2276 password = strdup(passwd);
2277 struct timespec now;
2278 clock_gettime(CLOCK_BOOTTIME, &now);
2279 password_expiry_time = now.tv_sec + password_max_age_seconds;
2280 }
2281
2282 return rc;
2283}
2284#endif
2285
Paul Crowley14c8c072018-09-18 13:30:21 -07002286int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002287 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002288 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002289 SLOGE("cryptfs_check_passwd not valid for file encryption");
2290 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002291 }
2292
Paul Lawrencef4faa572014-01-29 13:31:03 -08002293 struct crypt_mnt_ftr crypt_ftr;
2294 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002295
Paul Lawrencef4faa572014-01-29 13:31:03 -08002296 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002297 if (rc) {
2298 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002299 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002300 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002301
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302302#ifdef CONFIG_HW_DISK_ENCRYPTION
2303 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2304 return cryptfs_check_passwd_hw(passwd);
2305#endif
2306
Paul Crowley14c8c072018-09-18 13:30:21 -07002307 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002308 if (rc) {
2309 SLOGE("Password did not match");
2310 return rc;
2311 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002312
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002313 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2314 // Here we have a default actual password but a real password
2315 // we must test against the scrypted value
2316 // First, we must delete the crypto block device that
2317 // test_mount_encrypted_fs leaves behind as a side effect
2318 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002319 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2320 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002321 if (rc) {
2322 SLOGE("Default password did not match on reboot encryption");
2323 return rc;
2324 }
2325
2326 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2327 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302328 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002329 if (rc) {
2330 SLOGE("Could not change password on reboot encryption");
2331 return rc;
2332 }
2333 }
2334
2335 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002336 cryptfs_clear_password();
2337 password = strdup(passwd);
2338 struct timespec now;
2339 clock_gettime(CLOCK_BOOTTIME, &now);
2340 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002341 }
2342
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002343 return rc;
2344}
2345
Paul Crowley14c8c072018-09-18 13:30:21 -07002346int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002347 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002348 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002349 char encrypted_state[PROPERTY_VALUE_MAX];
2350 int rc;
2351
2352 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002353 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002354 SLOGE("device not encrypted, aborting");
2355 return -2;
2356 }
2357
2358 if (!master_key_saved) {
2359 SLOGE("encrypted fs not yet mounted, aborting");
2360 return -1;
2361 }
2362
2363 if (!saved_mount_point) {
2364 SLOGE("encrypted fs failed to save mount point, aborting");
2365 return -1;
2366 }
2367
Ken Sumrall160b4d62013-04-22 12:15:39 -07002368 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002369 SLOGE("Error getting crypt footer and key\n");
2370 return -1;
2371 }
2372
2373 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2374 /* If the device has no password, then just say the password is valid */
2375 rc = 0;
2376 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302377#ifdef CONFIG_HW_DISK_ENCRYPTION
2378 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2379 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2380 rc = 0;
2381 else
2382 rc = -1;
2383 } else {
2384 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2385 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2386 /* They match, the password is correct */
2387 rc = 0;
2388 } else {
2389 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2390 sleep(1);
2391 rc = 1;
2392 }
2393 }
2394#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002395 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002396 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2397 /* They match, the password is correct */
2398 rc = 0;
2399 } else {
2400 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2401 sleep(1);
2402 rc = 1;
2403 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302404#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002405 }
2406
2407 return rc;
2408}
2409
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002410/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002411 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002412 * Presumably, at a minimum, the caller will update the
2413 * filesystem size and crypto_type_name after calling this function.
2414 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002415static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002416 off64_t off;
2417
2418 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002419 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002420 ftr->major_version = CURRENT_MAJOR_VERSION;
2421 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002422 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002423 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002424
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002425 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002426 case 1:
2427 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2428 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002429
Paul Crowley14c8c072018-09-18 13:30:21 -07002430 case 0:
2431 ftr->kdf_type = KDF_SCRYPT;
2432 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002433
Paul Crowley14c8c072018-09-18 13:30:21 -07002434 default:
2435 SLOGE("keymaster_check_compatibility failed");
2436 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002437 }
2438
Kenny Rootc4c70f12013-06-14 12:11:38 -07002439 get_device_scrypt_params(ftr);
2440
Ken Sumrall160b4d62013-04-22 12:15:39 -07002441 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2442 if (get_crypt_ftr_info(NULL, &off) == 0) {
2443 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002444 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002445 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002446
2447 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002448}
2449
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002450#define FRAMEWORK_BOOT_WAIT 60
2451
Paul Crowley14c8c072018-09-18 13:30:21 -07002452static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2453 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002454 if (fd == -1) {
2455 SLOGE("Error opening file %s", filename);
2456 return -1;
2457 }
2458
2459 char block[CRYPT_INPLACE_BUFSIZE];
2460 memset(block, 0, sizeof(block));
2461 if (unix_read(fd, block, sizeof(block)) < 0) {
2462 SLOGE("Error reading file %s", filename);
2463 close(fd);
2464 return -1;
2465 }
2466
2467 close(fd);
2468
2469 SHA256_CTX c;
2470 SHA256_Init(&c);
2471 SHA256_Update(&c, block, sizeof(block));
2472 SHA256_Final(buf, &c);
2473
2474 return 0;
2475}
2476
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002477static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2478 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002479 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002480 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002481
Paul Lawrence87999172014-02-20 12:21:31 -08002482 /* The size of the userdata partition, and add in the vold volumes below */
2483 tot_encryption_size = crypt_ftr->fs_size;
2484
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002485 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002486 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002487
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002488 if (rc == ENABLE_INPLACE_ERR_DEV) {
2489 /* Hack for b/17898962 */
2490 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2491 cryptfs_reboot(RebootType::reboot);
2492 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002493
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002494 if (!rc) {
2495 crypt_ftr->encrypted_upto = cur_encryption_done;
2496 }
Paul Lawrence87999172014-02-20 12:21:31 -08002497
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002498 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2499 /* The inplace routine never actually sets the progress to 100% due
2500 * to the round down nature of integer division, so set it here */
2501 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002502 }
2503
2504 return rc;
2505}
2506
Paul Crowleyb64933a2017-10-31 08:25:55 -07002507static int vold_unmountAll(void) {
2508 VolumeManager* vm = VolumeManager::Instance();
2509 return vm->unmountAll();
2510}
2511
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002512int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002513 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002514 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002515 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002516 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002517 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002518 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002519 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002520 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002521 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002522 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002523 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002524 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302525#ifdef CONFIG_HW_DISK_ENCRYPTION
2526 unsigned char newpw[32];
2527 int key_index = 0;
2528#endif
2529 int index = 0;
2530
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002531 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002532 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2533 /* An encryption was underway and was interrupted */
2534 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2535 crypt_ftr.encrypted_upto = 0;
2536 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002537
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002538 /* At this point, we are in an inconsistent state. Until we successfully
2539 complete encryption, a reboot will leave us broken. So mark the
2540 encryption failed in case that happens.
2541 On successfully completing encryption, remove this flag */
2542 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002543
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002544 put_crypt_ftr_and_key(&crypt_ftr);
2545 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2546 if (!check_ftr_sha(&crypt_ftr)) {
2547 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2548 put_crypt_ftr_and_key(&crypt_ftr);
2549 goto error_unencrypted;
2550 }
2551
2552 /* Doing a reboot-encryption*/
2553 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2554 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2555 rebootEncryption = true;
2556 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002557 } else {
2558 // We don't want to accidentally reference invalid data.
2559 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002560 }
2561
2562 property_get("ro.crypto.state", encrypted_state, "");
2563 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2564 SLOGE("Device is already running encrypted, aborting");
2565 goto error_unencrypted;
2566 }
2567
2568 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002569 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2570 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002571
Ken Sumrall3ed82362011-01-28 23:31:16 -08002572 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002573 uint64_t nr_sec;
2574 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002575 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2576 goto error_unencrypted;
2577 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002578
2579 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002580 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002581 uint64_t fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002582 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002583 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002584
Paul Lawrence87999172014-02-20 12:21:31 -08002585 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002586
2587 if (fs_size_sec > max_fs_size_sec) {
2588 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2589 goto error_unencrypted;
2590 }
2591 }
2592
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002593 /* Get a wakelock as this may take a while, and we don't want the
2594 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2595 * wants to keep the screen on, it can grab a full wakelock.
2596 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002597 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002598 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2599
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002600 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002601 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002602 */
2603 property_set("vold.decrypt", "trigger_shutdown_framework");
2604 SLOGD("Just asked init to shut down class main\n");
2605
Jeff Sharkey9c484982015-03-31 10:35:33 -07002606 /* Ask vold to unmount all devices that it manages */
2607 if (vold_unmountAll()) {
2608 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002609 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002610
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002611 /* no_ui means we are being called from init, not settings.
2612 Now we always reboot from settings, so !no_ui means reboot
2613 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002614 if (!no_ui) {
2615 /* Try fallback, which is to reboot and try there */
2616 onlyCreateHeader = true;
2617 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2618 if (breadcrumb == 0) {
2619 SLOGE("Failed to create breadcrumb file");
2620 goto error_shutting_down;
2621 }
2622 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002623 }
2624
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002625 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002626 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002627 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002628 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2629 goto error_shutting_down;
2630 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002631
Paul Lawrence87999172014-02-20 12:21:31 -08002632 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002633 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002634 } else {
2635 crypt_ftr.fs_size = nr_sec;
2636 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002637 /* At this point, we are in an inconsistent state. Until we successfully
2638 complete encryption, a reboot will leave us broken. So mark the
2639 encryption failed in case that happens.
2640 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002641 if (onlyCreateHeader) {
2642 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2643 } else {
2644 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2645 }
Paul Lawrence87999172014-02-20 12:21:31 -08002646 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302647#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002648 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2649 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302650#else
Paul Crowley14c8c072018-09-18 13:30:21 -07002651 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2652 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302653#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002654
Paul Lawrence87999172014-02-20 12:21:31 -08002655 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002656 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2657 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002658 SLOGE("Cannot create encrypted master key\n");
2659 goto error_shutting_down;
2660 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002661
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002662 /* Replace scrypted intermediate key if we are preparing for a reboot */
2663 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002664 unsigned char fake_master_key[MAX_KEY_LEN];
2665 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002666 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002667 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002668 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002669 }
2670
Paul Lawrence87999172014-02-20 12:21:31 -08002671 /* Write the key to the end of the partition */
2672 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002673
Paul Lawrence87999172014-02-20 12:21:31 -08002674 /* If any persistent data has been remembered, save it.
2675 * If none, create a valid empty table and save that.
2676 */
2677 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002678 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2679 if (pdata) {
2680 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2681 persist_data = pdata;
2682 }
Paul Lawrence87999172014-02-20 12:21:31 -08002683 }
2684 if (persist_data) {
2685 save_persistent_data();
2686 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002687 }
2688
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302689 /* When encryption triggered from settings, encryption starts after reboot.
2690 So set the encryption key when the actual encryption starts.
2691 */
2692#ifdef CONFIG_HW_DISK_ENCRYPTION
2693 if (previously_encrypted_upto == 0) {
2694 if (!rebootEncryption)
2695 clear_hw_device_encryption_key();
2696
2697 if (get_keymaster_hw_fde_passwd(
2698 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2699 newpw, crypt_ftr.salt, &crypt_ftr))
2700 key_index = set_hw_device_encryption_key(
2701 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2702 (char*)crypt_ftr.crypto_type_name);
2703 else
2704 key_index = set_hw_device_encryption_key((const char*)newpw,
2705 (char*) crypt_ftr.crypto_type_name);
2706 if (key_index < 0)
2707 goto error_shutting_down;
2708
2709 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2710 put_crypt_ftr_and_key(&crypt_ftr);
2711 }
2712#endif
2713
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002714 if (onlyCreateHeader) {
2715 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002716 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302717 } else {
2718 /* Do extra work for a better UX when doing the long inplace encryption */
2719 /* Now that /data is unmounted, we need to mount a tmpfs
2720 * /data, set a property saying we're doing inplace encryption,
2721 * and restart the framework.
2722 */
2723 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2724 goto error_shutting_down;
2725 }
2726 /* Tells the framework that inplace encryption is starting */
2727 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002728
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302729 /* restart the framework. */
2730 /* Create necessary paths on /data */
2731 prep_data_fs();
2732
2733 /* Ugh, shutting down the framework is not synchronous, so until it
2734 * can be fixed, this horrible hack will wait a moment for it all to
2735 * shut down before proceeding. Without it, some devices cannot
2736 * restart the graphics services.
2737 */
2738 sleep(2);
2739
Ajay Dudani87701e22014-09-17 21:02:52 -07002740 /* startup service classes main and late_start */
2741 property_set("vold.decrypt", "trigger_restart_min_framework");
2742 SLOGD("Just triggered restart_min_framework\n");
2743
2744 /* OK, the framework is restarted and will soon be showing a
2745 * progress bar. Time to setup an encrypted mapping, and
2746 * either write a new filesystem, or encrypt in place updating
2747 * the progress bar as we work.
2748 */
2749 }
2750
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002751 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302752#ifdef CONFIG_HW_DISK_ENCRYPTION
2753 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302754#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2755 strlcpy(crypto_blkdev, real_blkdev, sizeof(crypto_blkdev));
2756#else
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302757 create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev, crypto_blkdev,
2758 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302759#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302760 else
2761 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2762 CRYPTO_BLOCK_DEVICE, 0);
2763#else
Ken Sumrall29d8da82011-05-18 17:20:07 -07002764 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002765 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302766#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002767
Paul Lawrence87999172014-02-20 12:21:31 -08002768 /* If we are continuing, check checksums match */
2769 rc = 0;
2770 if (previously_encrypted_upto) {
2771 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302772#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2773 if (set_ice_param(START_ENCDEC)) {
2774 SLOGE("Failed to set ICE data");
2775 goto error_shutting_down;
2776 }
2777#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002778 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002779
Paul Crowley14c8c072018-09-18 13:30:21 -07002780 if (!rc &&
2781 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002782 SLOGE("Checksums do not match - trigger wipe");
2783 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002784 }
2785 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002786
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302787#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2788 if (set_ice_param(START_ENC)) {
2789 SLOGE("Failed to set ICE data");
2790 goto error_shutting_down;
2791 }
2792#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002793 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002794 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002795 previously_encrypted_upto);
2796 }
2797
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302798#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2799 if (set_ice_param(START_ENCDEC)) {
2800 SLOGE("Failed to set ICE data");
2801 goto error_shutting_down;
2802 }
2803#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002804 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002805 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002806 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002807 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002808 SLOGE("Error calculating checksum for continuing encryption");
2809 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002810 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002811 }
2812
2813 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302814#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2815 if (!is_ice_enabled())
2816 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2817#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002818 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302819#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002820
Paul Crowley14c8c072018-09-18 13:30:21 -07002821 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002822 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002823 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002824
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002825 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002826 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2827 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002828 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002829 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002830
Paul Lawrence6bfed202014-07-28 12:47:22 -07002831 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002832
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002833 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2834 char value[PROPERTY_VALUE_MAX];
2835 property_get("ro.crypto.state", value, "");
2836 if (!strcmp(value, "")) {
2837 /* default encryption - continue first boot sequence */
2838 property_set("ro.crypto.state", "encrypted");
2839 property_set("ro.crypto.type", "block");
2840 release_wake_lock(lockid);
2841 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2842 // Bring up cryptkeeper that will check the password and set it
2843 property_set("vold.decrypt", "trigger_shutdown_framework");
2844 sleep(2);
2845 property_set("vold.encrypt_progress", "");
2846 cryptfs_trigger_restart_min_framework();
2847 } else {
2848 cryptfs_check_passwd(DEFAULT_PASSWORD);
2849 cryptfs_restart_internal(1);
2850 }
2851 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002852 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002853 sleep(2); /* Give the UI a chance to show 100% progress */
2854 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002855 }
Paul Lawrence87999172014-02-20 12:21:31 -08002856 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002857 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002858 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002859 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002860 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002861 char value[PROPERTY_VALUE_MAX];
2862
Ken Sumrall319369a2012-06-27 16:30:18 -07002863 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002864 if (!strcmp(value, "1")) {
2865 /* wipe data if encryption failed */
2866 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002867 std::string err;
2868 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002869 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002870 if (!write_bootloader_message(options, &err)) {
2871 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002872 }
Josh Gaofec44372017-08-28 13:22:55 -07002873 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002874 } else {
2875 /* set property to trigger dialog */
2876 property_set("vold.encrypt_progress", "error_partially_encrypted");
2877 release_wake_lock(lockid);
2878 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002879 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002880 }
2881
Ken Sumrall3ed82362011-01-28 23:31:16 -08002882 /* hrm, the encrypt step claims success, but the reboot failed.
2883 * This should not happen.
2884 * Set the property and return. Hope the framework can deal with it.
2885 */
2886 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002887 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002888 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002889
2890error_unencrypted:
2891 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002892 if (lockid[0]) {
2893 release_wake_lock(lockid);
2894 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002895 return -1;
2896
2897error_shutting_down:
2898 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2899 * but the framework is stopped and not restarted to show the error, so it's up to
2900 * vold to restart the system.
2901 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002902 SLOGE(
2903 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2904 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002905 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002906
2907 /* shouldn't get here */
2908 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002909 if (lockid[0]) {
2910 release_wake_lock(lockid);
2911 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002912 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002913}
2914
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002915int cryptfs_enable(int type, const char* passwd, int no_ui) {
2916 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002917}
2918
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002919int cryptfs_enable_default(int no_ui) {
2920 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002921}
2922
Bill Peckham0db11972018-10-10 10:25:42 -07002923int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002924 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002925 SLOGE("cryptfs_changepw not valid for file encryption");
2926 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002927 }
2928
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002929 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002930 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002931
2932 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002933 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002934 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002935 return -1;
2936 }
2937
Paul Lawrencef4faa572014-01-29 13:31:03 -08002938 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2939 SLOGE("Invalid crypt_type %d", crypt_type);
2940 return -1;
2941 }
2942
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002943 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002944 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002945 SLOGE("Error getting crypt footer and key");
2946 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002947 }
2948
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302949#ifdef CONFIG_HW_DISK_ENCRYPTION
2950 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2951 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
2952 else {
2953 crypt_ftr.crypt_type = crypt_type;
2954
2955 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
2956 DEFAULT_PASSWORD : newpw,
2957 crypt_ftr.salt,
2958 saved_master_key,
2959 crypt_ftr.master_key,
2960 &crypt_ftr, false);
2961 if (rc) {
2962 SLOGE("Encrypt master key failed: %d", rc);
2963 return -1;
2964 }
2965 /* save the key */
2966 put_crypt_ftr_and_key(&crypt_ftr);
2967
2968 return 0;
2969 }
2970#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08002971 crypt_ftr.crypt_type = crypt_type;
2972
Paul Crowley14c8c072018-09-18 13:30:21 -07002973 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07002974 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
2975 false);
JP Abgrall933216c2015-02-11 13:44:32 -08002976 if (rc) {
2977 SLOGE("Encrypt master key failed: %d", rc);
2978 return -1;
2979 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002980 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002981 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002982
2983 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302984#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002985}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002986
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302987#ifdef CONFIG_HW_DISK_ENCRYPTION
2988int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
2989{
2990 struct crypt_mnt_ftr crypt_ftr;
2991 int rc;
2992 int previous_type;
2993
2994 /* get key */
2995 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2996 SLOGE("Error getting crypt footer and key");
2997 return -1;
2998 }
2999
3000 previous_type = crypt_ftr.crypt_type;
3001 int rc1;
3002 unsigned char tmp_curpw[32] = {0};
3003 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3004 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3005 crypt_ftr.salt, &crypt_ftr);
3006
3007 crypt_ftr.crypt_type = crypt_type;
3008
3009 int ret, rc2;
3010 unsigned char tmp_newpw[32] = {0};
3011
3012 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3013 DEFAULT_PASSWORD : newpw , tmp_newpw,
3014 crypt_ftr.salt, &crypt_ftr);
3015
3016 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3017 ret = update_hw_device_encryption_key(
3018 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3019 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3020 (char*)crypt_ftr.crypto_type_name);
3021 if (ret) {
3022 SLOGE("Error updating device encryption hardware key ret %d", ret);
3023 return -1;
3024 } else {
3025 SLOGI("Encryption hardware key updated");
3026 }
3027 }
3028
3029 /* save the key */
3030 put_crypt_ftr_and_key(&crypt_ftr);
3031 return 0;
3032}
3033#endif
3034
Rubin Xu85c01f92014-10-13 12:49:54 +01003035static unsigned int persist_get_max_entries(int encrypted) {
3036 struct crypt_mnt_ftr crypt_ftr;
3037 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003038
3039 /* If encrypted, use the values from the crypt_ftr, otherwise
3040 * use the values for the current spec.
3041 */
3042 if (encrypted) {
3043 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01003044 /* Something is wrong, assume no space for entries */
3045 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003046 }
3047 dsize = crypt_ftr.persist_data_size;
3048 } else {
3049 dsize = CRYPT_PERSIST_DATA_SIZE;
3050 }
3051
Rubin Xud78181b2018-10-09 16:13:38 +01003052 if (dsize > sizeof(struct crypt_persist_data)) {
3053 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3054 } else {
3055 return 0;
3056 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003057}
3058
Paul Crowley14c8c072018-09-18 13:30:21 -07003059static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003060 unsigned int i;
3061
3062 if (persist_data == NULL) {
3063 return -1;
3064 }
3065 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3066 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3067 /* We found it! */
3068 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3069 return 0;
3070 }
3071 }
3072
3073 return -1;
3074}
3075
Paul Crowley14c8c072018-09-18 13:30:21 -07003076static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003077 unsigned int i;
3078 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003079 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003080
3081 if (persist_data == NULL) {
3082 return -1;
3083 }
3084
Rubin Xu85c01f92014-10-13 12:49:54 +01003085 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003086
3087 num = persist_data->persist_valid_entries;
3088
3089 for (i = 0; i < num; i++) {
3090 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3091 /* We found an existing entry, update it! */
3092 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3093 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3094 return 0;
3095 }
3096 }
3097
3098 /* We didn't find it, add it to the end, if there is room */
3099 if (persist_data->persist_valid_entries < max_persistent_entries) {
3100 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3101 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3102 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3103 persist_data->persist_valid_entries++;
3104 return 0;
3105 }
3106
3107 return -1;
3108}
3109
Rubin Xu85c01f92014-10-13 12:49:54 +01003110/**
3111 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3112 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3113 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003114int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003115 std::string key_ = key;
3116 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003117
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003118 std::string parsed_field;
3119 unsigned parsed_index;
3120
3121 std::string::size_type split = key_.find_last_of('_');
3122 if (split == std::string::npos) {
3123 parsed_field = key_;
3124 parsed_index = 0;
3125 } else {
3126 parsed_field = key_.substr(0, split);
3127 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003128 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003129
3130 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003131}
3132
3133/*
3134 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3135 * remaining entries starting from index will be deleted.
3136 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3137 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3138 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3139 *
3140 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003141static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003142 unsigned int i;
3143 unsigned int j;
3144 unsigned int num;
3145
3146 if (persist_data == NULL) {
3147 return PERSIST_DEL_KEY_ERROR_OTHER;
3148 }
3149
3150 num = persist_data->persist_valid_entries;
3151
Paul Crowley14c8c072018-09-18 13:30:21 -07003152 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003153 // Filter out to-be-deleted entries in place.
3154 for (i = 0; i < num; i++) {
3155 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3156 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3157 j++;
3158 }
3159 }
3160
3161 if (j < num) {
3162 persist_data->persist_valid_entries = j;
3163 // Zeroise the remaining entries
3164 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3165 return PERSIST_DEL_KEY_OK;
3166 } else {
3167 // Did not find an entry matching the given fieldname
3168 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3169 }
3170}
3171
Paul Crowley14c8c072018-09-18 13:30:21 -07003172static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003173 unsigned int i;
3174 unsigned int count;
3175
3176 if (persist_data == NULL) {
3177 return -1;
3178 }
3179
3180 count = 0;
3181 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3182 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3183 count++;
3184 }
3185 }
3186
3187 return count;
3188}
3189
Ken Sumrall160b4d62013-04-22 12:15:39 -07003190/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003191int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003192 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003193 SLOGE("Cannot get field when file encrypted");
3194 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003195 }
3196
Ken Sumrall160b4d62013-04-22 12:15:39 -07003197 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003198 /* CRYPTO_GETFIELD_OK is success,
3199 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3200 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3201 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003202 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003203 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3204 int i;
3205 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003206
3207 if (persist_data == NULL) {
3208 load_persistent_data();
3209 if (persist_data == NULL) {
3210 SLOGE("Getfield error, cannot load persistent data");
3211 goto out;
3212 }
3213 }
3214
Rubin Xu85c01f92014-10-13 12:49:54 +01003215 // Read value from persistent entries. If the original value is split into multiple entries,
3216 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003217 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003218 // 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 -07003219 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003220 // value too small
3221 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3222 goto out;
3223 }
3224 rc = CRYPTO_GETFIELD_OK;
3225
3226 for (i = 1; /* break explicitly */; i++) {
3227 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003228 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003229 // If the fieldname is very long, we stop as soon as it begins to overflow the
3230 // maximum field length. At this point we have in fact fully read out the original
3231 // value because cryptfs_setfield would not allow fields with longer names to be
3232 // written in the first place.
3233 break;
3234 }
3235 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003236 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3237 // value too small.
3238 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3239 goto out;
3240 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003241 } else {
3242 // Exhaust all entries.
3243 break;
3244 }
3245 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003246 } else {
3247 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003248 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003249 }
3250
3251out:
3252 return rc;
3253}
3254
3255/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003256int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003257 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003258 SLOGE("Cannot set field when file encrypted");
3259 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003260 }
3261
Ken Sumrall160b4d62013-04-22 12:15:39 -07003262 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003263 /* 0 is success, negative values are error */
3264 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003265 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003266 unsigned int field_id;
3267 char temp_field[PROPERTY_KEY_MAX];
3268 unsigned int num_entries;
3269 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003270
3271 if (persist_data == NULL) {
3272 load_persistent_data();
3273 if (persist_data == NULL) {
3274 SLOGE("Setfield error, cannot load persistent data");
3275 goto out;
3276 }
3277 }
3278
3279 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003280 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003281 encrypted = 1;
3282 }
3283
Rubin Xu85c01f92014-10-13 12:49:54 +01003284 // Compute the number of entries required to store value, each entry can store up to
3285 // (PROPERTY_VALUE_MAX - 1) chars
3286 if (strlen(value) == 0) {
3287 // Empty value also needs one entry to store.
3288 num_entries = 1;
3289 } else {
3290 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3291 }
3292
3293 max_keylen = strlen(fieldname);
3294 if (num_entries > 1) {
3295 // Need an extra "_%d" suffix.
3296 max_keylen += 1 + log10(num_entries);
3297 }
3298 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3299 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003300 goto out;
3301 }
3302
Rubin Xu85c01f92014-10-13 12:49:54 +01003303 // Make sure we have enough space to write the new value
3304 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3305 persist_get_max_entries(encrypted)) {
3306 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3307 goto out;
3308 }
3309
3310 // Now that we know persist_data has enough space for value, let's delete the old field first
3311 // to make up space.
3312 persist_del_keys(fieldname, 0);
3313
3314 if (persist_set_key(fieldname, value, encrypted)) {
3315 // fail to set key, should not happen as we have already checked the available space
3316 SLOGE("persist_set_key() error during setfield()");
3317 goto out;
3318 }
3319
3320 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003321 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003322
3323 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3324 // fail to set key, should not happen as we have already checked the available space.
3325 SLOGE("persist_set_key() error during setfield()");
3326 goto out;
3327 }
3328 }
3329
Ken Sumrall160b4d62013-04-22 12:15:39 -07003330 /* If we are running encrypted, save the persistent data now */
3331 if (encrypted) {
3332 if (save_persistent_data()) {
3333 SLOGE("Setfield error, cannot save persistent data");
3334 goto out;
3335 }
3336 }
3337
Rubin Xu85c01f92014-10-13 12:49:54 +01003338 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003339
3340out:
3341 return rc;
3342}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003343
3344/* Checks userdata. Attempt to mount the volume if default-
3345 * encrypted.
3346 * On success trigger next init phase and return 0.
3347 * Currently do not handle failure - see TODO below.
3348 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003349int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003350 int crypt_type = cryptfs_get_password_type();
3351 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3352 SLOGE("Bad crypt type - error");
3353 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003354 SLOGD(
3355 "Password is not default - "
3356 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003357 property_set("vold.decrypt", "trigger_restart_min_framework");
3358 return 0;
3359 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3360 SLOGD("Password is default - restarting filesystem");
3361 cryptfs_restart_internal(0);
3362 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003363 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003364 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003365 }
3366
Paul Lawrence6bfed202014-07-28 12:47:22 -07003367 /** Corrupt. Allow us to boot into framework, which will detect bad
3368 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003369 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003370 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003371 return 0;
3372}
3373
3374/* Returns type of the password, default, pattern, pin or password.
3375 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003376int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003377 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003378 SLOGE("cryptfs_get_password_type not valid for file encryption");
3379 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003380 }
3381
Paul Lawrencef4faa572014-01-29 13:31:03 -08003382 struct crypt_mnt_ftr crypt_ftr;
3383
3384 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3385 SLOGE("Error getting crypt footer and key\n");
3386 return -1;
3387 }
3388
Paul Lawrence6bfed202014-07-28 12:47:22 -07003389 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3390 return -1;
3391 }
3392
Paul Lawrencef4faa572014-01-29 13:31:03 -08003393 return crypt_ftr.crypt_type;
3394}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003395
Paul Crowley14c8c072018-09-18 13:30:21 -07003396const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003397 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003398 SLOGE("cryptfs_get_password not valid for file encryption");
3399 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003400 }
3401
Paul Lawrence399317e2014-03-10 13:20:50 -07003402 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003403 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003404 if (now.tv_sec < password_expiry_time) {
3405 return password;
3406 } else {
3407 cryptfs_clear_password();
3408 return 0;
3409 }
3410}
3411
Paul Crowley14c8c072018-09-18 13:30:21 -07003412void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003413 if (password) {
3414 size_t len = strlen(password);
3415 memset(password, 0, len);
3416 free(password);
3417 password = 0;
3418 password_expiry_time = 0;
3419 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003420}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003421
Paul Crowley14c8c072018-09-18 13:30:21 -07003422int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07003423 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07003424 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07003425}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303426
3427int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3428{
3429 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3430 SLOGE("Failed to initialize crypt_ftr");
3431 return -1;
3432 }
3433
3434 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3435 crypt_ftr->salt, crypt_ftr)) {
3436 SLOGE("Cannot create encrypted master key\n");
3437 return -1;
3438 }
3439
3440 //crypt_ftr->keysize = key_length / 8;
3441 return 0;
3442}
3443
3444int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3445 unsigned char* master_key)
3446{
3447 int rc;
3448
3449 unsigned char* intermediate_key = 0;
3450 size_t intermediate_key_size = 0;
3451
3452 if (password == 0 || *password == 0) {
3453 password = DEFAULT_PASSWORD;
3454 }
3455
3456 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3457 &intermediate_key_size);
3458
3459 if (rc) {
3460 SLOGE("Can't calculate intermediate key");
3461 return rc;
3462 }
3463
3464 int N = 1 << ftr->N_factor;
3465 int r = 1 << ftr->r_factor;
3466 int p = 1 << ftr->p_factor;
3467
3468 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3469
3470 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3471 ftr->salt, sizeof(ftr->salt), N, r, p,
3472 scrypted_intermediate_key,
3473 sizeof(scrypted_intermediate_key));
3474
3475 free(intermediate_key);
3476
3477 if (rc) {
3478 SLOGE("Can't scrypt intermediate key");
3479 return rc;
3480 }
3481
3482 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3483 intermediate_key_size);
3484}