blob: 08bcaba40ad4273765d4451c4401212c7c34646f [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}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001224// Only adds parameters if the property is set.
1225static void add_sector_size_param(std::vector<std::string>* extra_params_vec) {
1226 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
1227 char sector_size[PROPERTY_VALUE_MAX];
1228
1229 if (property_get(DM_CRYPT_SECTOR_SIZE, sector_size, "") > 0) {
1230 std::string param = StringPrintf("sector_size:%s", sector_size);
1231 extra_params_vec->push_back(std::move(param));
1232
1233 // With this option, IVs will match the sector numbering, instead
1234 // of being hard-coded to being based on 512-byte sectors.
1235 extra_params_vec->emplace_back("iv_large_sectors");
1236 }
1237}
Steven Laverec1b6bc2019-01-15 11:03:32 -08001238#endif
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001239
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;
Yue Hu9d6cc182018-12-17 17:09:55 +08001369 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001370
Paul Crowley14c8c072018-09-18 13:30:21 -07001371 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1372 SLOGE("Cannot open device-mapper\n");
1373 goto errout;
1374 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001375
Paul Crowley14c8c072018-09-18 13:30:21 -07001376 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001377
Paul Crowley14c8c072018-09-18 13:30:21 -07001378 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Yue Hu9d6cc182018-12-17 17:09:55 +08001379 err = ioctl(fd, DM_DEV_REMOVE, io);
1380 if (err) {
1381 SLOGE("Cannot remove dm-crypt device %s: %s\n", name, strerror(errno));
Paul Crowley14c8c072018-09-18 13:30:21 -07001382 goto errout;
1383 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001384
Paul Crowley14c8c072018-09-18 13:30:21 -07001385 /* We made it here with no errors. Woot! */
1386 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001387
1388errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001389 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 -08001390
Paul Crowley14c8c072018-09-18 13:30:21 -07001391 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001392}
1393
Paul Crowley14c8c072018-09-18 13:30:21 -07001394static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1395 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001396 SLOGI("Using pbkdf2 for cryptfs KDF");
1397
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001398 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001399 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1400 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001401}
1402
Paul Crowley14c8c072018-09-18 13:30:21 -07001403static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001404 SLOGI("Using scrypt for cryptfs KDF");
1405
Paul Crowley14c8c072018-09-18 13:30:21 -07001406 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001407
1408 int N = 1 << ftr->N_factor;
1409 int r = 1 << ftr->r_factor;
1410 int p = 1 << ftr->p_factor;
1411
1412 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001413 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001414 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001415
Paul Crowley14c8c072018-09-18 13:30:21 -07001416 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001417}
1418
Paul Crowley14c8c072018-09-18 13:30:21 -07001419static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1420 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001421 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1422
1423 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001424 size_t signature_size;
1425 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001426 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001427
1428 int N = 1 << ftr->N_factor;
1429 int r = 1 << ftr->r_factor;
1430 int p = 1 << ftr->p_factor;
1431
Paul Crowley14c8c072018-09-18 13:30:21 -07001432 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001433 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001434
1435 if (rc) {
1436 SLOGE("scrypt failed");
1437 return -1;
1438 }
1439
Paul Crowley14c8c072018-09-18 13:30:21 -07001440 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001441 SLOGE("Signing failed");
1442 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001443 }
1444
Paul Crowley14c8c072018-09-18 13:30:21 -07001445 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1446 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001447 free(signature);
1448
1449 if (rc) {
1450 SLOGE("scrypt failed");
1451 return -1;
1452 }
1453
1454 return 0;
1455}
1456
Paul Crowley14c8c072018-09-18 13:30:21 -07001457static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1458 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001459 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1460 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001461 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001462 EVP_CIPHER_CTX e_ctx;
1463 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001464 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001465
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001466 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001467 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001468
1469 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001470 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001471 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001472 SLOGE("keymaster_create_key failed");
1473 return -1;
1474 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001475
Paul Crowley14c8c072018-09-18 13:30:21 -07001476 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1477 SLOGE("scrypt failed");
1478 return -1;
1479 }
1480 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001481
Paul Crowley14c8c072018-09-18 13:30:21 -07001482 case KDF_SCRYPT:
1483 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1484 SLOGE("scrypt failed");
1485 return -1;
1486 }
1487 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001488
Paul Crowley14c8c072018-09-18 13:30:21 -07001489 default:
1490 SLOGE("Invalid kdf_type");
1491 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001492 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001493
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001494 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001495 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001496 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1497 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001498 SLOGE("EVP_EncryptInit failed\n");
1499 return -1;
1500 }
1501 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001502
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001503 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001504 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1505 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001506 SLOGE("EVP_EncryptUpdate failed\n");
1507 return -1;
1508 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001509 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001510 SLOGE("EVP_EncryptFinal failed\n");
1511 return -1;
1512 }
1513
Greg Kaiser59ad0182018-02-16 13:01:36 -08001514 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001515 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1516 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001517 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001518
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001519 /* Store the scrypt of the intermediate key, so we can validate if it's a
1520 password error or mount error when things go wrong.
1521 Note there's no need to check for errors, since if this is incorrect, we
1522 simply won't wipe userdata, which is the correct default behavior
1523 */
1524 int N = 1 << crypt_ftr->N_factor;
1525 int r = 1 << crypt_ftr->r_factor;
1526 int p = 1 << crypt_ftr->p_factor;
1527
Paul Crowley14c8c072018-09-18 13:30:21 -07001528 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1529 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001530 sizeof(crypt_ftr->scrypted_intermediate_key));
1531
1532 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001533 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001534 }
1535
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001536 EVP_CIPHER_CTX_cleanup(&e_ctx);
1537
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001538 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001539}
1540
Paul Crowley14c8c072018-09-18 13:30:21 -07001541static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1542 const unsigned char* encrypted_master_key, size_t keysize,
1543 unsigned char* decrypted_master_key, kdf_func kdf,
1544 void* kdf_params, unsigned char** intermediate_key,
1545 size_t* intermediate_key_size) {
1546 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1547 EVP_CIPHER_CTX d_ctx;
1548 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001549
Paul Crowley14c8c072018-09-18 13:30:21 -07001550 /* Turn the password into an intermediate key and IV that can decrypt the
1551 master key */
1552 if (kdf(passwd, salt, ikey, kdf_params)) {
1553 SLOGE("kdf failed");
1554 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001555 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001556
Paul Crowley14c8c072018-09-18 13:30:21 -07001557 /* Initialize the decryption engine */
1558 EVP_CIPHER_CTX_init(&d_ctx);
1559 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1560 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1561 return -1;
1562 }
1563 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1564 /* Decrypt the master key */
1565 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1566 keysize)) {
1567 return -1;
1568 }
1569 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1570 return -1;
1571 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001572
Paul Crowley14c8c072018-09-18 13:30:21 -07001573 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1574 return -1;
1575 }
1576
1577 /* Copy intermediate key if needed by params */
1578 if (intermediate_key && intermediate_key_size) {
1579 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1580 if (*intermediate_key) {
1581 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1582 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1583 }
1584 }
1585
1586 EVP_CIPHER_CTX_cleanup(&d_ctx);
1587
1588 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001589}
1590
Paul Crowley14c8c072018-09-18 13:30:21 -07001591static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001592 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001593 *kdf = scrypt_keymaster;
1594 *kdf_params = ftr;
1595 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001596 *kdf = scrypt;
1597 *kdf_params = ftr;
1598 } else {
1599 *kdf = pbkdf2;
1600 *kdf_params = NULL;
1601 }
1602}
1603
Paul Crowley14c8c072018-09-18 13:30:21 -07001604static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1605 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1606 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001607 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001608 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001609 int ret;
1610
1611 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001612 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1613 decrypted_master_key, kdf, kdf_params, intermediate_key,
1614 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001615 if (ret != 0) {
1616 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001617 }
1618
1619 return ret;
1620}
1621
Paul Crowley14c8c072018-09-18 13:30:21 -07001622static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1623 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001624 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001625 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001626
1627 /* Get some random bits for a key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001628 fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001629 read(fd, key_buf, sizeof(key_buf));
1630 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001631 close(fd);
1632
1633 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301634 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001635}
1636
Paul Crowley14c8c072018-09-18 13:30:21 -07001637int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001638 int i, err, rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301639#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001640
1641 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001642 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001643 if (umount(mountpoint) == 0) {
1644 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001645 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001646
1647 if (errno == EINVAL) {
1648 /* EINVAL is returned if the directory is not a mountpoint,
1649 * i.e. there is no filesystem mounted there. So just get out.
1650 */
1651 break;
1652 }
1653
1654 err = errno;
1655
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301656 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001657 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301658 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001659 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001660 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301661 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001662 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001663 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001664 }
1665 }
1666
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301667 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001668 }
1669
1670 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001671 SLOGD("unmounting %s succeeded\n", mountpoint);
1672 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001673 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001674 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1675 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1676 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001677 }
1678
1679 return rc;
1680}
1681
Paul Crowley14c8c072018-09-18 13:30:21 -07001682static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001683 // NOTE: post_fs_data results in init calling back around to vold, so all
1684 // callers to this method must be async
1685
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001686 /* Do the prep of the /data filesystem */
1687 property_set("vold.post_fs_data_done", "0");
1688 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001689 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001690
Ken Sumrallc5872692013-05-14 15:26:31 -07001691 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001692 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001693 /* We timed out to prep /data in time. Continue wait. */
1694 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001695 }
Wei Wang42e38102017-06-07 10:46:12 -07001696 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001697}
1698
Paul Crowley14c8c072018-09-18 13:30:21 -07001699static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001700 // Mark the footer as bad
1701 struct crypt_mnt_ftr crypt_ftr;
1702 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1703 SLOGE("Failed to get crypto footer - panic");
1704 return;
1705 }
1706
1707 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1708 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1709 SLOGE("Failed to set crypto footer - panic");
1710 return;
1711 }
1712}
1713
Paul Crowley14c8c072018-09-18 13:30:21 -07001714static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001715 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001716 SLOGE("Failed to mount tmpfs on data - panic");
1717 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001718 }
1719
1720 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1721 SLOGE("Failed to trigger post fs data - panic");
1722 return;
1723 }
1724
1725 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1726 SLOGE("Failed to trigger restart min framework - panic");
1727 return;
1728 }
1729}
1730
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001731/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001732static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001733 char crypto_blkdev[MAXPATHLEN];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301734#ifdef CONFIG_HW_DISK_ENCRYPTION
1735 char blkdev[MAXPATHLEN];
1736#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001737 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001738 static int restart_successful = 0;
1739
1740 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001741 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001742 SLOGE("Encrypted filesystem not validated, aborting");
1743 return -1;
1744 }
1745
1746 if (restart_successful) {
1747 SLOGE("System already restarted with encrypted disk, aborting");
1748 return -1;
1749 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001750
Paul Lawrencef4faa572014-01-29 13:31:03 -08001751 if (restart_main) {
1752 /* Here is where we shut down the framework. The init scripts
1753 * start all services in one of three classes: core, main or late_start.
1754 * On boot, we start core and main. Now, we stop main, but not core,
1755 * as core includes vold and a few other really important things that
1756 * we need to keep running. Once main has stopped, we should be able
1757 * to umount the tmpfs /data, then mount the encrypted /data.
1758 * We then restart the class main, and also the class late_start.
1759 * At the moment, I've only put a few things in late_start that I know
1760 * are not needed to bring up the framework, and that also cause problems
1761 * with unmounting the tmpfs /data, but I hope to add add more services
1762 * to the late_start class as we optimize this to decrease the delay
1763 * till the user is asked for the password to the filesystem.
1764 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001765
Paul Lawrencef4faa572014-01-29 13:31:03 -08001766 /* The init files are setup to stop the class main when vold.decrypt is
1767 * set to trigger_reset_main.
1768 */
1769 property_set("vold.decrypt", "trigger_reset_main");
1770 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001771
Paul Lawrencef4faa572014-01-29 13:31:03 -08001772 /* Ugh, shutting down the framework is not synchronous, so until it
1773 * can be fixed, this horrible hack will wait a moment for it all to
1774 * shut down before proceeding. Without it, some devices cannot
1775 * restart the graphics services.
1776 */
1777 sleep(2);
1778 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001779
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001780 /* Now that the framework is shutdown, we should be able to umount()
1781 * the tmpfs filesystem, and mount the real one.
1782 */
1783
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301784#if defined(CONFIG_HW_DISK_ENCRYPTION)
1785#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1786 if (is_ice_enabled()) {
1787 fs_mgr_get_crypt_info(fstab_default, 0, blkdev, sizeof(blkdev));
1788 if (set_ice_param(START_ENCDEC)) {
1789 SLOGE("Failed to set ICE data");
1790 return -1;
1791 }
1792 }
1793#else
1794 property_get("ro.crypto.fs_crypto_blkdev", blkdev, "");
1795 if (strlen(blkdev) == 0) {
1796 SLOGE("fs_crypto_blkdev not set\n");
1797 return -1;
1798 }
1799 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1800#endif
1801#else
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001802 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1803 if (strlen(crypto_blkdev) == 0) {
1804 SLOGE("fs_crypto_blkdev not set\n");
1805 return -1;
1806 }
1807
Paul Crowley14c8c072018-09-18 13:30:21 -07001808 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301809#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001810 /* If ro.crypto.readonly is set to 1, mount the decrypted
1811 * filesystem readonly. This is used when /data is mounted by
1812 * recovery mode.
1813 */
1814 char ro_prop[PROPERTY_VALUE_MAX];
1815 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001816 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001817 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07001818 if (rec) {
1819 rec->flags |= MS_RDONLY;
1820 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001821 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001822
Ken Sumralle5032c42012-04-01 23:58:44 -07001823 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001824 int retries = RETRY_MOUNT_ATTEMPTS;
1825 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001826
1827 /*
1828 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1829 * partitions in the fsck domain.
1830 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001831 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001832 SLOGE("Failed to setexeccon");
1833 return -1;
1834 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001835 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301836#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001837 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, blkdev, 0,
1838 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301839#else
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001840 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1841 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301842#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001843 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1844 /* TODO: invoke something similar to
1845 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1846 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301847#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001848 SLOGI("Failed to mount %s because it is busy - waiting", blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301849#else
Paul Crowley14c8c072018-09-18 13:30:21 -07001850 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301851#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001852 if (--retries) {
1853 sleep(RETRY_MOUNT_DELAY_SECONDS);
1854 } else {
1855 /* Let's hope that a reboot clears away whatever is keeping
1856 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001857 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001858 }
1859 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301860#ifdef CONFIG_HW_DISK_ENCRYPTION
1861 if (--retries) {
1862 sleep(RETRY_MOUNT_DELAY_SECONDS);
1863 } else {
1864 SLOGE("Failed to mount decrypted data");
1865 cryptfs_set_corrupt();
1866 cryptfs_trigger_restart_min_framework();
1867 SLOGI("Started framework to offer wipe");
1868 return -1;
1869 }
1870#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001871 SLOGE("Failed to mount decrypted data");
1872 cryptfs_set_corrupt();
1873 cryptfs_trigger_restart_min_framework();
1874 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001875 if (setexeccon(NULL)) {
1876 SLOGE("Failed to setexeccon");
1877 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001878 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301879#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001880 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001881 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001882 if (setexeccon(NULL)) {
1883 SLOGE("Failed to setexeccon");
1884 return -1;
1885 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001886
Ken Sumralle5032c42012-04-01 23:58:44 -07001887 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001888 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001889 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001890
1891 /* startup service classes main and late_start */
1892 property_set("vold.decrypt", "trigger_restart_framework");
1893 SLOGD("Just triggered restart_framework\n");
1894
1895 /* Give it a few moments to get started */
1896 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301897#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001898 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301899#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001900
Ken Sumrall0cc16632011-01-18 20:32:26 -08001901 if (rc == 0) {
1902 restart_successful = 1;
1903 }
1904
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001905 return rc;
1906}
1907
Paul Crowley14c8c072018-09-18 13:30:21 -07001908int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001909 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001910 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001911 SLOGE("cryptfs_restart not valid for file encryption:");
1912 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001913 }
1914
Paul Lawrencef4faa572014-01-29 13:31:03 -08001915 /* Call internal implementation forcing a restart of main service group */
1916 return cryptfs_restart_internal(1);
1917}
1918
Paul Crowley14c8c072018-09-18 13:30:21 -07001919static int do_crypto_complete(const char* mount_point) {
1920 struct crypt_mnt_ftr crypt_ftr;
1921 char encrypted_state[PROPERTY_VALUE_MAX];
1922 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001923
Paul Crowley14c8c072018-09-18 13:30:21 -07001924 property_get("ro.crypto.state", encrypted_state, "");
1925 if (strcmp(encrypted_state, "encrypted")) {
1926 SLOGE("not running with encryption, aborting");
1927 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001928 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001929
Paul Crowley14c8c072018-09-18 13:30:21 -07001930 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001931 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001932 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1933 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001934
Paul Crowley14c8c072018-09-18 13:30:21 -07001935 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1936 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001937
Paul Crowley14c8c072018-09-18 13:30:21 -07001938 /*
1939 * Only report this error if key_loc is a file and it exists.
1940 * If the device was never encrypted, and /data is not mountable for
1941 * some reason, returning 1 should prevent the UI from presenting the
1942 * a "enter password" screen, or worse, a "press button to wipe the
1943 * device" screen.
1944 */
1945 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1946 SLOGE("master key file does not exist, aborting");
1947 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1948 } else {
1949 SLOGE("Error getting crypt footer and key\n");
1950 return CRYPTO_COMPLETE_BAD_METADATA;
1951 }
1952 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001953
Paul Crowley14c8c072018-09-18 13:30:21 -07001954 // Test for possible error flags
1955 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1956 SLOGE("Encryption process is partway completed\n");
1957 return CRYPTO_COMPLETE_PARTIAL;
1958 }
1959
1960 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1961 SLOGE("Encryption process was interrupted but cannot continue\n");
1962 return CRYPTO_COMPLETE_INCONSISTENT;
1963 }
1964
1965 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1966 SLOGE("Encryption is successful but data is corrupt\n");
1967 return CRYPTO_COMPLETE_CORRUPT;
1968 }
1969
1970 /* We passed the test! We shall diminish, and return to the west */
1971 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001972}
1973
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301974#ifdef CONFIG_HW_DISK_ENCRYPTION
1975static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1976 const char *passwd, const char *mount_point, const char *label)
1977{
Bill Peckham0db11972018-10-10 10:25:42 -07001978 /* Allocate enough space for a 256 bit key, but we may use less */
1979 unsigned char decrypted_master_key[32];
1980 char crypto_blkdev[MAXPATHLEN];
1981 char real_blkdev[MAXPATHLEN];
1982 unsigned int orig_failed_decrypt_count;
1983 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301984
Bill Peckham0db11972018-10-10 10:25:42 -07001985 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1986 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301987
Bill Peckham0db11972018-10-10 10:25:42 -07001988 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301989
Bill Peckham0db11972018-10-10 10:25:42 -07001990 int key_index = 0;
1991 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1992 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
1993 if (key_index < 0) {
1994 rc = crypt_ftr->failed_decrypt_count;
1995 goto errout;
1996 }
1997 else {
1998 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301999#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07002000 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
2001 real_blkdev, crypto_blkdev, label, 0)) {
2002 SLOGE("Error creating decrypted block device");
2003 rc = -1;
2004 goto errout;
2005 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302006#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002007 } else {
2008 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
2009 real_blkdev, crypto_blkdev, label, 0)) {
2010 SLOGE("Error creating decrypted block device");
2011 rc = -1;
2012 goto errout;
2013 }
2014 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302015 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302016 }
2017
Bill Peckham0db11972018-10-10 10:25:42 -07002018 if (rc == 0) {
2019 crypt_ftr->failed_decrypt_count = 0;
2020 if (orig_failed_decrypt_count != 0) {
2021 put_crypt_ftr_and_key(crypt_ftr);
2022 }
2023
2024 /* Save the name of the crypto block device
2025 * so we can mount it when restarting the framework. */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302026#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07002027 if (!is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302028#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002029 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2030 master_key_saved = 1;
2031 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302032
Bill Peckham0db11972018-10-10 10:25:42 -07002033 errout:
2034 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302035}
2036#endif
2037
Paul Crowley14c8c072018-09-18 13:30:21 -07002038static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2039 const char* mount_point, const char* label) {
2040 unsigned char decrypted_master_key[MAX_KEY_LEN];
2041 char crypto_blkdev[MAXPATHLEN];
2042 char real_blkdev[MAXPATHLEN];
2043 char tmp_mount_point[64];
2044 unsigned int orig_failed_decrypt_count;
2045 int rc;
2046 int use_keymaster = 0;
2047 int upgrade = 0;
2048 unsigned char* intermediate_key = 0;
2049 size_t intermediate_key_size = 0;
2050 int N = 1 << crypt_ftr->N_factor;
2051 int r = 1 << crypt_ftr->r_factor;
2052 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302053
Paul Crowley14c8c072018-09-18 13:30:21 -07002054 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2055 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002056
Paul Crowley14c8c072018-09-18 13:30:21 -07002057 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2058 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2059 &intermediate_key_size)) {
2060 SLOGE("Failed to decrypt master key\n");
2061 rc = -1;
2062 goto errout;
2063 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002064 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002065
Paul Crowley14c8c072018-09-18 13:30:21 -07002066 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08002067
Paul Crowley14c8c072018-09-18 13:30:21 -07002068 // Create crypto block device - all (non fatal) code paths
2069 // need it
2070 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
2071 0)) {
2072 SLOGE("Error creating decrypted block device\n");
2073 rc = -1;
2074 goto errout;
2075 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002076
Paul Crowley14c8c072018-09-18 13:30:21 -07002077 /* Work out if the problem is the password or the data */
2078 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002079
Paul Crowley14c8c072018-09-18 13:30:21 -07002080 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2081 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2082 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002083
Paul Crowley14c8c072018-09-18 13:30:21 -07002084 // Does the key match the crypto footer?
2085 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2086 sizeof(scrypted_intermediate_key)) == 0) {
2087 SLOGI("Password matches");
2088 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002089 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002090 /* Try mounting the file system anyway, just in case the problem's with
2091 * the footer, not the key. */
2092 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2093 mkdir(tmp_mount_point, 0755);
2094 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
2095 SLOGE("Error temp mounting decrypted block device\n");
2096 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002097
Paul Crowley14c8c072018-09-18 13:30:21 -07002098 rc = ++crypt_ftr->failed_decrypt_count;
2099 put_crypt_ftr_and_key(crypt_ftr);
2100 } else {
2101 /* Success! */
2102 SLOGI("Password did not match but decrypted drive mounted - continue");
2103 umount(tmp_mount_point);
2104 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002105 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002106 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002107
Paul Crowley14c8c072018-09-18 13:30:21 -07002108 if (rc == 0) {
2109 crypt_ftr->failed_decrypt_count = 0;
2110 if (orig_failed_decrypt_count != 0) {
2111 put_crypt_ftr_and_key(crypt_ftr);
2112 }
2113
2114 /* Save the name of the crypto block device
2115 * so we can mount it when restarting the framework. */
2116 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2117
2118 /* Also save a the master key so we can reencrypted the key
2119 * the key when we want to change the password on it. */
2120 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2121 saved_mount_point = strdup(mount_point);
2122 master_key_saved = 1;
2123 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2124 rc = 0;
2125
2126 // Upgrade if we're not using the latest KDF.
2127 use_keymaster = keymaster_check_compatibility();
2128 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2129 // Don't allow downgrade
2130 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2131 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2132 upgrade = 1;
2133 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2134 crypt_ftr->kdf_type = KDF_SCRYPT;
2135 upgrade = 1;
2136 }
2137
2138 if (upgrade) {
2139 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002140 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002141 if (!rc) {
2142 rc = put_crypt_ftr_and_key(crypt_ftr);
2143 }
2144 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2145
2146 // Do not fail even if upgrade failed - machine is bootable
2147 // Note that if this code is ever hit, there is a *serious* problem
2148 // since KDFs should never fail. You *must* fix the kdf before
2149 // proceeding!
2150 if (rc) {
2151 SLOGW(
2152 "Upgrade failed with error %d,"
2153 " but continuing with previous state",
2154 rc);
2155 rc = 0;
2156 }
2157 }
2158 }
2159
2160errout:
2161 if (intermediate_key) {
2162 memset(intermediate_key, 0, intermediate_key_size);
2163 free(intermediate_key);
2164 }
2165 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002166}
2167
Ken Sumrall29d8da82011-05-18 17:20:07 -07002168/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002169 * Called by vold when it's asked to mount an encrypted external
2170 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002171 * as any metadata is been stored in a separate, small partition. We
2172 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07002173 *
2174 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002175 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002176int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
2177 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002178 uint64_t nr_sec = 0;
2179 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002180 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002181 return -1;
2182 }
2183
Jeff Sharkey9c484982015-03-31 10:35:33 -07002184 struct crypt_mnt_ftr ext_crypt_ftr;
2185 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2186 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002187 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07002188 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002189 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002190 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002191 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002192 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2193 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002194
Paul Crowley385cb8c2018-03-29 13:27:23 -07002195 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07002196}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002197
Jeff Sharkey9c484982015-03-31 10:35:33 -07002198/*
2199 * Called by vold when it's asked to unmount an encrypted external
2200 * storage volume.
2201 */
2202int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002203 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002204}
2205
Paul Crowley14c8c072018-09-18 13:30:21 -07002206int cryptfs_crypto_complete(void) {
2207 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002208}
2209
Paul Crowley14c8c072018-09-18 13:30:21 -07002210int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002211 char encrypted_state[PROPERTY_VALUE_MAX];
2212 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002213 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2214 SLOGE(
2215 "encrypted fs already validated or not running with encryption,"
2216 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002217 return -1;
2218 }
2219
2220 if (get_crypt_ftr_and_key(crypt_ftr)) {
2221 SLOGE("Error getting crypt footer and key");
2222 return -1;
2223 }
2224
2225 return 0;
2226}
2227
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302228#ifdef CONFIG_HW_DISK_ENCRYPTION
2229int cryptfs_check_passwd_hw(const char* passwd)
2230{
2231 struct crypt_mnt_ftr crypt_ftr;
2232 int rc;
2233 unsigned char master_key[KEY_LEN_BYTES];
2234
2235 /* get key */
2236 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2237 SLOGE("Error getting crypt footer and key");
2238 return -1;
2239 }
2240
2241 /*
2242 * in case of manual encryption (from GUI), the encryption is done with
2243 * default password
2244 */
2245 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2246 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2247 * which was created with actual password before reboot.
2248 */
2249 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2250 if (rc) {
2251 SLOGE("password doesn't match");
2252 rc = ++crypt_ftr.failed_decrypt_count;
2253 put_crypt_ftr_and_key(&crypt_ftr);
2254 return rc;
2255 }
2256
2257 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2258 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2259
2260 if (rc) {
2261 SLOGE("Default password did not match on reboot encryption");
2262 return rc;
2263 }
2264
2265 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2266 put_crypt_ftr_and_key(&crypt_ftr);
2267 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2268 if (rc) {
2269 SLOGE("Could not change password on reboot encryption");
2270 return rc;
2271 }
2272 } else
2273 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2274 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2275
2276 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2277 cryptfs_clear_password();
2278 password = strdup(passwd);
2279 struct timespec now;
2280 clock_gettime(CLOCK_BOOTTIME, &now);
2281 password_expiry_time = now.tv_sec + password_max_age_seconds;
2282 }
2283
2284 return rc;
2285}
2286#endif
2287
Paul Crowley14c8c072018-09-18 13:30:21 -07002288int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002289 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002290 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002291 SLOGE("cryptfs_check_passwd not valid for file encryption");
2292 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002293 }
2294
Paul Lawrencef4faa572014-01-29 13:31:03 -08002295 struct crypt_mnt_ftr crypt_ftr;
2296 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002297
Paul Lawrencef4faa572014-01-29 13:31:03 -08002298 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002299 if (rc) {
2300 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002301 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002302 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002303
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302304#ifdef CONFIG_HW_DISK_ENCRYPTION
2305 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2306 return cryptfs_check_passwd_hw(passwd);
2307#endif
2308
Paul Crowley14c8c072018-09-18 13:30:21 -07002309 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002310 if (rc) {
2311 SLOGE("Password did not match");
2312 return rc;
2313 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002314
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002315 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2316 // Here we have a default actual password but a real password
2317 // we must test against the scrypted value
2318 // First, we must delete the crypto block device that
2319 // test_mount_encrypted_fs leaves behind as a side effect
2320 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002321 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2322 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002323 if (rc) {
2324 SLOGE("Default password did not match on reboot encryption");
2325 return rc;
2326 }
2327
2328 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2329 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302330 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002331 if (rc) {
2332 SLOGE("Could not change password on reboot encryption");
2333 return rc;
2334 }
2335 }
2336
2337 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002338 cryptfs_clear_password();
2339 password = strdup(passwd);
2340 struct timespec now;
2341 clock_gettime(CLOCK_BOOTTIME, &now);
2342 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002343 }
2344
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002345 return rc;
2346}
2347
Paul Crowley14c8c072018-09-18 13:30:21 -07002348int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002349 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002350 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002351 char encrypted_state[PROPERTY_VALUE_MAX];
2352 int rc;
2353
2354 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002355 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002356 SLOGE("device not encrypted, aborting");
2357 return -2;
2358 }
2359
2360 if (!master_key_saved) {
2361 SLOGE("encrypted fs not yet mounted, aborting");
2362 return -1;
2363 }
2364
2365 if (!saved_mount_point) {
2366 SLOGE("encrypted fs failed to save mount point, aborting");
2367 return -1;
2368 }
2369
Ken Sumrall160b4d62013-04-22 12:15:39 -07002370 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002371 SLOGE("Error getting crypt footer and key\n");
2372 return -1;
2373 }
2374
2375 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2376 /* If the device has no password, then just say the password is valid */
2377 rc = 0;
2378 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302379#ifdef CONFIG_HW_DISK_ENCRYPTION
2380 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2381 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2382 rc = 0;
2383 else
2384 rc = -1;
2385 } else {
2386 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2387 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2388 /* They match, the password is correct */
2389 rc = 0;
2390 } else {
2391 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2392 sleep(1);
2393 rc = 1;
2394 }
2395 }
2396#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002397 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002398 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2399 /* They match, the password is correct */
2400 rc = 0;
2401 } else {
2402 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2403 sleep(1);
2404 rc = 1;
2405 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302406#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002407 }
2408
2409 return rc;
2410}
2411
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002412/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002413 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002414 * Presumably, at a minimum, the caller will update the
2415 * filesystem size and crypto_type_name after calling this function.
2416 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002417static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002418 off64_t off;
2419
2420 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002421 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002422 ftr->major_version = CURRENT_MAJOR_VERSION;
2423 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002424 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002425 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002426
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002427 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002428 case 1:
2429 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2430 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002431
Paul Crowley14c8c072018-09-18 13:30:21 -07002432 case 0:
2433 ftr->kdf_type = KDF_SCRYPT;
2434 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002435
Paul Crowley14c8c072018-09-18 13:30:21 -07002436 default:
2437 SLOGE("keymaster_check_compatibility failed");
2438 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002439 }
2440
Kenny Rootc4c70f12013-06-14 12:11:38 -07002441 get_device_scrypt_params(ftr);
2442
Ken Sumrall160b4d62013-04-22 12:15:39 -07002443 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2444 if (get_crypt_ftr_info(NULL, &off) == 0) {
2445 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002446 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002447 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002448
2449 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002450}
2451
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002452#define FRAMEWORK_BOOT_WAIT 60
2453
Paul Crowley14c8c072018-09-18 13:30:21 -07002454static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2455 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002456 if (fd == -1) {
2457 SLOGE("Error opening file %s", filename);
2458 return -1;
2459 }
2460
2461 char block[CRYPT_INPLACE_BUFSIZE];
2462 memset(block, 0, sizeof(block));
2463 if (unix_read(fd, block, sizeof(block)) < 0) {
2464 SLOGE("Error reading file %s", filename);
2465 close(fd);
2466 return -1;
2467 }
2468
2469 close(fd);
2470
2471 SHA256_CTX c;
2472 SHA256_Init(&c);
2473 SHA256_Update(&c, block, sizeof(block));
2474 SHA256_Final(buf, &c);
2475
2476 return 0;
2477}
2478
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002479static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2480 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002481 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002482 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002483
Paul Lawrence87999172014-02-20 12:21:31 -08002484 /* The size of the userdata partition, and add in the vold volumes below */
2485 tot_encryption_size = crypt_ftr->fs_size;
2486
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002487 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002488 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002489
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002490 if (rc == ENABLE_INPLACE_ERR_DEV) {
2491 /* Hack for b/17898962 */
2492 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2493 cryptfs_reboot(RebootType::reboot);
2494 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002495
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002496 if (!rc) {
2497 crypt_ftr->encrypted_upto = cur_encryption_done;
2498 }
Paul Lawrence87999172014-02-20 12:21:31 -08002499
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002500 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2501 /* The inplace routine never actually sets the progress to 100% due
2502 * to the round down nature of integer division, so set it here */
2503 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002504 }
2505
2506 return rc;
2507}
2508
Paul Crowleyb64933a2017-10-31 08:25:55 -07002509static int vold_unmountAll(void) {
2510 VolumeManager* vm = VolumeManager::Instance();
2511 return vm->unmountAll();
2512}
2513
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002514int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002515 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002516 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002517 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002518 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002519 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002520 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002521 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002522 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002523 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002524 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002525 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002526 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302527#ifdef CONFIG_HW_DISK_ENCRYPTION
2528 unsigned char newpw[32];
2529 int key_index = 0;
2530#endif
2531 int index = 0;
2532
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002533 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002534 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2535 /* An encryption was underway and was interrupted */
2536 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2537 crypt_ftr.encrypted_upto = 0;
2538 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002539
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002540 /* At this point, we are in an inconsistent state. Until we successfully
2541 complete encryption, a reboot will leave us broken. So mark the
2542 encryption failed in case that happens.
2543 On successfully completing encryption, remove this flag */
2544 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002545
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002546 put_crypt_ftr_and_key(&crypt_ftr);
2547 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2548 if (!check_ftr_sha(&crypt_ftr)) {
2549 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2550 put_crypt_ftr_and_key(&crypt_ftr);
2551 goto error_unencrypted;
2552 }
2553
2554 /* Doing a reboot-encryption*/
2555 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2556 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2557 rebootEncryption = true;
2558 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002559 } else {
2560 // We don't want to accidentally reference invalid data.
2561 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002562 }
2563
2564 property_get("ro.crypto.state", encrypted_state, "");
2565 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2566 SLOGE("Device is already running encrypted, aborting");
2567 goto error_unencrypted;
2568 }
2569
2570 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002571 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2572 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002573
Ken Sumrall3ed82362011-01-28 23:31:16 -08002574 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002575 uint64_t nr_sec;
2576 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002577 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2578 goto error_unencrypted;
2579 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002580
2581 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002582 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002583 uint64_t fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002584 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002585 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002586
Paul Lawrence87999172014-02-20 12:21:31 -08002587 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002588
2589 if (fs_size_sec > max_fs_size_sec) {
2590 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2591 goto error_unencrypted;
2592 }
2593 }
2594
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002595 /* Get a wakelock as this may take a while, and we don't want the
2596 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2597 * wants to keep the screen on, it can grab a full wakelock.
2598 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002599 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002600 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2601
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002602 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002603 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002604 */
2605 property_set("vold.decrypt", "trigger_shutdown_framework");
2606 SLOGD("Just asked init to shut down class main\n");
2607
Jeff Sharkey9c484982015-03-31 10:35:33 -07002608 /* Ask vold to unmount all devices that it manages */
2609 if (vold_unmountAll()) {
2610 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002611 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002612
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002613 /* no_ui means we are being called from init, not settings.
2614 Now we always reboot from settings, so !no_ui means reboot
2615 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002616 if (!no_ui) {
2617 /* Try fallback, which is to reboot and try there */
2618 onlyCreateHeader = true;
2619 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2620 if (breadcrumb == 0) {
2621 SLOGE("Failed to create breadcrumb file");
2622 goto error_shutting_down;
2623 }
2624 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002625 }
2626
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002627 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002628 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002629 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002630 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2631 goto error_shutting_down;
2632 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002633
Paul Lawrence87999172014-02-20 12:21:31 -08002634 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002635 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002636 } else {
2637 crypt_ftr.fs_size = nr_sec;
2638 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002639 /* At this point, we are in an inconsistent state. Until we successfully
2640 complete encryption, a reboot will leave us broken. So mark the
2641 encryption failed in case that happens.
2642 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002643 if (onlyCreateHeader) {
2644 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2645 } else {
2646 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2647 }
Paul Lawrence87999172014-02-20 12:21:31 -08002648 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302649#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002650 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2651 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302652#else
Paul Crowley14c8c072018-09-18 13:30:21 -07002653 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2654 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302655#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002656
Paul Lawrence87999172014-02-20 12:21:31 -08002657 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002658 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2659 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002660 SLOGE("Cannot create encrypted master key\n");
2661 goto error_shutting_down;
2662 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002663
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002664 /* Replace scrypted intermediate key if we are preparing for a reboot */
2665 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002666 unsigned char fake_master_key[MAX_KEY_LEN];
2667 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002668 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002669 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002670 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002671 }
2672
Paul Lawrence87999172014-02-20 12:21:31 -08002673 /* Write the key to the end of the partition */
2674 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002675
Paul Lawrence87999172014-02-20 12:21:31 -08002676 /* If any persistent data has been remembered, save it.
2677 * If none, create a valid empty table and save that.
2678 */
2679 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002680 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2681 if (pdata) {
2682 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2683 persist_data = pdata;
2684 }
Paul Lawrence87999172014-02-20 12:21:31 -08002685 }
2686 if (persist_data) {
2687 save_persistent_data();
2688 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002689 }
2690
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302691 /* When encryption triggered from settings, encryption starts after reboot.
2692 So set the encryption key when the actual encryption starts.
2693 */
2694#ifdef CONFIG_HW_DISK_ENCRYPTION
2695 if (previously_encrypted_upto == 0) {
2696 if (!rebootEncryption)
2697 clear_hw_device_encryption_key();
2698
2699 if (get_keymaster_hw_fde_passwd(
2700 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2701 newpw, crypt_ftr.salt, &crypt_ftr))
2702 key_index = set_hw_device_encryption_key(
2703 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2704 (char*)crypt_ftr.crypto_type_name);
2705 else
2706 key_index = set_hw_device_encryption_key((const char*)newpw,
2707 (char*) crypt_ftr.crypto_type_name);
2708 if (key_index < 0)
2709 goto error_shutting_down;
2710
2711 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2712 put_crypt_ftr_and_key(&crypt_ftr);
2713 }
2714#endif
2715
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002716 if (onlyCreateHeader) {
2717 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002718 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302719 } else {
2720 /* Do extra work for a better UX when doing the long inplace encryption */
2721 /* Now that /data is unmounted, we need to mount a tmpfs
2722 * /data, set a property saying we're doing inplace encryption,
2723 * and restart the framework.
2724 */
2725 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2726 goto error_shutting_down;
2727 }
2728 /* Tells the framework that inplace encryption is starting */
2729 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002730
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302731 /* restart the framework. */
2732 /* Create necessary paths on /data */
2733 prep_data_fs();
2734
2735 /* Ugh, shutting down the framework is not synchronous, so until it
2736 * can be fixed, this horrible hack will wait a moment for it all to
2737 * shut down before proceeding. Without it, some devices cannot
2738 * restart the graphics services.
2739 */
2740 sleep(2);
2741
Ajay Dudani87701e22014-09-17 21:02:52 -07002742 /* startup service classes main and late_start */
2743 property_set("vold.decrypt", "trigger_restart_min_framework");
2744 SLOGD("Just triggered restart_min_framework\n");
2745
2746 /* OK, the framework is restarted and will soon be showing a
2747 * progress bar. Time to setup an encrypted mapping, and
2748 * either write a new filesystem, or encrypt in place updating
2749 * the progress bar as we work.
2750 */
2751 }
2752
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002753 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302754#ifdef CONFIG_HW_DISK_ENCRYPTION
2755 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302756#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2757 strlcpy(crypto_blkdev, real_blkdev, sizeof(crypto_blkdev));
2758#else
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302759 create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev, crypto_blkdev,
2760 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302761#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302762 else
2763 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2764 CRYPTO_BLOCK_DEVICE, 0);
2765#else
Ken Sumrall29d8da82011-05-18 17:20:07 -07002766 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002767 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302768#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002769
Paul Lawrence87999172014-02-20 12:21:31 -08002770 /* If we are continuing, check checksums match */
2771 rc = 0;
2772 if (previously_encrypted_upto) {
2773 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302774#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2775 if (set_ice_param(START_ENCDEC)) {
2776 SLOGE("Failed to set ICE data");
2777 goto error_shutting_down;
2778 }
2779#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002780 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002781
Paul Crowley14c8c072018-09-18 13:30:21 -07002782 if (!rc &&
2783 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002784 SLOGE("Checksums do not match - trigger wipe");
2785 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002786 }
2787 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002788
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302789#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2790 if (set_ice_param(START_ENC)) {
2791 SLOGE("Failed to set ICE data");
2792 goto error_shutting_down;
2793 }
2794#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002795 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002796 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002797 previously_encrypted_upto);
2798 }
2799
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302800#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2801 if (set_ice_param(START_ENCDEC)) {
2802 SLOGE("Failed to set ICE data");
2803 goto error_shutting_down;
2804 }
2805#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002806 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002807 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002808 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002809 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002810 SLOGE("Error calculating checksum for continuing encryption");
2811 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002812 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002813 }
2814
2815 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302816#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2817 if (!is_ice_enabled())
2818 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2819#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002820 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302821#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002822
Paul Crowley14c8c072018-09-18 13:30:21 -07002823 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002824 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002825 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002826
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002827 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002828 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2829 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002830 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002831 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002832
Paul Lawrence6bfed202014-07-28 12:47:22 -07002833 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002834
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002835 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2836 char value[PROPERTY_VALUE_MAX];
2837 property_get("ro.crypto.state", value, "");
2838 if (!strcmp(value, "")) {
2839 /* default encryption - continue first boot sequence */
2840 property_set("ro.crypto.state", "encrypted");
2841 property_set("ro.crypto.type", "block");
2842 release_wake_lock(lockid);
2843 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2844 // Bring up cryptkeeper that will check the password and set it
2845 property_set("vold.decrypt", "trigger_shutdown_framework");
2846 sleep(2);
2847 property_set("vold.encrypt_progress", "");
2848 cryptfs_trigger_restart_min_framework();
2849 } else {
2850 cryptfs_check_passwd(DEFAULT_PASSWORD);
2851 cryptfs_restart_internal(1);
2852 }
2853 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002854 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002855 sleep(2); /* Give the UI a chance to show 100% progress */
2856 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002857 }
Paul Lawrence87999172014-02-20 12:21:31 -08002858 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002859 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002860 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002861 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002862 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002863 char value[PROPERTY_VALUE_MAX];
2864
Ken Sumrall319369a2012-06-27 16:30:18 -07002865 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002866 if (!strcmp(value, "1")) {
2867 /* wipe data if encryption failed */
2868 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002869 std::string err;
2870 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002871 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002872 if (!write_bootloader_message(options, &err)) {
2873 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002874 }
Josh Gaofec44372017-08-28 13:22:55 -07002875 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002876 } else {
2877 /* set property to trigger dialog */
2878 property_set("vold.encrypt_progress", "error_partially_encrypted");
2879 release_wake_lock(lockid);
2880 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002881 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002882 }
2883
Ken Sumrall3ed82362011-01-28 23:31:16 -08002884 /* hrm, the encrypt step claims success, but the reboot failed.
2885 * This should not happen.
2886 * Set the property and return. Hope the framework can deal with it.
2887 */
2888 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002889 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002890 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002891
2892error_unencrypted:
2893 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002894 if (lockid[0]) {
2895 release_wake_lock(lockid);
2896 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002897 return -1;
2898
2899error_shutting_down:
2900 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2901 * but the framework is stopped and not restarted to show the error, so it's up to
2902 * vold to restart the system.
2903 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002904 SLOGE(
2905 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2906 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002907 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002908
2909 /* shouldn't get here */
2910 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002911 if (lockid[0]) {
2912 release_wake_lock(lockid);
2913 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002914 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002915}
2916
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002917int cryptfs_enable(int type, const char* passwd, int no_ui) {
2918 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002919}
2920
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002921int cryptfs_enable_default(int no_ui) {
2922 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002923}
2924
Bill Peckham0db11972018-10-10 10:25:42 -07002925int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002926 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002927 SLOGE("cryptfs_changepw not valid for file encryption");
2928 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002929 }
2930
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002931 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002932 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002933
2934 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002935 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002936 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002937 return -1;
2938 }
2939
Paul Lawrencef4faa572014-01-29 13:31:03 -08002940 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2941 SLOGE("Invalid crypt_type %d", crypt_type);
2942 return -1;
2943 }
2944
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002945 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002946 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002947 SLOGE("Error getting crypt footer and key");
2948 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002949 }
2950
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302951#ifdef CONFIG_HW_DISK_ENCRYPTION
2952 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2953 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
2954 else {
2955 crypt_ftr.crypt_type = crypt_type;
2956
2957 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
2958 DEFAULT_PASSWORD : newpw,
2959 crypt_ftr.salt,
2960 saved_master_key,
2961 crypt_ftr.master_key,
2962 &crypt_ftr, false);
2963 if (rc) {
2964 SLOGE("Encrypt master key failed: %d", rc);
2965 return -1;
2966 }
2967 /* save the key */
2968 put_crypt_ftr_and_key(&crypt_ftr);
2969
2970 return 0;
2971 }
2972#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08002973 crypt_ftr.crypt_type = crypt_type;
2974
Paul Crowley14c8c072018-09-18 13:30:21 -07002975 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07002976 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
2977 false);
JP Abgrall933216c2015-02-11 13:44:32 -08002978 if (rc) {
2979 SLOGE("Encrypt master key failed: %d", rc);
2980 return -1;
2981 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002982 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002983 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002984
2985 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302986#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002987}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002988
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302989#ifdef CONFIG_HW_DISK_ENCRYPTION
2990int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
2991{
2992 struct crypt_mnt_ftr crypt_ftr;
2993 int rc;
2994 int previous_type;
2995
2996 /* get key */
2997 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2998 SLOGE("Error getting crypt footer and key");
2999 return -1;
3000 }
3001
3002 previous_type = crypt_ftr.crypt_type;
3003 int rc1;
3004 unsigned char tmp_curpw[32] = {0};
3005 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3006 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3007 crypt_ftr.salt, &crypt_ftr);
3008
3009 crypt_ftr.crypt_type = crypt_type;
3010
3011 int ret, rc2;
3012 unsigned char tmp_newpw[32] = {0};
3013
3014 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3015 DEFAULT_PASSWORD : newpw , tmp_newpw,
3016 crypt_ftr.salt, &crypt_ftr);
3017
3018 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3019 ret = update_hw_device_encryption_key(
3020 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3021 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3022 (char*)crypt_ftr.crypto_type_name);
3023 if (ret) {
3024 SLOGE("Error updating device encryption hardware key ret %d", ret);
3025 return -1;
3026 } else {
3027 SLOGI("Encryption hardware key updated");
3028 }
3029 }
3030
3031 /* save the key */
3032 put_crypt_ftr_and_key(&crypt_ftr);
3033 return 0;
3034}
3035#endif
3036
Rubin Xu85c01f92014-10-13 12:49:54 +01003037static unsigned int persist_get_max_entries(int encrypted) {
3038 struct crypt_mnt_ftr crypt_ftr;
3039 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003040
3041 /* If encrypted, use the values from the crypt_ftr, otherwise
3042 * use the values for the current spec.
3043 */
3044 if (encrypted) {
3045 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01003046 /* Something is wrong, assume no space for entries */
3047 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003048 }
3049 dsize = crypt_ftr.persist_data_size;
3050 } else {
3051 dsize = CRYPT_PERSIST_DATA_SIZE;
3052 }
3053
Rubin Xud78181b2018-10-09 16:13:38 +01003054 if (dsize > sizeof(struct crypt_persist_data)) {
3055 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3056 } else {
3057 return 0;
3058 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003059}
3060
Paul Crowley14c8c072018-09-18 13:30:21 -07003061static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003062 unsigned int i;
3063
3064 if (persist_data == NULL) {
3065 return -1;
3066 }
3067 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3068 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3069 /* We found it! */
3070 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3071 return 0;
3072 }
3073 }
3074
3075 return -1;
3076}
3077
Paul Crowley14c8c072018-09-18 13:30:21 -07003078static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003079 unsigned int i;
3080 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003081 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003082
3083 if (persist_data == NULL) {
3084 return -1;
3085 }
3086
Rubin Xu85c01f92014-10-13 12:49:54 +01003087 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003088
3089 num = persist_data->persist_valid_entries;
3090
3091 for (i = 0; i < num; i++) {
3092 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3093 /* We found an existing entry, update it! */
3094 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3095 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3096 return 0;
3097 }
3098 }
3099
3100 /* We didn't find it, add it to the end, if there is room */
3101 if (persist_data->persist_valid_entries < max_persistent_entries) {
3102 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3103 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3104 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3105 persist_data->persist_valid_entries++;
3106 return 0;
3107 }
3108
3109 return -1;
3110}
3111
Rubin Xu85c01f92014-10-13 12:49:54 +01003112/**
3113 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3114 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3115 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003116int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003117 std::string key_ = key;
3118 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003119
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003120 std::string parsed_field;
3121 unsigned parsed_index;
3122
3123 std::string::size_type split = key_.find_last_of('_');
3124 if (split == std::string::npos) {
3125 parsed_field = key_;
3126 parsed_index = 0;
3127 } else {
3128 parsed_field = key_.substr(0, split);
3129 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003130 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003131
3132 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003133}
3134
3135/*
3136 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3137 * remaining entries starting from index will be deleted.
3138 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3139 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3140 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3141 *
3142 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003143static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003144 unsigned int i;
3145 unsigned int j;
3146 unsigned int num;
3147
3148 if (persist_data == NULL) {
3149 return PERSIST_DEL_KEY_ERROR_OTHER;
3150 }
3151
3152 num = persist_data->persist_valid_entries;
3153
Paul Crowley14c8c072018-09-18 13:30:21 -07003154 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003155 // Filter out to-be-deleted entries in place.
3156 for (i = 0; i < num; i++) {
3157 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3158 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3159 j++;
3160 }
3161 }
3162
3163 if (j < num) {
3164 persist_data->persist_valid_entries = j;
3165 // Zeroise the remaining entries
3166 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3167 return PERSIST_DEL_KEY_OK;
3168 } else {
3169 // Did not find an entry matching the given fieldname
3170 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3171 }
3172}
3173
Paul Crowley14c8c072018-09-18 13:30:21 -07003174static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003175 unsigned int i;
3176 unsigned int count;
3177
3178 if (persist_data == NULL) {
3179 return -1;
3180 }
3181
3182 count = 0;
3183 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3184 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3185 count++;
3186 }
3187 }
3188
3189 return count;
3190}
3191
Ken Sumrall160b4d62013-04-22 12:15:39 -07003192/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003193int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003194 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003195 SLOGE("Cannot get field when file encrypted");
3196 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003197 }
3198
Ken Sumrall160b4d62013-04-22 12:15:39 -07003199 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003200 /* CRYPTO_GETFIELD_OK is success,
3201 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3202 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3203 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003204 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003205 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3206 int i;
3207 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003208
3209 if (persist_data == NULL) {
3210 load_persistent_data();
3211 if (persist_data == NULL) {
3212 SLOGE("Getfield error, cannot load persistent data");
3213 goto out;
3214 }
3215 }
3216
Rubin Xu85c01f92014-10-13 12:49:54 +01003217 // Read value from persistent entries. If the original value is split into multiple entries,
3218 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003219 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003220 // 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 -07003221 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003222 // value too small
3223 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3224 goto out;
3225 }
3226 rc = CRYPTO_GETFIELD_OK;
3227
3228 for (i = 1; /* break explicitly */; i++) {
3229 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003230 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003231 // If the fieldname is very long, we stop as soon as it begins to overflow the
3232 // maximum field length. At this point we have in fact fully read out the original
3233 // value because cryptfs_setfield would not allow fields with longer names to be
3234 // written in the first place.
3235 break;
3236 }
3237 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003238 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3239 // value too small.
3240 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3241 goto out;
3242 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003243 } else {
3244 // Exhaust all entries.
3245 break;
3246 }
3247 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003248 } else {
3249 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003250 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003251 }
3252
3253out:
3254 return rc;
3255}
3256
3257/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003258int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003259 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003260 SLOGE("Cannot set field when file encrypted");
3261 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003262 }
3263
Ken Sumrall160b4d62013-04-22 12:15:39 -07003264 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003265 /* 0 is success, negative values are error */
3266 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003267 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003268 unsigned int field_id;
3269 char temp_field[PROPERTY_KEY_MAX];
3270 unsigned int num_entries;
3271 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003272
3273 if (persist_data == NULL) {
3274 load_persistent_data();
3275 if (persist_data == NULL) {
3276 SLOGE("Setfield error, cannot load persistent data");
3277 goto out;
3278 }
3279 }
3280
3281 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003282 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003283 encrypted = 1;
3284 }
3285
Rubin Xu85c01f92014-10-13 12:49:54 +01003286 // Compute the number of entries required to store value, each entry can store up to
3287 // (PROPERTY_VALUE_MAX - 1) chars
3288 if (strlen(value) == 0) {
3289 // Empty value also needs one entry to store.
3290 num_entries = 1;
3291 } else {
3292 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3293 }
3294
3295 max_keylen = strlen(fieldname);
3296 if (num_entries > 1) {
3297 // Need an extra "_%d" suffix.
3298 max_keylen += 1 + log10(num_entries);
3299 }
3300 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3301 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003302 goto out;
3303 }
3304
Rubin Xu85c01f92014-10-13 12:49:54 +01003305 // Make sure we have enough space to write the new value
3306 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3307 persist_get_max_entries(encrypted)) {
3308 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3309 goto out;
3310 }
3311
3312 // Now that we know persist_data has enough space for value, let's delete the old field first
3313 // to make up space.
3314 persist_del_keys(fieldname, 0);
3315
3316 if (persist_set_key(fieldname, value, encrypted)) {
3317 // fail to set key, should not happen as we have already checked the available space
3318 SLOGE("persist_set_key() error during setfield()");
3319 goto out;
3320 }
3321
3322 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003323 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003324
3325 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3326 // fail to set key, should not happen as we have already checked the available space.
3327 SLOGE("persist_set_key() error during setfield()");
3328 goto out;
3329 }
3330 }
3331
Ken Sumrall160b4d62013-04-22 12:15:39 -07003332 /* If we are running encrypted, save the persistent data now */
3333 if (encrypted) {
3334 if (save_persistent_data()) {
3335 SLOGE("Setfield error, cannot save persistent data");
3336 goto out;
3337 }
3338 }
3339
Rubin Xu85c01f92014-10-13 12:49:54 +01003340 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003341
3342out:
3343 return rc;
3344}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003345
3346/* Checks userdata. Attempt to mount the volume if default-
3347 * encrypted.
3348 * On success trigger next init phase and return 0.
3349 * Currently do not handle failure - see TODO below.
3350 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003351int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003352 int crypt_type = cryptfs_get_password_type();
3353 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3354 SLOGE("Bad crypt type - error");
3355 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003356 SLOGD(
3357 "Password is not default - "
3358 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003359 property_set("vold.decrypt", "trigger_restart_min_framework");
3360 return 0;
3361 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3362 SLOGD("Password is default - restarting filesystem");
3363 cryptfs_restart_internal(0);
3364 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003365 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003366 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003367 }
3368
Paul Lawrence6bfed202014-07-28 12:47:22 -07003369 /** Corrupt. Allow us to boot into framework, which will detect bad
3370 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003371 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003372 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003373 return 0;
3374}
3375
3376/* Returns type of the password, default, pattern, pin or password.
3377 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003378int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003379 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003380 SLOGE("cryptfs_get_password_type not valid for file encryption");
3381 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003382 }
3383
Paul Lawrencef4faa572014-01-29 13:31:03 -08003384 struct crypt_mnt_ftr crypt_ftr;
3385
3386 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3387 SLOGE("Error getting crypt footer and key\n");
3388 return -1;
3389 }
3390
Paul Lawrence6bfed202014-07-28 12:47:22 -07003391 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3392 return -1;
3393 }
3394
Paul Lawrencef4faa572014-01-29 13:31:03 -08003395 return crypt_ftr.crypt_type;
3396}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003397
Paul Crowley14c8c072018-09-18 13:30:21 -07003398const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003399 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003400 SLOGE("cryptfs_get_password not valid for file encryption");
3401 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003402 }
3403
Paul Lawrence399317e2014-03-10 13:20:50 -07003404 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003405 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003406 if (now.tv_sec < password_expiry_time) {
3407 return password;
3408 } else {
3409 cryptfs_clear_password();
3410 return 0;
3411 }
3412}
3413
Paul Crowley14c8c072018-09-18 13:30:21 -07003414void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003415 if (password) {
3416 size_t len = strlen(password);
3417 memset(password, 0, len);
3418 free(password);
3419 password = 0;
3420 password_expiry_time = 0;
3421 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003422}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003423
Paul Crowley14c8c072018-09-18 13:30:21 -07003424int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07003425 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07003426 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07003427}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303428
3429int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3430{
3431 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3432 SLOGE("Failed to initialize crypt_ftr");
3433 return -1;
3434 }
3435
3436 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3437 crypt_ftr->salt, crypt_ftr)) {
3438 SLOGE("Cannot create encrypted master key\n");
3439 return -1;
3440 }
3441
3442 //crypt_ftr->keysize = key_length / 8;
3443 return 0;
3444}
3445
3446int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3447 unsigned char* master_key)
3448{
3449 int rc;
3450
3451 unsigned char* intermediate_key = 0;
3452 size_t intermediate_key_size = 0;
3453
3454 if (password == 0 || *password == 0) {
3455 password = DEFAULT_PASSWORD;
3456 }
3457
3458 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3459 &intermediate_key_size);
3460
3461 if (rc) {
3462 SLOGE("Can't calculate intermediate key");
3463 return rc;
3464 }
3465
3466 int N = 1 << ftr->N_factor;
3467 int r = 1 << ftr->r_factor;
3468 int p = 1 << ftr->p_factor;
3469
3470 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3471
3472 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3473 ftr->salt, sizeof(ftr->salt), N, r, p,
3474 scrypted_intermediate_key,
3475 sizeof(scrypted_intermediate_key));
3476
3477 free(intermediate_key);
3478
3479 if (rc) {
3480 SLOGE("Can't scrypt intermediate key");
3481 return rc;
3482 }
3483
3484 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3485 intermediate_key_size);
3486}