blob: f9d4ed4ae7574c5e56fad12162b86dae16d30c32 [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
Logan Chiend557d762018-05-02 11:36:45 +080017#define LOG_TAG "Cryptfs"
18
19#include "cryptfs.h"
20
Daniel Rosenberg65f99c92018-08-28 01:58:49 -070021#include "Checkpoint.h"
Paul Crowley220567c2020-02-07 12:45:20 -080022#include "CryptoType.h"
Logan Chiend557d762018-05-02 11:36:45 +080023#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070024#include "FsCrypt.h"
Eric Biggersd86a8ab2021-06-15 11:34:00 -070025#include "Keystore.h"
Logan Chiend557d762018-05-02 11:36:45 +080026#include "Process.h"
27#include "ScryptParameters.h"
Paul Crowleycfe39722018-10-30 15:59:24 -070028#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080029#include "VoldUtil.h"
30#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080031
Satya Tangiralae8de4ff2021-02-28 22:32:07 -080032#include <android-base/logging.h>
Eric Biggersed45ec32019-01-25 10:47:55 -080033#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080034#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080035#include <android-base/stringprintf.h>
Hyangseok Chae3cf32332020-02-27 18:21:50 +090036#include <android-base/strings.h>
Logan Chiend557d762018-05-02 11:36:45 +080037#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080039#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070040#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070043#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070044#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080045#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080046#include <logwrap/logwrap.h>
47#include <openssl/evp.h>
48#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070050#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080051
52#include <ctype.h>
53#include <errno.h>
54#include <fcntl.h>
55#include <inttypes.h>
56#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080057#include <linux/kdev_t.h>
58#include <math.h>
Hyangseok Chae3cf32332020-02-27 18:21:50 +090059#include <mntent.h>
Logan Chiend557d762018-05-02 11:36:45 +080060#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080063#include <sys/mount.h>
64#include <sys/param.h>
65#include <sys/stat.h>
66#include <sys/types.h>
67#include <sys/wait.h>
68#include <time.h>
69#include <unistd.h>
70
Martijn Coenen26ad7b32020-02-13 16:20:52 +010071#include <chrono>
72#include <thread>
73
Wei Wang4375f1b2017-02-24 17:43:01 -080074extern "C" {
75#include <crypto_scrypt.h>
76}
Mark Salyzyn3e971272014-01-21 13:27:04 -080077
Eric Biggersed45ec32019-01-25 10:47:55 -080078using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080079using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080080using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley220567c2020-02-07 12:45:20 -080081using android::vold::CryptoType;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080082using android::vold::KeyBuffer;
Paul Crowleyb3d018a2020-02-12 11:04:05 -080083using android::vold::KeyGeneration;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -080084using namespace android::vold;
David Andersonb9224732019-05-13 13:02:54 -070085using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070086using namespace std::chrono_literals;
87
Paul Crowley73be12d2020-02-03 12:22:03 -080088/* The current cryptfs version */
89#define CURRENT_MAJOR_VERSION 1
90#define CURRENT_MINOR_VERSION 3
91
92#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
93#define CRYPT_PERSIST_DATA_SIZE 0x1000
94
Eric Biggersf038c5f2020-11-03 14:11:02 -080095#define CRYPT_SECTOR_SIZE 512
96
Paul Crowley73be12d2020-02-03 12:22:03 -080097#define MAX_CRYPTO_TYPE_NAME_LEN 64
98
99#define MAX_KEY_LEN 48
100#define SALT_LEN 16
101#define SCRYPT_LEN 32
102
103/* definitions of flags in the structure below */
104#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
Eric Biggersc01995e2020-11-03 14:11:00 -0800105#define CRYPT_ENCRYPTION_IN_PROGRESS 0x2 /* no longer used */
Paul Crowley73be12d2020-02-03 12:22:03 -0800106#define CRYPT_INCONSISTENT_STATE \
107 0x4 /* Set when starting encryption, clear when \
108 exit cleanly, either through success or \
109 correctly marked partial encryption */
110#define CRYPT_DATA_CORRUPT \
111 0x8 /* Set when encryption is fine, but the \
112 underlying volume is corrupt */
113#define CRYPT_FORCE_ENCRYPTION \
114 0x10 /* Set when it is time to encrypt this \
115 volume on boot. Everything in this \
116 structure is set up correctly as \
117 though device is encrypted except \
118 that the master key is encrypted with the \
119 default password. */
120#define CRYPT_FORCE_COMPLETE \
121 0x20 /* Set when the above encryption cycle is \
122 complete. On next cryptkeeper entry, match \
123 the password. If it matches fix the master \
124 key and remove this flag. */
125
126/* Allowed values for type in the structure below */
127#define CRYPT_TYPE_PASSWORD \
128 0 /* master_key is encrypted with a password \
129 * Must be zero to be compatible with pre-L \
130 * devices where type is always password.*/
131#define CRYPT_TYPE_DEFAULT \
132 1 /* master_key is encrypted with default \
133 * password */
134#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
135#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
136#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
137
138#define CRYPT_MNT_MAGIC 0xD0B5B1C4
139#define PERSIST_DATA_MAGIC 0xE950CD44
140
141/* Key Derivation Function algorithms */
142#define KDF_PBKDF2 1
143#define KDF_SCRYPT 2
144/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
145#define KDF_SCRYPT_KEYMASTER 5
146
147/* Maximum allowed keymaster blob size. */
148#define KEYMASTER_BLOB_SIZE 2048
149
150/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
151#define __le8 unsigned char
152
153#if !defined(SHA256_DIGEST_LENGTH)
154#define SHA256_DIGEST_LENGTH 32
155#endif
156
157/* This structure starts 16,384 bytes before the end of a hardware
158 * partition that is encrypted, or in a separate partition. It's location
159 * is specified by a property set in init.<device>.rc.
160 * The structure allocates 48 bytes for a key, but the real key size is
161 * specified in the struct. Currently, the code is hardcoded to use 128
162 * bit keys.
163 * The fields after salt are only valid in rev 1.1 and later stuctures.
164 * Obviously, the filesystem does not include the last 16 kbytes
165 * of the partition if the crypt_mnt_ftr lives at the end of the
166 * partition.
167 */
168
169struct crypt_mnt_ftr {
170 __le32 magic; /* See above */
171 __le16 major_version;
172 __le16 minor_version;
173 __le32 ftr_size; /* in bytes, not including key following */
174 __le32 flags; /* See above */
175 __le32 keysize; /* in bytes */
176 __le32 crypt_type; /* how master_key is encrypted. Must be a
177 * CRYPT_TYPE_XXX value */
178 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
179 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
180 mount, set to 0 on successful mount */
181 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
182 needed to decrypt this
183 partition, null terminated */
184 __le32 spare2; /* ignored */
185 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
186 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
187 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
188 * on device with that info, either the footer of the
189 * real_blkdevice or the metadata partition. */
190
191 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
192 * persistent data table*/
193
194 __le8 kdf_type; /* The key derivation function used. */
195
196 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
197 __le8 N_factor; /* (1 << N) */
198 __le8 r_factor; /* (1 << r) */
199 __le8 p_factor; /* (1 << p) */
Eric Biggersc01995e2020-11-03 14:11:00 -0800200 __le64 encrypted_upto; /* no longer used */
201 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* no longer used */
Paul Crowley73be12d2020-02-03 12:22:03 -0800202
203 /* key_master key, used to sign the derived key which is then used to generate
204 * the intermediate key
205 * This key should be used for no other purposes! We use this key to sign unpadded
206 * data, which is acceptable but only if the key is not reused elsewhere. */
207 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
208 __le32 keymaster_blob_size;
209
210 /* Store scrypt of salted intermediate key. When decryption fails, we can
211 check if this matches, and if it does, we know that the problem is with the
212 drive, and there is no point in asking the user for more passwords.
213
214 Note that if any part of this structure is corrupt, this will not match and
215 we will continue to believe the user entered the wrong password. In that
216 case the only solution is for the user to enter a password enough times to
217 force a wipe.
218
219 Note also that there is no need to worry about migration. If this data is
220 wrong, we simply won't recognise a right password, and will continue to
221 prompt. On the first password change, this value will be populated and
222 then we will be OK.
223 */
224 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
225
226 /* sha of this structure with this element set to zero
227 Used when encrypting on reboot to validate structure before doing something
228 fatal
229 */
230 unsigned char sha256[SHA256_DIGEST_LENGTH];
231};
232
233/* Persistant data that should be available before decryption.
234 * Things like airplane mode, locale and timezone are kept
235 * here and can be retrieved by the CryptKeeper UI to properly
236 * configure the phone before asking for the password
237 * This is only valid if the major and minor version above
238 * is set to 1.1 or higher.
239 *
240 * This is a 4K structure. There are 2 copies, and the code alternates
241 * writing one and then clearing the previous one. The reading
242 * code reads the first valid copy it finds, based on the magic number.
243 * The absolute offset to the first of the two copies is kept in rev 1.1
244 * and higher crypt_mnt_ftr structures.
245 */
246struct crypt_persist_entry {
247 char key[PROPERTY_KEY_MAX];
248 char val[PROPERTY_VALUE_MAX];
249};
250
251/* Should be exactly 4K in size */
252struct crypt_persist_data {
253 __le32 persist_magic;
254 __le32 persist_valid_entries;
255 __le32 persist_spare[30];
256 struct crypt_persist_entry persist_entry[0];
257};
258
Paul Crowley73be12d2020-02-03 12:22:03 -0800259typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
260 void* params);
261
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800262#define UNUSED __attribute__((unused))
263
Jason parks70a4b3f2011-01-28 10:10:47 -0600264#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800265
266constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
267constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700268constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800269
270// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700271static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600272
Paul Crowley14c8c072018-09-18 13:30:21 -0700273#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700274
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700275#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800276
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800277#define CRYPTO_BLOCK_DEVICE "userdata"
278
279#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
280
Ken Sumrall29d8da82011-05-18 17:20:07 -0700281#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700282#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700283
Ken Sumralle919efe2012-09-29 17:07:41 -0700284#define TABLE_LOAD_RETRIES 10
285
Shawn Willden47ba10d2014-09-03 17:07:06 -0600286#define RSA_KEY_SIZE 2048
287#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
288#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600289#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700290
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700291#define RETRY_MOUNT_ATTEMPTS 10
292#define RETRY_MOUNT_DELAY_SECONDS 1
293
Paul Crowley5afbc622017-11-27 09:42:17 -0800294#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
295
Paul Crowley73473332017-11-21 15:43:51 -0800296static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
297
Greg Kaiser59ad0182018-02-16 13:01:36 -0800298static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700299static char* saved_mount_point;
300static int master_key_saved = 0;
301static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800302
Paul Crowley220567c2020-02-07 12:45:20 -0800303constexpr CryptoType aes_128_cbc = CryptoType()
304 .set_config_name("AES-128-CBC")
305 .set_kernel_name("aes-cbc-essiv:sha256")
306 .set_keysize(16);
307
308constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
309
310static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
311 array_length(supported_crypto_types)),
312 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
313 "incompletely constructed.");
314
315static const CryptoType& get_crypto_type() {
316 // We only want to parse this read-only property once. But we need to wait
317 // until the system is initialized before we can read it. So we use a static
318 // scoped within this function to get it only once.
319 static CryptoType crypto_type =
320 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
321 aes_128_cbc, "ro.crypto.fde_algorithm");
322 return crypto_type;
323}
324
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800325const KeyGeneration cryptfs_get_keygen() {
Paul Crowley249c2fb2020-02-07 12:51:56 -0800326 return KeyGeneration{get_crypto_type().get_keysize(), true, false};
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800327}
328
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800329static bool write_string_to_buf(const std::string& towrite, uint8_t* buffer, uint32_t buffer_size,
330 uint32_t* out_size) {
331 if (!buffer || !out_size) {
332 LOG(ERROR) << "Missing target pointers";
333 return false;
334 }
335 *out_size = towrite.size();
336 if (buffer_size < towrite.size()) {
337 LOG(ERROR) << "Buffer too small " << buffer_size << " < " << towrite.size();
338 return false;
339 }
340 memset(buffer, '\0', buffer_size);
341 std::copy(towrite.begin(), towrite.end(), buffer);
342 return true;
343}
344
345static int keymaster_create_key_for_cryptfs_scrypt(uint32_t rsa_key_size, uint64_t rsa_exponent,
346 uint32_t ratelimit, uint8_t* key_buffer,
347 uint32_t key_buffer_size,
348 uint32_t* key_out_size) {
349 if (key_out_size) {
350 *key_out_size = 0;
351 }
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700352 Keystore dev;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800353 if (!dev) {
354 LOG(ERROR) << "Failed to initiate keymaster session";
355 return -1;
356 }
357 auto keyParams = km::AuthorizationSetBuilder()
358 .RsaSigningKey(rsa_key_size, rsa_exponent)
359 .NoDigestOrPadding()
360 .Authorization(km::TAG_NO_AUTH_REQUIRED)
361 .Authorization(km::TAG_MIN_SECONDS_BETWEEN_OPS, ratelimit);
362 std::string key;
363 if (!dev.generateKey(keyParams, &key)) return -1;
364 if (!write_string_to_buf(key, key_buffer, key_buffer_size, key_out_size)) return -1;
365 return 0;
366}
367
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700368/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700369static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800370 if (ftr->keymaster_blob_size) {
371 SLOGI("Already have key");
372 return 0;
373 }
374
Paul Crowley14c8c072018-09-18 13:30:21 -0700375 int rc = keymaster_create_key_for_cryptfs_scrypt(
376 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
377 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000378 if (rc) {
379 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800380 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000381 ftr->keymaster_blob_size = 0;
382 }
383 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700384 return -1;
385 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000386 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700387}
388
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800389static int keymaster_sign_object_for_cryptfs_scrypt(struct crypt_mnt_ftr* ftr, uint32_t ratelimit,
390 const uint8_t* object, const size_t object_size,
391 uint8_t** signature_buffer,
392 size_t* signature_buffer_size) {
393 if (!object || !signature_buffer || !signature_buffer_size) {
394 LOG(ERROR) << __FILE__ << ":" << __LINE__ << ":Invalid argument";
395 return -1;
396 }
397
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700398 Keystore dev;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800399 if (!dev) {
400 LOG(ERROR) << "Failed to initiate keymaster session";
401 return -1;
402 }
403
404 km::AuthorizationSet outParams;
405 std::string key(reinterpret_cast<const char*>(ftr->keymaster_blob), ftr->keymaster_blob_size);
406 std::string input(reinterpret_cast<const char*>(object), object_size);
407 std::string output;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700408 KeystoreOperation op;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800409
410 auto paramBuilder = km::AuthorizationSetBuilder().NoDigestOrPadding().Authorization(
411 km::TAG_PURPOSE, km::KeyPurpose::SIGN);
412 while (true) {
413 op = dev.begin(key, paramBuilder, &outParams);
414 if (op.getErrorCode() == km::ErrorCode::KEY_RATE_LIMIT_EXCEEDED) {
415 sleep(ratelimit);
416 continue;
417 } else
418 break;
419 }
420
421 if (!op) {
422 LOG(ERROR) << "Error starting keymaster signature transaction: "
423 << int32_t(op.getErrorCode());
424 return -1;
425 }
426
427 if (op.getUpgradedBlob()) {
428 write_string_to_buf(*op.getUpgradedBlob(), ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
429 &ftr->keymaster_blob_size);
430
431 SLOGD("Upgrading key");
432 if (put_crypt_ftr_and_key(ftr) != 0) {
433 SLOGE("Failed to write upgraded key to disk");
434 return -1;
435 }
436 SLOGD("Key upgraded successfully");
437 }
438
439 if (!op.updateCompletely(input, &output)) {
440 LOG(ERROR) << "Error sending data to keymaster signature transaction: "
441 << int32_t(op.getErrorCode());
442 return -1;
443 }
444
445 if (!op.finish(&output)) {
446 LOG(ERROR) << "Error finalizing keymaster signature transaction: "
447 << int32_t(op.getErrorCode());
448 return -1;
449 }
450
451 *signature_buffer = reinterpret_cast<uint8_t*>(malloc(output.size()));
452 if (*signature_buffer == nullptr) {
453 LOG(ERROR) << "Error allocation buffer for keymaster signature";
454 return -1;
455 }
456 *signature_buffer_size = output.size();
457 std::copy(output.data(), output.data() + output.size(), *signature_buffer);
458
459 return 0;
460}
461
Shawn Willdene17a9c42014-09-08 13:04:08 -0600462/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700463static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
464 const size_t object_size, unsigned char** signature,
465 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600466 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600467 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600468 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600469
Shawn Willdene17a9c42014-09-08 13:04:08 -0600470 // To sign a message with RSA, the message must satisfy two
471 // constraints:
472 //
473 // 1. The message, when interpreted as a big-endian numeric value, must
474 // be strictly less than the public modulus of the RSA key. Note
475 // that because the most significant bit of the public modulus is
476 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
477 // key), an n-bit message with most significant bit 0 always
478 // satisfies this requirement.
479 //
480 // 2. The message must have the same length in bits as the public
481 // modulus of the RSA key. This requirement isn't mathematically
482 // necessary, but is necessary to ensure consistency in
483 // implementations.
484 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600485 case KDF_SCRYPT_KEYMASTER:
486 // This ensures the most significant byte of the signed message
487 // is zero. We could have zero-padded to the left instead, but
488 // this approach is slightly more robust against changes in
489 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600490 // so) because we really should be using a proper deterministic
491 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800492 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600493 SLOGI("Signing safely-padded object");
494 break;
495 default:
496 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000497 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600498 }
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800499 return keymaster_sign_object_for_cryptfs_scrypt(ftr, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
500 to_sign_size, signature, signature_size);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600501}
502
Paul Lawrence399317e2014-03-10 13:20:50 -0700503/* Store password when userdata is successfully decrypted and mounted.
504 * Cleared by cryptfs_clear_password
505 *
506 * To avoid a double prompt at boot, we need to store the CryptKeeper
507 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
508 * Since the entire framework is torn down and rebuilt after encryption,
509 * we have to use a daemon or similar to store the password. Since vold
510 * is secured against IPC except from system processes, it seems a reasonable
511 * place to store this.
512 *
513 * password should be cleared once it has been used.
514 *
515 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800516 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700517static char* password = 0;
518static int password_expiry_time = 0;
519static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800520
Paul Crowley14c8c072018-09-18 13:30:21 -0700521enum class RebootType { reboot, recovery, shutdown };
522static void cryptfs_reboot(RebootType rt) {
523 switch (rt) {
524 case RebootType::reboot:
525 property_set(ANDROID_RB_PROPERTY, "reboot");
526 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800527
Paul Crowley14c8c072018-09-18 13:30:21 -0700528 case RebootType::recovery:
529 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
530 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800531
Paul Crowley14c8c072018-09-18 13:30:21 -0700532 case RebootType::shutdown:
533 property_set(ANDROID_RB_PROPERTY, "shutdown");
534 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700535 }
Paul Lawrence87999172014-02-20 12:21:31 -0800536
Ken Sumralladfba362013-06-04 16:37:52 -0700537 sleep(20);
538
539 /* Shouldn't get here, reboot should happen before sleep times out */
540 return;
541}
542
Kenny Rootc4c70f12013-06-14 12:11:38 -0700543/**
544 * Gets the default device scrypt parameters for key derivation time tuning.
545 * The parameters should lead to about one second derivation time for the
546 * given device.
547 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700548static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700549 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000550 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700551
Paul Crowley63c18d32016-02-10 14:02:47 +0000552 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
553 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
554 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
555 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700556 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000557 ftr->N_factor = Nf;
558 ftr->r_factor = rf;
559 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700560}
561
Tom Cherry4c5bde22019-01-29 14:34:01 -0800562static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800563 int fd, block_size;
564 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200565 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800566
Paul Crowley14c8c072018-09-18 13:30:21 -0700567 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800568 SLOGE("Cannot open device to get filesystem size ");
569 return 0;
570 }
571
572 if (lseek64(fd, 1024, SEEK_SET) < 0) {
573 SLOGE("Cannot seek to superblock");
574 return 0;
575 }
576
577 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
578 SLOGE("Cannot read superblock");
579 return 0;
580 }
581
582 close(fd);
583
Daniel Rosenberge82df162014-08-15 22:19:23 +0000584 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
585 SLOGE("Not a valid ext4 superblock");
586 return 0;
587 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800588 block_size = 1024 << sb.s_log_block_size;
589 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200590 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800591
592 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200593 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800594}
595
Tom Cherry4c5bde22019-01-29 14:34:01 -0800596static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
597 for (const auto& entry : fstab_default) {
598 if (!entry.fs_mgr_flags.vold_managed &&
599 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
600 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
601 if (key_loc != nullptr) {
602 *key_loc = entry.key_loc;
603 }
604 if (real_blk_device != nullptr) {
605 *real_blk_device = entry.blk_device;
606 }
607 return;
608 }
609 }
610}
611
Paul Crowley14c8c072018-09-18 13:30:21 -0700612static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
613 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200614 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700615 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700616 char key_loc[PROPERTY_VALUE_MAX];
617 char real_blkdev[PROPERTY_VALUE_MAX];
618 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619
Paul Crowley14c8c072018-09-18 13:30:21 -0700620 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800621 std::string key_loc;
622 std::string real_blkdev;
623 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700624
Tom Cherry4c5bde22019-01-29 14:34:01 -0800625 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200626 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700627 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
628 * encryption info footer and key, and plenty of bytes to spare for future
629 * growth.
630 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800631 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200632 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700633 cached_data = 1;
634 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800635 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700636 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700637 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800638 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700639 cached_off = 0;
640 cached_data = 1;
641 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700642 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700643
Paul Crowley14c8c072018-09-18 13:30:21 -0700644 if (cached_data) {
645 if (metadata_fname) {
646 *metadata_fname = cached_metadata_fname;
647 }
648 if (off) {
649 *off = cached_off;
650 }
651 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700652 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700653
Paul Crowley14c8c072018-09-18 13:30:21 -0700654 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700655}
656
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800657/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700658static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800659 SHA256_CTX c;
660 SHA256_Init(&c);
661 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
662 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
663 SHA256_Final(crypt_ftr->sha256, &c);
664}
665
Ken Sumralle8744072011-01-18 22:01:55 -0800666/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800667 * update the failed mount count but not change the key.
668 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700669static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
670 int fd;
671 unsigned int cnt;
672 /* starting_off is set to the SEEK_SET offset
673 * where the crypto structure starts
674 */
675 off64_t starting_off;
676 int rc = -1;
677 char* fname = NULL;
678 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800679
Paul Crowley14c8c072018-09-18 13:30:21 -0700680 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800681
Paul Crowley14c8c072018-09-18 13:30:21 -0700682 if (get_crypt_ftr_info(&fname, &starting_off)) {
683 SLOGE("Unable to get crypt_ftr_info\n");
684 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800685 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700686 if (fname[0] != '/') {
687 SLOGE("Unexpected value for crypto key location\n");
688 return -1;
689 }
690 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
691 SLOGE("Cannot open footer file %s for put\n", fname);
692 return -1;
693 }
Ken Sumralle8744072011-01-18 22:01:55 -0800694
Paul Crowley14c8c072018-09-18 13:30:21 -0700695 /* Seek to the start of the crypt footer */
696 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
697 SLOGE("Cannot seek to real block device footer\n");
698 goto errout;
699 }
700
701 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
702 SLOGE("Cannot write real block device footer\n");
703 goto errout;
704 }
705
706 fstat(fd, &statbuf);
707 /* If the keys are kept on a raw block device, do not try to truncate it. */
708 if (S_ISREG(statbuf.st_mode)) {
709 if (ftruncate(fd, 0x4000)) {
710 SLOGE("Cannot set footer file size\n");
711 goto errout;
712 }
713 }
714
715 /* Success! */
716 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800717
718errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700719 close(fd);
720 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800721}
722
Paul Crowley14c8c072018-09-18 13:30:21 -0700723static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800724 struct crypt_mnt_ftr copy;
725 memcpy(&copy, crypt_ftr, sizeof(copy));
726 set_ftr_sha(&copy);
727 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
728}
729
Paul Crowley14c8c072018-09-18 13:30:21 -0700730static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700731 return TEMP_FAILURE_RETRY(read(fd, buff, len));
732}
733
Paul Crowley14c8c072018-09-18 13:30:21 -0700734static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700735 return TEMP_FAILURE_RETRY(write(fd, buff, len));
736}
737
Paul Crowley14c8c072018-09-18 13:30:21 -0700738static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700739 memset(pdata, 0, len);
740 pdata->persist_magic = PERSIST_DATA_MAGIC;
741 pdata->persist_valid_entries = 0;
742}
743
744/* A routine to update the passed in crypt_ftr to the lastest version.
745 * fd is open read/write on the device that holds the crypto footer and persistent
746 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
747 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
748 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700749static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700750 int orig_major = crypt_ftr->major_version;
751 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700752
Kenny Root7434b312013-06-14 11:29:53 -0700753 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700754 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700755 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700756
Kenny Rootc4c70f12013-06-14 12:11:38 -0700757 SLOGW("upgrading crypto footer to 1.1");
758
Paul Crowley14c8c072018-09-18 13:30:21 -0700759 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700760 if (pdata == NULL) {
761 SLOGE("Cannot allocate persisent data\n");
762 return;
763 }
764 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
765
766 /* Need to initialize the persistent data area */
767 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
768 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100769 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700770 return;
771 }
772 /* Write all zeros to the first copy, making it invalid */
773 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
774
775 /* Write a valid but empty structure to the second copy */
776 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
777 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
778
779 /* Update the footer */
780 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
781 crypt_ftr->persist_data_offset[0] = pdata_offset;
782 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
783 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100784 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700785 }
786
Paul Lawrencef4faa572014-01-29 13:31:03 -0800787 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700788 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800789 /* But keep the old kdf_type.
790 * It will get updated later to KDF_SCRYPT after the password has been verified.
791 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700792 crypt_ftr->kdf_type = KDF_PBKDF2;
793 get_device_scrypt_params(crypt_ftr);
794 crypt_ftr->minor_version = 2;
795 }
796
Paul Lawrencef4faa572014-01-29 13:31:03 -0800797 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
798 SLOGW("upgrading crypto footer to 1.3");
799 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
800 crypt_ftr->minor_version = 3;
801 }
802
Kenny Root7434b312013-06-14 11:29:53 -0700803 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
804 if (lseek64(fd, offset, SEEK_SET) == -1) {
805 SLOGE("Cannot seek to crypt footer\n");
806 return;
807 }
808 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700809 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700810}
811
Paul Crowley14c8c072018-09-18 13:30:21 -0700812static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
813 int fd;
814 unsigned int cnt;
815 off64_t starting_off;
816 int rc = -1;
817 char* fname = NULL;
818 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700819
Paul Crowley14c8c072018-09-18 13:30:21 -0700820 if (get_crypt_ftr_info(&fname, &starting_off)) {
821 SLOGE("Unable to get crypt_ftr_info\n");
822 return -1;
823 }
824 if (fname[0] != '/') {
825 SLOGE("Unexpected value for crypto key location\n");
826 return -1;
827 }
828 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
829 SLOGE("Cannot open footer file %s for get\n", fname);
830 return -1;
831 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800832
Paul Crowley14c8c072018-09-18 13:30:21 -0700833 /* Make sure it's 16 Kbytes in length */
834 fstat(fd, &statbuf);
835 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
836 SLOGE("footer file %s is not the expected size!\n", fname);
837 goto errout;
838 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700839
Paul Crowley14c8c072018-09-18 13:30:21 -0700840 /* Seek to the start of the crypt footer */
841 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
842 SLOGE("Cannot seek to real block device footer\n");
843 goto errout;
844 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700845
Paul Crowley14c8c072018-09-18 13:30:21 -0700846 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
847 SLOGE("Cannot read real block device footer\n");
848 goto errout;
849 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800850
Paul Crowley14c8c072018-09-18 13:30:21 -0700851 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
852 SLOGE("Bad magic for real block device %s\n", fname);
853 goto errout;
854 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800855
Paul Crowley14c8c072018-09-18 13:30:21 -0700856 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
857 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
858 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
859 goto errout;
860 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800861
Paul Crowley14c8c072018-09-18 13:30:21 -0700862 // We risk buffer overflows with oversized keys, so we just reject them.
863 // 0-sized keys are problematic (essentially by-passing encryption), and
864 // AES-CBC key wrapping only works for multiples of 16 bytes.
865 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
866 (crypt_ftr->keysize > MAX_KEY_LEN)) {
867 SLOGE(
868 "Invalid keysize (%u) for block device %s; Must be non-zero, "
869 "divisible by 16, and <= %d\n",
870 crypt_ftr->keysize, fname, MAX_KEY_LEN);
871 goto errout;
872 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800873
Paul Crowley14c8c072018-09-18 13:30:21 -0700874 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
875 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
876 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
877 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800878
Paul Crowley14c8c072018-09-18 13:30:21 -0700879 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
880 * copy on disk before returning.
881 */
882 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
883 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
884 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800885
Paul Crowley14c8c072018-09-18 13:30:21 -0700886 /* Success! */
887 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800888
889errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700890 close(fd);
891 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800892}
893
Paul Crowley14c8c072018-09-18 13:30:21 -0700894static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700895 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
896 crypt_ftr->persist_data_offset[1]) {
897 SLOGE("Crypt_ftr persist data regions overlap");
898 return -1;
899 }
900
901 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
902 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
903 return -1;
904 }
905
906 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700907 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700908 CRYPT_FOOTER_OFFSET) {
909 SLOGE("Persistent data extends past crypto footer");
910 return -1;
911 }
912
913 return 0;
914}
915
Paul Crowley14c8c072018-09-18 13:30:21 -0700916static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700917 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700918 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700919 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700920 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700921 int found = 0;
922 int fd;
923 int ret;
924 int i;
925
926 if (persist_data) {
927 /* Nothing to do, we've already loaded or initialized it */
928 return 0;
929 }
930
Ken Sumrall160b4d62013-04-22 12:15:39 -0700931 /* If not encrypted, just allocate an empty table and initialize it */
932 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700933 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800934 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700935 if (pdata) {
936 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
937 persist_data = pdata;
938 return 0;
939 }
940 return -1;
941 }
942
Paul Crowley14c8c072018-09-18 13:30:21 -0700943 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700944 return -1;
945 }
946
Paul Crowley14c8c072018-09-18 13:30:21 -0700947 if ((crypt_ftr.major_version < 1) ||
948 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700949 SLOGE("Crypt_ftr version doesn't support persistent data");
950 return -1;
951 }
952
953 if (get_crypt_ftr_info(&fname, NULL)) {
954 return -1;
955 }
956
957 ret = validate_persistent_data_storage(&crypt_ftr);
958 if (ret) {
959 return -1;
960 }
961
Paul Crowley14c8c072018-09-18 13:30:21 -0700962 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700963 if (fd < 0) {
964 SLOGE("Cannot open %s metadata file", fname);
965 return -1;
966 }
967
Wei Wang4375f1b2017-02-24 17:43:01 -0800968 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800969 if (pdata == NULL) {
970 SLOGE("Cannot allocate memory for persistent data");
971 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700972 }
973
974 for (i = 0; i < 2; i++) {
975 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
976 SLOGE("Cannot seek to read persistent data on %s", fname);
977 goto err2;
978 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700979 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700980 SLOGE("Error reading persistent data on iteration %d", i);
981 goto err2;
982 }
983 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
984 found = 1;
985 break;
986 }
987 }
988
989 if (!found) {
990 SLOGI("Could not find valid persistent data, creating");
991 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
992 }
993
994 /* Success */
995 persist_data = pdata;
996 close(fd);
997 return 0;
998
999err2:
1000 free(pdata);
1001
1002err:
1003 close(fd);
1004 return -1;
1005}
1006
Paul Crowley14c8c072018-09-18 13:30:21 -07001007static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001008 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001009 struct crypt_persist_data* pdata;
1010 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001011 off64_t write_offset;
1012 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001013 int fd;
1014 int ret;
1015
1016 if (persist_data == NULL) {
1017 SLOGE("No persistent data to save");
1018 return -1;
1019 }
1020
Paul Crowley14c8c072018-09-18 13:30:21 -07001021 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001022 return -1;
1023 }
1024
Paul Crowley14c8c072018-09-18 13:30:21 -07001025 if ((crypt_ftr.major_version < 1) ||
1026 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001027 SLOGE("Crypt_ftr version doesn't support persistent data");
1028 return -1;
1029 }
1030
1031 ret = validate_persistent_data_storage(&crypt_ftr);
1032 if (ret) {
1033 return -1;
1034 }
1035
1036 if (get_crypt_ftr_info(&fname, NULL)) {
1037 return -1;
1038 }
1039
Paul Crowley14c8c072018-09-18 13:30:21 -07001040 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001041 if (fd < 0) {
1042 SLOGE("Cannot open %s metadata file", fname);
1043 return -1;
1044 }
1045
Wei Wang4375f1b2017-02-24 17:43:01 -08001046 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001047 if (pdata == NULL) {
1048 SLOGE("Cannot allocate persistant data");
1049 goto err;
1050 }
1051
1052 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1053 SLOGE("Cannot seek to read persistent data on %s", fname);
1054 goto err2;
1055 }
1056
1057 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001058 SLOGE("Error reading persistent data before save");
1059 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001060 }
1061
1062 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1063 /* The first copy is the curent valid copy, so write to
1064 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001065 write_offset = crypt_ftr.persist_data_offset[1];
1066 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001067 } else {
1068 /* The second copy must be the valid copy, so write to
1069 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001070 write_offset = crypt_ftr.persist_data_offset[0];
1071 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001072 }
1073
1074 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001075 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001076 SLOGE("Cannot seek to write persistent data");
1077 goto err2;
1078 }
1079 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001080 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001081 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001082 SLOGE("Cannot seek to erase previous persistent data");
1083 goto err2;
1084 }
1085 fsync(fd);
1086 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001087 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001088 SLOGE("Cannot write to erase previous persistent data");
1089 goto err2;
1090 }
1091 fsync(fd);
1092 } else {
1093 SLOGE("Cannot write to save persistent data");
1094 goto err2;
1095 }
1096
1097 /* Success */
1098 free(pdata);
1099 close(fd);
1100 return 0;
1101
1102err2:
1103 free(pdata);
1104err:
1105 close(fd);
1106 return -1;
1107}
1108
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001109/* Convert a binary key of specified length into an ascii hex string equivalent,
1110 * without the leading 0x and with null termination
1111 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001112static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1113 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001114 unsigned int i, a;
1115 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001116
Paul Crowley14c8c072018-09-18 13:30:21 -07001117 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001118 /* For each byte, write out two ascii hex digits */
1119 nibble = (master_key[i] >> 4) & 0xf;
1120 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001122 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001123 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001124 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001126 /* Add the null termination */
1127 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001128}
1129
Eric Biggersed45ec32019-01-25 10:47:55 -08001130/*
1131 * If the ro.crypto.fde_sector_size system property is set, append the
1132 * parameters to make dm-crypt use the specified crypto sector size and round
1133 * the crypto device size down to a crypto sector boundary.
1134 */
David Andersonb9224732019-05-13 13:02:54 -07001135static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001136 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001137 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001138
Eric Biggersed45ec32019-01-25 10:47:55 -08001139 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1140 unsigned int sector_size;
1141
1142 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1143 (sector_size & (sector_size - 1)) != 0) {
1144 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1145 DM_CRYPT_SECTOR_SIZE, value);
1146 return -1;
1147 }
1148
David Andersonb9224732019-05-13 13:02:54 -07001149 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001150
1151 // With this option, IVs will match the sector numbering, instead
1152 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001153 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001154
1155 // Round the crypto device size down to a crypto sector boundary.
1156 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001157 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001158 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001159}
1160
Paul Crowley5afbc622017-11-27 09:42:17 -08001161static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001162 const char* real_blk_name, std::string* crypto_blk_name,
1163 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001164 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165
David Andersonb9224732019-05-13 13:02:54 -07001166 // We need two ASCII characters to represent each byte, and need space for
1167 // the '\0' terminator.
1168 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1169 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001170
David Andersonb9224732019-05-13 13:02:54 -07001171 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1172 (const char*)crypt_ftr->crypto_type_name,
1173 master_key_ascii, 0, real_blk_name, 0);
1174 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001175
Paul Crowley5afbc622017-11-27 09:42:17 -08001176 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001177 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001178 }
David Andersonb9224732019-05-13 13:02:54 -07001179 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001180 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001181 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001182 }
David Andersonb9224732019-05-13 13:02:54 -07001183
1184 DmTable table;
1185 table.AddTarget(std::move(target));
1186
1187 int load_count = 1;
1188 while (load_count < TABLE_LOAD_RETRIES) {
1189 if (dm.CreateDevice(name, table)) {
1190 break;
1191 }
1192 load_count++;
1193 }
1194
1195 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001196 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001197 return -1;
1198 }
1199 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001200 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1201 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001202
Paul Crowley81796e92020-02-07 11:27:49 -08001203 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001204 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1205 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001206 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207
Paul Crowleycfe39722018-10-30 15:59:24 -07001208 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001209 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001210 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001211 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001212 }
David Andersonb9224732019-05-13 13:02:54 -07001213 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001214}
1215
David Andersonb9224732019-05-13 13:02:54 -07001216static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001217 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001218 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001219 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1220 // to delete the device fails with EBUSY; for now, work around this by retrying.
1221 int tries = 5;
1222 while (tries-- > 0) {
1223 ret = dm.DeleteDevice(name);
1224 if (ret || errno != EBUSY) {
1225 break;
1226 }
1227 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1228 strerror(errno));
1229 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1230 }
1231 if (!ret) {
1232 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001233 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001234 }
David Andersonb9224732019-05-13 13:02:54 -07001235 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001236}
1237
Paul Crowley14c8c072018-09-18 13:30:21 -07001238static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1239 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001240 SLOGI("Using pbkdf2 for cryptfs KDF");
1241
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001242 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001243 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1244 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001245}
1246
Paul Crowley14c8c072018-09-18 13:30:21 -07001247static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001248 SLOGI("Using scrypt for cryptfs KDF");
1249
Paul Crowley14c8c072018-09-18 13:30:21 -07001250 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001251
1252 int N = 1 << ftr->N_factor;
1253 int r = 1 << ftr->r_factor;
1254 int p = 1 << ftr->p_factor;
1255
1256 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001257 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001258 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001259
Paul Crowley14c8c072018-09-18 13:30:21 -07001260 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001261}
1262
Paul Crowley14c8c072018-09-18 13:30:21 -07001263static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1264 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001265 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1266
1267 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001268 size_t signature_size;
1269 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001270 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001271
1272 int N = 1 << ftr->N_factor;
1273 int r = 1 << ftr->r_factor;
1274 int p = 1 << ftr->p_factor;
1275
Paul Crowley14c8c072018-09-18 13:30:21 -07001276 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001277 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001278
1279 if (rc) {
1280 SLOGE("scrypt failed");
1281 return -1;
1282 }
1283
Paul Crowley14c8c072018-09-18 13:30:21 -07001284 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001285 SLOGE("Signing failed");
1286 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001287 }
1288
Paul Crowley14c8c072018-09-18 13:30:21 -07001289 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1290 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001291 free(signature);
1292
1293 if (rc) {
1294 SLOGE("scrypt failed");
1295 return -1;
1296 }
1297
1298 return 0;
1299}
1300
Paul Crowley14c8c072018-09-18 13:30:21 -07001301static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1302 const unsigned char* decrypted_master_key,
1303 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1304 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001305 EVP_CIPHER_CTX e_ctx;
1306 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001307 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001308
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001309 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001310 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001311
1312 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001313 case KDF_SCRYPT_KEYMASTER:
1314 if (keymaster_create_key(crypt_ftr)) {
1315 SLOGE("keymaster_create_key failed");
1316 return -1;
1317 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001318
Paul Crowley14c8c072018-09-18 13:30:21 -07001319 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1320 SLOGE("scrypt failed");
1321 return -1;
1322 }
1323 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001324
Paul Crowley14c8c072018-09-18 13:30:21 -07001325 case KDF_SCRYPT:
1326 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1327 SLOGE("scrypt failed");
1328 return -1;
1329 }
1330 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001331
Paul Crowley14c8c072018-09-18 13:30:21 -07001332 default:
1333 SLOGE("Invalid kdf_type");
1334 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001335 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001336
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001337 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001338 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001339 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1340 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001341 SLOGE("EVP_EncryptInit failed\n");
1342 return -1;
1343 }
1344 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001345
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001346 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001347 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1348 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349 SLOGE("EVP_EncryptUpdate failed\n");
1350 return -1;
1351 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001352 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001353 SLOGE("EVP_EncryptFinal failed\n");
1354 return -1;
1355 }
1356
Greg Kaiser59ad0182018-02-16 13:01:36 -08001357 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001358 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1359 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001360 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001361
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001362 /* Store the scrypt of the intermediate key, so we can validate if it's a
1363 password error or mount error when things go wrong.
1364 Note there's no need to check for errors, since if this is incorrect, we
1365 simply won't wipe userdata, which is the correct default behavior
1366 */
1367 int N = 1 << crypt_ftr->N_factor;
1368 int r = 1 << crypt_ftr->r_factor;
1369 int p = 1 << crypt_ftr->p_factor;
1370
Paul Crowley14c8c072018-09-18 13:30:21 -07001371 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1372 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001373 sizeof(crypt_ftr->scrypted_intermediate_key));
1374
1375 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001376 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001377 }
1378
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001379 EVP_CIPHER_CTX_cleanup(&e_ctx);
1380
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001381 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001382}
1383
Paul Crowley14c8c072018-09-18 13:30:21 -07001384static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1385 const unsigned char* encrypted_master_key, size_t keysize,
1386 unsigned char* decrypted_master_key, kdf_func kdf,
1387 void* kdf_params, unsigned char** intermediate_key,
1388 size_t* intermediate_key_size) {
1389 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1390 EVP_CIPHER_CTX d_ctx;
1391 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001392
Paul Crowley14c8c072018-09-18 13:30:21 -07001393 /* Turn the password into an intermediate key and IV that can decrypt the
1394 master key */
1395 if (kdf(passwd, salt, ikey, kdf_params)) {
1396 SLOGE("kdf failed");
1397 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001398 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001399
Paul Crowley14c8c072018-09-18 13:30:21 -07001400 /* Initialize the decryption engine */
1401 EVP_CIPHER_CTX_init(&d_ctx);
1402 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1403 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1404 return -1;
1405 }
1406 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1407 /* Decrypt the master key */
1408 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1409 keysize)) {
1410 return -1;
1411 }
1412 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1413 return -1;
1414 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001415
Paul Crowley14c8c072018-09-18 13:30:21 -07001416 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1417 return -1;
1418 }
1419
1420 /* Copy intermediate key if needed by params */
1421 if (intermediate_key && intermediate_key_size) {
1422 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1423 if (*intermediate_key) {
1424 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1425 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1426 }
1427 }
1428
1429 EVP_CIPHER_CTX_cleanup(&d_ctx);
1430
1431 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001432}
1433
Paul Crowley14c8c072018-09-18 13:30:21 -07001434static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001435 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001436 *kdf = scrypt_keymaster;
1437 *kdf_params = ftr;
1438 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001439 *kdf = scrypt;
1440 *kdf_params = ftr;
1441 } else {
1442 *kdf = pbkdf2;
1443 *kdf_params = NULL;
1444 }
1445}
1446
Paul Crowley14c8c072018-09-18 13:30:21 -07001447static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1448 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1449 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001450 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001451 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001452 int ret;
1453
1454 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001455 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1456 decrypted_master_key, kdf, kdf_params, intermediate_key,
1457 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001458 if (ret != 0) {
1459 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001460 }
1461
1462 return ret;
1463}
1464
Paul Crowley14c8c072018-09-18 13:30:21 -07001465static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1466 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001467 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001468
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001469 /* Get some random bits for a key and salt */
1470 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1471 return -1;
1472 }
1473 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1474 return -1;
1475 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001476
1477 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001478 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001479}
1480
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001481static void ensure_subdirectory_unmounted(const char *prefix) {
1482 std::vector<std::string> umount_points;
1483 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
1484 if (!mnts) {
1485 SLOGW("could not read mount files");
1486 return;
1487 }
1488
1489 //Find sudirectory mount point
1490 mntent* mentry;
1491 std::string top_directory(prefix);
1492 if (!android::base::EndsWith(prefix, "/")) {
1493 top_directory = top_directory + "/";
1494 }
1495 while ((mentry = getmntent(mnts.get())) != nullptr) {
1496 if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
1497 continue;
1498 }
1499
1500 if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
1501 SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
1502 umount_points.push_back(mentry->mnt_dir);
1503 }
1504 }
1505
1506 //Sort by path length to umount longest path first
1507 std::sort(std::begin(umount_points), std::end(umount_points),
1508 [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
1509
1510 for (std::string& mount_point : umount_points) {
Eric Biggers89534302021-06-07 12:34:39 -07001511 SLOGW("unmounting sub-directory mount %s\n", mount_point.c_str());
1512 if (umount(mount_point.c_str()) != 0) {
1513 SLOGE("unmounting %s failed: %s\n", mount_point.c_str(), strerror(errno));
1514 }
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001515 }
1516}
1517
Eric Biggersb4faeb82021-05-10 17:44:34 -07001518static int wait_and_unmount(const char* mountpoint) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001519 int i, err, rc;
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001520
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001521#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001522
1523 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001524 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Eric Biggers89534302021-06-07 12:34:39 -07001525 // Subdirectory mount will cause a failure of umount.
1526 ensure_subdirectory_unmounted(mountpoint);
1527
Eric Biggers47525e62021-06-11 17:53:26 -07001528 SLOGD("unmounting mount %s\n", mountpoint);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001529 if (umount(mountpoint) == 0) {
1530 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001531 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001532
1533 if (errno == EINVAL) {
1534 /* EINVAL is returned if the directory is not a mountpoint,
1535 * i.e. there is no filesystem mounted there. So just get out.
1536 */
Eric Biggers47525e62021-06-11 17:53:26 -07001537 SLOGD("%s is not a mountpoint, nothing to do\n", mountpoint);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001538 break;
1539 }
1540
1541 err = errno;
Eric Biggers47525e62021-06-11 17:53:26 -07001542 SLOGW("unmounting mount %s failed: %s\n", mountpoint, strerror(err));
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001543
Eric Biggersb4faeb82021-05-10 17:44:34 -07001544 // If it's taking too long, kill the processes with open files.
1545 //
1546 // Originally this logic was only a fail-safe, but now it's relied on to
1547 // kill certain processes that aren't stopped by init because they
1548 // aren't in the main or late_start classes. So to avoid waiting for
1549 // too long, we now are fairly aggressive in starting to kill processes.
1550 static_assert(WAIT_UNMOUNT_COUNT >= 4);
1551 if (i == 2) {
1552 SLOGW("sending SIGTERM to processes with open files\n");
1553 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
1554 } else if (i >= 3) {
1555 SLOGW("sending SIGKILL to processes with open files\n");
1556 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001557 }
1558
1559 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001560 }
1561
1562 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001563 SLOGD("unmounting %s succeeded\n", mountpoint);
1564 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001565 } else {
Eric Biggers47525e62021-06-11 17:53:26 -07001566 SLOGE("too many retries -- giving up unmounting %s\n", mountpoint);
Paul Crowley14c8c072018-09-18 13:30:21 -07001567 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Paul Crowley14c8c072018-09-18 13:30:21 -07001568 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569 }
1570
1571 return rc;
1572}
1573
Paul Crowley14c8c072018-09-18 13:30:21 -07001574static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001575 // NOTE: post_fs_data results in init calling back around to vold, so all
1576 // callers to this method must be async
1577
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001578 /* Do the prep of the /data filesystem */
1579 property_set("vold.post_fs_data_done", "0");
1580 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001581 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001582
Ken Sumrallc5872692013-05-14 15:26:31 -07001583 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001584 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001585 /* We timed out to prep /data in time. Continue wait. */
1586 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001587 }
Wei Wang42e38102017-06-07 10:46:12 -07001588 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001589}
1590
Paul Crowley14c8c072018-09-18 13:30:21 -07001591static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001592 // Mark the footer as bad
1593 struct crypt_mnt_ftr crypt_ftr;
1594 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1595 SLOGE("Failed to get crypto footer - panic");
1596 return;
1597 }
1598
1599 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1600 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1601 SLOGE("Failed to set crypto footer - panic");
1602 return;
1603 }
1604}
1605
Paul Crowley14c8c072018-09-18 13:30:21 -07001606static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001607 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001608 SLOGE("Failed to mount tmpfs on data - panic");
1609 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001610 }
1611
1612 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1613 SLOGE("Failed to trigger post fs data - panic");
1614 return;
1615 }
1616
1617 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1618 SLOGE("Failed to trigger restart min framework - panic");
1619 return;
1620 }
1621}
1622
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001623/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001624static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001625 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001626 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001627 static int restart_successful = 0;
1628
1629 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001630 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001631 SLOGE("Encrypted filesystem not validated, aborting");
1632 return -1;
1633 }
1634
1635 if (restart_successful) {
1636 SLOGE("System already restarted with encrypted disk, aborting");
1637 return -1;
1638 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001639
Paul Lawrencef4faa572014-01-29 13:31:03 -08001640 if (restart_main) {
1641 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001642 * start all services in one of these classes: core, early_hal, hal,
1643 * main and late_start. To get to the minimal UI for PIN entry, we
1644 * need to start core, early_hal, hal and main. When we want to
1645 * shutdown the framework again, we need to stop most of the services in
1646 * these classes, but only those services that were started after
1647 * /data was mounted. This excludes critical services like vold and
1648 * ueventd, which need to keep running. We could possible stop
1649 * even fewer services, but because we want services to pick up APEX
1650 * libraries from the real /data, restarting is better, as it makes
1651 * these devices consistent with FBE devices and lets them use the
1652 * most recent code.
1653 *
1654 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001655 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001656 * We then restart the class core, hal, main, and also the class
1657 * late_start.
1658 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001659 * At the moment, I've only put a few things in late_start that I know
1660 * are not needed to bring up the framework, and that also cause problems
1661 * with unmounting the tmpfs /data, but I hope to add add more services
1662 * to the late_start class as we optimize this to decrease the delay
1663 * till the user is asked for the password to the filesystem.
1664 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001665
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001666 /* The init files are setup to stop the right set of services when
1667 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001668 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001669 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001670 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001671
Paul Lawrencef4faa572014-01-29 13:31:03 -08001672 /* Ugh, shutting down the framework is not synchronous, so until it
1673 * can be fixed, this horrible hack will wait a moment for it all to
1674 * shut down before proceeding. Without it, some devices cannot
1675 * restart the graphics services.
1676 */
1677 sleep(2);
1678 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001679
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001680 /* Now that the framework is shutdown, we should be able to umount()
1681 * the tmpfs filesystem, and mount the real one.
1682 */
1683
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001684 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1685 if (strlen(crypto_blkdev) == 0) {
1686 SLOGE("fs_crypto_blkdev not set\n");
1687 return -1;
1688 }
1689
Eric Biggersb4faeb82021-05-10 17:44:34 -07001690 if (!(rc = wait_and_unmount(DATA_MNT_POINT))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001691 /* If ro.crypto.readonly is set to 1, mount the decrypted
1692 * filesystem readonly. This is used when /data is mounted by
1693 * recovery mode.
1694 */
1695 char ro_prop[PROPERTY_VALUE_MAX];
1696 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001697 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001698 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1699 if (entry != nullptr) {
1700 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001701 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001702 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001703
Ken Sumralle5032c42012-04-01 23:58:44 -07001704 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001705 int retries = RETRY_MOUNT_ATTEMPTS;
1706 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001707
1708 /*
1709 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1710 * partitions in the fsck domain.
1711 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001712 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001713 SLOGE("Failed to setexeccon");
1714 return -1;
1715 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001716 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001717 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Paul Lawrence3fe93112020-06-12 08:12:48 -07001718 needs_cp, false)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001719 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1720 /* TODO: invoke something similar to
1721 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1722 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001723 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001724 if (--retries) {
1725 sleep(RETRY_MOUNT_DELAY_SECONDS);
1726 } else {
1727 /* Let's hope that a reboot clears away whatever is keeping
1728 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001729 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001730 }
1731 } else {
1732 SLOGE("Failed to mount decrypted data");
1733 cryptfs_set_corrupt();
1734 cryptfs_trigger_restart_min_framework();
1735 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001736 if (setexeccon(NULL)) {
1737 SLOGE("Failed to setexeccon");
1738 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001739 return -1;
1740 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001741 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001742 if (setexeccon(NULL)) {
1743 SLOGE("Failed to setexeccon");
1744 return -1;
1745 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001746
Ken Sumralle5032c42012-04-01 23:58:44 -07001747 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001748 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001749 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001750
1751 /* startup service classes main and late_start */
1752 property_set("vold.decrypt", "trigger_restart_framework");
1753 SLOGD("Just triggered restart_framework\n");
1754
1755 /* Give it a few moments to get started */
1756 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001757 }
1758
Ken Sumrall0cc16632011-01-18 20:32:26 -08001759 if (rc == 0) {
1760 restart_successful = 1;
1761 }
1762
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001763 return rc;
1764}
1765
Paul Crowley14c8c072018-09-18 13:30:21 -07001766int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001767 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001768 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001769 SLOGE("cryptfs_restart not valid for file encryption:");
1770 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001771 }
1772
Paul Lawrencef4faa572014-01-29 13:31:03 -08001773 /* Call internal implementation forcing a restart of main service group */
1774 return cryptfs_restart_internal(1);
1775}
1776
Paul Crowley14c8c072018-09-18 13:30:21 -07001777static int do_crypto_complete(const char* mount_point) {
1778 struct crypt_mnt_ftr crypt_ftr;
1779 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001780
Paul Crowley14c8c072018-09-18 13:30:21 -07001781 property_get("ro.crypto.state", encrypted_state, "");
1782 if (strcmp(encrypted_state, "encrypted")) {
1783 SLOGE("not running with encryption, aborting");
1784 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001785 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001786
Paul Crowley14c8c072018-09-18 13:30:21 -07001787 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001788 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001789 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1790 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001791
Paul Crowley14c8c072018-09-18 13:30:21 -07001792 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001793 std::string key_loc;
1794 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001795
Paul Crowley14c8c072018-09-18 13:30:21 -07001796 /*
1797 * Only report this error if key_loc is a file and it exists.
1798 * If the device was never encrypted, and /data is not mountable for
1799 * some reason, returning 1 should prevent the UI from presenting the
1800 * a "enter password" screen, or worse, a "press button to wipe the
1801 * device" screen.
1802 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001803 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001804 SLOGE("master key file does not exist, aborting");
1805 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1806 } else {
1807 SLOGE("Error getting crypt footer and key\n");
1808 return CRYPTO_COMPLETE_BAD_METADATA;
1809 }
1810 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001811
Paul Crowley14c8c072018-09-18 13:30:21 -07001812 // Test for possible error flags
1813 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1814 SLOGE("Encryption process is partway completed\n");
1815 return CRYPTO_COMPLETE_PARTIAL;
1816 }
1817
1818 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1819 SLOGE("Encryption process was interrupted but cannot continue\n");
1820 return CRYPTO_COMPLETE_INCONSISTENT;
1821 }
1822
1823 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1824 SLOGE("Encryption is successful but data is corrupt\n");
1825 return CRYPTO_COMPLETE_CORRUPT;
1826 }
1827
1828 /* We passed the test! We shall diminish, and return to the west */
1829 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001830}
1831
Paul Crowley14c8c072018-09-18 13:30:21 -07001832static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1833 const char* mount_point, const char* label) {
1834 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001835 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001836 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001837 char tmp_mount_point[64];
1838 unsigned int orig_failed_decrypt_count;
1839 int rc;
Paul Crowley14c8c072018-09-18 13:30:21 -07001840 int upgrade = 0;
1841 unsigned char* intermediate_key = 0;
1842 size_t intermediate_key_size = 0;
1843 int N = 1 << crypt_ftr->N_factor;
1844 int r = 1 << crypt_ftr->r_factor;
1845 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001846
Paul Crowley14c8c072018-09-18 13:30:21 -07001847 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1848 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001849
Paul Crowley14c8c072018-09-18 13:30:21 -07001850 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1851 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1852 &intermediate_key_size)) {
1853 SLOGE("Failed to decrypt master key\n");
1854 rc = -1;
1855 goto errout;
1856 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001857 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001858
Tom Cherry4c5bde22019-01-29 14:34:01 -08001859 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001860
Paul Crowley14c8c072018-09-18 13:30:21 -07001861 // Create crypto block device - all (non fatal) code paths
1862 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001863 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001864 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001865 SLOGE("Error creating decrypted block device\n");
1866 rc = -1;
1867 goto errout;
1868 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001869
Paul Crowley14c8c072018-09-18 13:30:21 -07001870 /* Work out if the problem is the password or the data */
1871 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001872
Paul Crowley14c8c072018-09-18 13:30:21 -07001873 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1874 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1875 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001876
Paul Crowley14c8c072018-09-18 13:30:21 -07001877 // Does the key match the crypto footer?
1878 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1879 sizeof(scrypted_intermediate_key)) == 0) {
1880 SLOGI("Password matches");
1881 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001882 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001883 /* Try mounting the file system anyway, just in case the problem's with
1884 * the footer, not the key. */
1885 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1886 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001887 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1888 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001889 SLOGE("Error temp mounting decrypted block device\n");
1890 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001891
Paul Crowley14c8c072018-09-18 13:30:21 -07001892 rc = ++crypt_ftr->failed_decrypt_count;
1893 put_crypt_ftr_and_key(crypt_ftr);
1894 } else {
1895 /* Success! */
1896 SLOGI("Password did not match but decrypted drive mounted - continue");
1897 umount(tmp_mount_point);
1898 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001899 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001900 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001901
Paul Crowley14c8c072018-09-18 13:30:21 -07001902 if (rc == 0) {
1903 crypt_ftr->failed_decrypt_count = 0;
1904 if (orig_failed_decrypt_count != 0) {
1905 put_crypt_ftr_and_key(crypt_ftr);
1906 }
1907
1908 /* Save the name of the crypto block device
1909 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001910 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001911
1912 /* Also save a the master key so we can reencrypted the key
1913 * the key when we want to change the password on it. */
1914 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1915 saved_mount_point = strdup(mount_point);
1916 master_key_saved = 1;
1917 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1918 rc = 0;
1919
1920 // Upgrade if we're not using the latest KDF.
Satya Tangirala23452c12021-03-22 23:29:15 -07001921 if (crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001922 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1923 upgrade = 1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001924 }
1925
1926 if (upgrade) {
1927 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1928 crypt_ftr->master_key, crypt_ftr);
1929 if (!rc) {
1930 rc = put_crypt_ftr_and_key(crypt_ftr);
1931 }
1932 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1933
1934 // Do not fail even if upgrade failed - machine is bootable
1935 // Note that if this code is ever hit, there is a *serious* problem
1936 // since KDFs should never fail. You *must* fix the kdf before
1937 // proceeding!
1938 if (rc) {
1939 SLOGW(
1940 "Upgrade failed with error %d,"
1941 " but continuing with previous state",
1942 rc);
1943 rc = 0;
1944 }
1945 }
1946 }
1947
1948errout:
1949 if (intermediate_key) {
1950 memset(intermediate_key, 0, intermediate_key_size);
1951 free(intermediate_key);
1952 }
1953 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001954}
1955
Ken Sumrall29d8da82011-05-18 17:20:07 -07001956/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001957 * Called by vold when it's asked to mount an encrypted external
1958 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001959 * as any metadata is been stored in a separate, small partition. We
1960 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001961 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001962int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001963 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08001964 auto crypto_type = get_crypto_type();
1965 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08001966 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08001967 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001968 return -1;
1969 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001970 uint64_t nr_sec = 0;
1971 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001972 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001973 return -1;
1974 }
1975
Jeff Sharkey9c484982015-03-31 10:35:33 -07001976 struct crypt_mnt_ftr ext_crypt_ftr;
1977 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1978 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08001979 ext_crypt_ftr.keysize = crypto_type.get_keysize();
1980 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001981 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001982 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001983 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001984 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1985 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001986
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001987 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1988 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001989}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001990
Paul Crowley14c8c072018-09-18 13:30:21 -07001991int cryptfs_crypto_complete(void) {
1992 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001993}
1994
Paul Crowley14c8c072018-09-18 13:30:21 -07001995int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001996 char encrypted_state[PROPERTY_VALUE_MAX];
1997 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001998 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1999 SLOGE(
2000 "encrypted fs already validated or not running with encryption,"
2001 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002002 return -1;
2003 }
2004
2005 if (get_crypt_ftr_and_key(crypt_ftr)) {
2006 SLOGE("Error getting crypt footer and key");
2007 return -1;
2008 }
2009
2010 return 0;
2011}
2012
Paul Crowley14c8c072018-09-18 13:30:21 -07002013int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002014 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002015 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002016 SLOGE("cryptfs_check_passwd not valid for file encryption");
2017 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002018 }
2019
Paul Lawrencef4faa572014-01-29 13:31:03 -08002020 struct crypt_mnt_ftr crypt_ftr;
2021 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002022
Paul Lawrencef4faa572014-01-29 13:31:03 -08002023 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002024 if (rc) {
2025 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002026 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002027 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002028
Paul Crowley14c8c072018-09-18 13:30:21 -07002029 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002030 if (rc) {
2031 SLOGE("Password did not match");
2032 return rc;
2033 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002034
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002035 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2036 // Here we have a default actual password but a real password
2037 // we must test against the scrypted value
2038 // First, we must delete the crypto block device that
2039 // test_mount_encrypted_fs leaves behind as a side effect
2040 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002041 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2042 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002043 if (rc) {
2044 SLOGE("Default password did not match on reboot encryption");
2045 return rc;
2046 }
2047
2048 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2049 put_crypt_ftr_and_key(&crypt_ftr);
2050 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2051 if (rc) {
2052 SLOGE("Could not change password on reboot encryption");
2053 return rc;
2054 }
2055 }
2056
2057 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002058 cryptfs_clear_password();
2059 password = strdup(passwd);
2060 struct timespec now;
2061 clock_gettime(CLOCK_BOOTTIME, &now);
2062 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002063 }
2064
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002065 return rc;
2066}
2067
Paul Crowley14c8c072018-09-18 13:30:21 -07002068int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002069 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002070 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002071 char encrypted_state[PROPERTY_VALUE_MAX];
2072 int rc;
2073
2074 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002075 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002076 SLOGE("device not encrypted, aborting");
2077 return -2;
2078 }
2079
2080 if (!master_key_saved) {
2081 SLOGE("encrypted fs not yet mounted, aborting");
2082 return -1;
2083 }
2084
2085 if (!saved_mount_point) {
2086 SLOGE("encrypted fs failed to save mount point, aborting");
2087 return -1;
2088 }
2089
Ken Sumrall160b4d62013-04-22 12:15:39 -07002090 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002091 SLOGE("Error getting crypt footer and key\n");
2092 return -1;
2093 }
2094
2095 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2096 /* If the device has no password, then just say the password is valid */
2097 rc = 0;
2098 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002099 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002100 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2101 /* They match, the password is correct */
2102 rc = 0;
2103 } else {
2104 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2105 sleep(1);
2106 rc = 1;
2107 }
2108 }
2109
2110 return rc;
2111}
2112
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002113/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08002114 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002115 * Presumably, at a minimum, the caller will update the
2116 * filesystem size and crypto_type_name after calling this function.
2117 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002118static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002119 off64_t off;
2120
2121 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002122 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002123 ftr->major_version = CURRENT_MAJOR_VERSION;
2124 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002125 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002126 ftr->keysize = get_crypto_type().get_keysize();
Satya Tangirala23452c12021-03-22 23:29:15 -07002127 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002128
Kenny Rootc4c70f12013-06-14 12:11:38 -07002129 get_device_scrypt_params(ftr);
2130
Ken Sumrall160b4d62013-04-22 12:15:39 -07002131 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2132 if (get_crypt_ftr_info(NULL, &off) == 0) {
2133 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002134 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002135 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002136
2137 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002138}
2139
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002140#define FRAMEWORK_BOOT_WAIT 60
2141
Paul Crowleyb64933a2017-10-31 08:25:55 -07002142static int vold_unmountAll(void) {
2143 VolumeManager* vm = VolumeManager::Instance();
2144 return vm->unmountAll();
2145}
2146
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002147int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002148 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002149 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002150 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002151 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002152 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002153 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002154 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002155 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002156 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002157 int num_vols;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002158 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002159 bool onlyCreateHeader = false;
Kalesh Singh98062dc2021-02-22 15:10:45 -05002160
2161 /* Get a wakelock as this may take a while, and we don't want the
2162 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2163 * wants to keep the screen on, it can grab a full wakelock.
2164 */
2165 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
2166 auto wl = android::wakelock::WakeLock::tryGet(lockid);
2167 if (!wl.has_value()) {
2168 return android::UNEXPECTED_NULL;
2169 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002170
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002171 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Eric Biggersc01995e2020-11-03 14:11:00 -08002172 if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002173 if (!check_ftr_sha(&crypt_ftr)) {
2174 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2175 put_crypt_ftr_and_key(&crypt_ftr);
2176 goto error_unencrypted;
2177 }
2178
2179 /* Doing a reboot-encryption*/
2180 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2181 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2182 rebootEncryption = true;
2183 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002184 } else {
2185 // We don't want to accidentally reference invalid data.
2186 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002187 }
2188
2189 property_get("ro.crypto.state", encrypted_state, "");
Eric Biggersc01995e2020-11-03 14:11:00 -08002190 if (!strcmp(encrypted_state, "encrypted")) {
Paul Lawrence87999172014-02-20 12:21:31 -08002191 SLOGE("Device is already running encrypted, aborting");
2192 goto error_unencrypted;
2193 }
2194
Tom Cherry4c5bde22019-01-29 14:34:01 -08002195 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002196
Ken Sumrall3ed82362011-01-28 23:31:16 -08002197 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002198 uint64_t nr_sec;
2199 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002200 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002201 goto error_unencrypted;
2202 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002203
2204 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002205 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002206 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002207 fs_size_sec = get_fs_size(real_blkdev.c_str());
2208 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002209
Paul Lawrence87999172014-02-20 12:21:31 -08002210 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002211
2212 if (fs_size_sec > max_fs_size_sec) {
2213 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2214 goto error_unencrypted;
2215 }
2216 }
2217
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002218 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002219 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002220 */
2221 property_set("vold.decrypt", "trigger_shutdown_framework");
2222 SLOGD("Just asked init to shut down class main\n");
2223
Jeff Sharkey9c484982015-03-31 10:35:33 -07002224 /* Ask vold to unmount all devices that it manages */
2225 if (vold_unmountAll()) {
2226 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002227 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002228
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002229 /* no_ui means we are being called from init, not settings.
2230 Now we always reboot from settings, so !no_ui means reboot
2231 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002232 if (!no_ui) {
2233 /* Try fallback, which is to reboot and try there */
2234 onlyCreateHeader = true;
2235 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2236 if (breadcrumb == 0) {
2237 SLOGE("Failed to create breadcrumb file");
2238 goto error_shutting_down;
2239 }
2240 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002241 }
2242
2243 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002244 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002245 /* Now that /data is unmounted, we need to mount a tmpfs
2246 * /data, set a property saying we're doing inplace encryption,
2247 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002248 */
Eric Biggersb4faeb82021-05-10 17:44:34 -07002249 wait_and_unmount(DATA_MNT_POINT);
Ken Sumralle5032c42012-04-01 23:58:44 -07002250 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002251 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002252 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002253 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002254 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002255
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002256 /* restart the framework. */
2257 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002258 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002259
Ken Sumrall92736ef2012-10-17 20:57:14 -07002260 /* Ugh, shutting down the framework is not synchronous, so until it
2261 * can be fixed, this horrible hack will wait a moment for it all to
2262 * shut down before proceeding. Without it, some devices cannot
2263 * restart the graphics services.
2264 */
2265 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002266 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002267
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002268 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002269 /* Initialize a crypt_mnt_ftr for the partition */
Eric Biggersc01995e2020-11-03 14:11:00 -08002270 if (!rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002271 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2272 goto error_shutting_down;
2273 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002274
Tom Cherry4c5bde22019-01-29 14:34:01 -08002275 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002276 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002277 } else {
2278 crypt_ftr.fs_size = nr_sec;
2279 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002280 /* At this point, we are in an inconsistent state. Until we successfully
2281 complete encryption, a reboot will leave us broken. So mark the
2282 encryption failed in case that happens.
2283 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002284 if (onlyCreateHeader) {
2285 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2286 } else {
2287 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2288 }
Paul Lawrence87999172014-02-20 12:21:31 -08002289 crypt_ftr.crypt_type = crypt_type;
Paul Crowley220567c2020-02-07 12:45:20 -08002290 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002291 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002292
Paul Lawrence87999172014-02-20 12:21:31 -08002293 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002294 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2295 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002296 SLOGE("Cannot create encrypted master key\n");
2297 goto error_shutting_down;
2298 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002299
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002300 /* Replace scrypted intermediate key if we are preparing for a reboot */
2301 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002302 unsigned char fake_master_key[MAX_KEY_LEN];
2303 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002304 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002305 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2306 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002307 }
2308
Paul Lawrence87999172014-02-20 12:21:31 -08002309 /* Write the key to the end of the partition */
2310 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002311
Paul Lawrence87999172014-02-20 12:21:31 -08002312 /* If any persistent data has been remembered, save it.
2313 * If none, create a valid empty table and save that.
2314 */
2315 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002316 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2317 if (pdata) {
2318 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2319 persist_data = pdata;
2320 }
Paul Lawrence87999172014-02-20 12:21:31 -08002321 }
2322 if (persist_data) {
2323 save_persistent_data();
2324 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002325 }
2326
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002327 if (onlyCreateHeader) {
2328 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002329 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002330 }
2331
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002332 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002333 /* startup service classes main and late_start */
2334 property_set("vold.decrypt", "trigger_restart_min_framework");
2335 SLOGD("Just triggered restart_min_framework\n");
2336
2337 /* OK, the framework is restarted and will soon be showing a
2338 * progress bar. Time to setup an encrypted mapping, and
2339 * either write a new filesystem, or encrypt in place updating
2340 * the progress bar as we work.
2341 */
2342 }
2343
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002344 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Eric Biggers88f993b2020-11-03 14:11:00 -08002345 rc = create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(),
2346 &crypto_blkdev, CRYPTO_BLOCK_DEVICE, 0);
2347 if (!rc) {
Eric Biggersf038c5f2020-11-03 14:11:02 -08002348 if (encrypt_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size, true)) {
2349 crypt_ftr.encrypted_upto = crypt_ftr.fs_size;
2350 rc = 0;
2351 } else {
2352 rc = -1;
2353 }
Eric Biggers88f993b2020-11-03 14:11:00 -08002354 /* Undo the dm-crypt mapping whether we succeed or not */
2355 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2356 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002357
Paul Crowley14c8c072018-09-18 13:30:21 -07002358 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002359 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002360 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002361
Paul Lawrence6bfed202014-07-28 12:47:22 -07002362 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002363
Eric Biggersc01995e2020-11-03 14:11:00 -08002364 char value[PROPERTY_VALUE_MAX];
2365 property_get("ro.crypto.state", value, "");
2366 if (!strcmp(value, "")) {
2367 /* default encryption - continue first boot sequence */
2368 property_set("ro.crypto.state", "encrypted");
2369 property_set("ro.crypto.type", "block");
Kalesh Singh98062dc2021-02-22 15:10:45 -05002370 wl.reset();
Eric Biggersc01995e2020-11-03 14:11:00 -08002371 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2372 // Bring up cryptkeeper that will check the password and set it
2373 property_set("vold.decrypt", "trigger_shutdown_framework");
2374 sleep(2);
2375 property_set("vold.encrypt_progress", "");
2376 cryptfs_trigger_restart_min_framework();
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002377 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002378 cryptfs_check_passwd(DEFAULT_PASSWORD);
2379 cryptfs_restart_internal(1);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002380 }
Eric Biggersc01995e2020-11-03 14:11:00 -08002381 return 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002382 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002383 sleep(2); /* Give the UI a chance to show 100% progress */
2384 cryptfs_reboot(RebootType::reboot);
Paul Lawrence87999172014-02-20 12:21:31 -08002385 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002386 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002387 char value[PROPERTY_VALUE_MAX];
2388
Ken Sumrall319369a2012-06-27 16:30:18 -07002389 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002390 if (!strcmp(value, "1")) {
2391 /* wipe data if encryption failed */
2392 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002393 std::string err;
2394 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002395 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002396 if (!write_bootloader_message(options, &err)) {
2397 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002398 }
Josh Gaofec44372017-08-28 13:22:55 -07002399 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002400 } else {
2401 /* set property to trigger dialog */
2402 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002403 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002404 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002405 }
2406
Ken Sumrall3ed82362011-01-28 23:31:16 -08002407 /* hrm, the encrypt step claims success, but the reboot failed.
2408 * This should not happen.
2409 * Set the property and return. Hope the framework can deal with it.
2410 */
2411 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002412 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002413
2414error_unencrypted:
2415 property_set("vold.encrypt_progress", "error_not_encrypted");
2416 return -1;
2417
2418error_shutting_down:
2419 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2420 * but the framework is stopped and not restarted to show the error, so it's up to
2421 * vold to restart the system.
2422 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002423 SLOGE(
2424 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2425 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002426 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002427
2428 /* shouldn't get here */
2429 property_set("vold.encrypt_progress", "error_shutting_down");
2430 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002431}
2432
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002433int cryptfs_enable(int type, const char* passwd, int no_ui) {
2434 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002435}
2436
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002437int cryptfs_enable_default(int no_ui) {
2438 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002439}
2440
Paul Crowley14c8c072018-09-18 13:30:21 -07002441int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002442 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002443 SLOGE("cryptfs_changepw not valid for file encryption");
2444 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002445 }
2446
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002447 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002448 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002449
2450 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002451 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002452 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002453 return -1;
2454 }
2455
Paul Lawrencef4faa572014-01-29 13:31:03 -08002456 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2457 SLOGE("Invalid crypt_type %d", crypt_type);
2458 return -1;
2459 }
2460
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002461 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002462 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002463 SLOGE("Error getting crypt footer and key");
2464 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002465 }
2466
Paul Lawrencef4faa572014-01-29 13:31:03 -08002467 crypt_ftr.crypt_type = crypt_type;
2468
Paul Crowley14c8c072018-09-18 13:30:21 -07002469 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2470 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002471 if (rc) {
2472 SLOGE("Encrypt master key failed: %d", rc);
2473 return -1;
2474 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002475 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002476 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002477
2478 return 0;
2479}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002480
Rubin Xu85c01f92014-10-13 12:49:54 +01002481static unsigned int persist_get_max_entries(int encrypted) {
2482 struct crypt_mnt_ftr crypt_ftr;
2483 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002484
2485 /* If encrypted, use the values from the crypt_ftr, otherwise
2486 * use the values for the current spec.
2487 */
2488 if (encrypted) {
2489 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002490 /* Something is wrong, assume no space for entries */
2491 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002492 }
2493 dsize = crypt_ftr.persist_data_size;
2494 } else {
2495 dsize = CRYPT_PERSIST_DATA_SIZE;
2496 }
2497
Rubin Xuf83cc612018-10-09 16:13:38 +01002498 if (dsize > sizeof(struct crypt_persist_data)) {
2499 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2500 } else {
2501 return 0;
2502 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002503}
2504
Paul Crowley14c8c072018-09-18 13:30:21 -07002505static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002506 unsigned int i;
2507
2508 if (persist_data == NULL) {
2509 return -1;
2510 }
2511 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2512 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2513 /* We found it! */
2514 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2515 return 0;
2516 }
2517 }
2518
2519 return -1;
2520}
2521
Paul Crowley14c8c072018-09-18 13:30:21 -07002522static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002523 unsigned int i;
2524 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002525 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002526
2527 if (persist_data == NULL) {
2528 return -1;
2529 }
2530
Rubin Xu85c01f92014-10-13 12:49:54 +01002531 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002532
2533 num = persist_data->persist_valid_entries;
2534
2535 for (i = 0; i < num; i++) {
2536 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2537 /* We found an existing entry, update it! */
2538 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2539 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2540 return 0;
2541 }
2542 }
2543
2544 /* We didn't find it, add it to the end, if there is room */
2545 if (persist_data->persist_valid_entries < max_persistent_entries) {
2546 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2547 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2548 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2549 persist_data->persist_valid_entries++;
2550 return 0;
2551 }
2552
2553 return -1;
2554}
2555
Rubin Xu85c01f92014-10-13 12:49:54 +01002556/**
2557 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2558 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2559 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002560int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002561 std::string key_ = key;
2562 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002563
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002564 std::string parsed_field;
2565 unsigned parsed_index;
2566
2567 std::string::size_type split = key_.find_last_of('_');
2568 if (split == std::string::npos) {
2569 parsed_field = key_;
2570 parsed_index = 0;
2571 } else {
2572 parsed_field = key_.substr(0, split);
2573 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002574 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002575
2576 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002577}
2578
2579/*
2580 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2581 * remaining entries starting from index will be deleted.
2582 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2583 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2584 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2585 *
2586 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002587static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002588 unsigned int i;
2589 unsigned int j;
2590 unsigned int num;
2591
2592 if (persist_data == NULL) {
2593 return PERSIST_DEL_KEY_ERROR_OTHER;
2594 }
2595
2596 num = persist_data->persist_valid_entries;
2597
Paul Crowley14c8c072018-09-18 13:30:21 -07002598 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002599 // Filter out to-be-deleted entries in place.
2600 for (i = 0; i < num; i++) {
2601 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2602 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2603 j++;
2604 }
2605 }
2606
2607 if (j < num) {
2608 persist_data->persist_valid_entries = j;
2609 // Zeroise the remaining entries
2610 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2611 return PERSIST_DEL_KEY_OK;
2612 } else {
2613 // Did not find an entry matching the given fieldname
2614 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2615 }
2616}
2617
Paul Crowley14c8c072018-09-18 13:30:21 -07002618static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002619 unsigned int i;
2620 unsigned int count;
2621
2622 if (persist_data == NULL) {
2623 return -1;
2624 }
2625
2626 count = 0;
2627 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2628 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2629 count++;
2630 }
2631 }
2632
2633 return count;
2634}
2635
Ken Sumrall160b4d62013-04-22 12:15:39 -07002636/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002637int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002638 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002639 SLOGE("Cannot get field when file encrypted");
2640 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002641 }
2642
Ken Sumrall160b4d62013-04-22 12:15:39 -07002643 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002644 /* CRYPTO_GETFIELD_OK is success,
2645 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2646 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2647 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002648 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002649 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2650 int i;
2651 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002652
2653 if (persist_data == NULL) {
2654 load_persistent_data();
2655 if (persist_data == NULL) {
2656 SLOGE("Getfield error, cannot load persistent data");
2657 goto out;
2658 }
2659 }
2660
Rubin Xu85c01f92014-10-13 12:49:54 +01002661 // Read value from persistent entries. If the original value is split into multiple entries,
2662 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002663 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002664 // 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 -07002665 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002666 // value too small
2667 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2668 goto out;
2669 }
2670 rc = CRYPTO_GETFIELD_OK;
2671
2672 for (i = 1; /* break explicitly */; i++) {
2673 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002674 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002675 // If the fieldname is very long, we stop as soon as it begins to overflow the
2676 // maximum field length. At this point we have in fact fully read out the original
2677 // value because cryptfs_setfield would not allow fields with longer names to be
2678 // written in the first place.
2679 break;
2680 }
2681 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002682 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2683 // value too small.
2684 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2685 goto out;
2686 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002687 } else {
2688 // Exhaust all entries.
2689 break;
2690 }
2691 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002692 } else {
2693 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002694 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002695 }
2696
2697out:
2698 return rc;
2699}
2700
2701/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002702int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002703 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002704 SLOGE("Cannot set field when file encrypted");
2705 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002706 }
2707
Ken Sumrall160b4d62013-04-22 12:15:39 -07002708 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002709 /* 0 is success, negative values are error */
2710 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002711 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002712 unsigned int field_id;
2713 char temp_field[PROPERTY_KEY_MAX];
2714 unsigned int num_entries;
2715 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002716
2717 if (persist_data == NULL) {
2718 load_persistent_data();
2719 if (persist_data == NULL) {
2720 SLOGE("Setfield error, cannot load persistent data");
2721 goto out;
2722 }
2723 }
2724
2725 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002726 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002727 encrypted = 1;
2728 }
2729
Rubin Xu85c01f92014-10-13 12:49:54 +01002730 // Compute the number of entries required to store value, each entry can store up to
2731 // (PROPERTY_VALUE_MAX - 1) chars
2732 if (strlen(value) == 0) {
2733 // Empty value also needs one entry to store.
2734 num_entries = 1;
2735 } else {
2736 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2737 }
2738
2739 max_keylen = strlen(fieldname);
2740 if (num_entries > 1) {
2741 // Need an extra "_%d" suffix.
2742 max_keylen += 1 + log10(num_entries);
2743 }
2744 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2745 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002746 goto out;
2747 }
2748
Rubin Xu85c01f92014-10-13 12:49:54 +01002749 // Make sure we have enough space to write the new value
2750 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2751 persist_get_max_entries(encrypted)) {
2752 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2753 goto out;
2754 }
2755
2756 // Now that we know persist_data has enough space for value, let's delete the old field first
2757 // to make up space.
2758 persist_del_keys(fieldname, 0);
2759
2760 if (persist_set_key(fieldname, value, encrypted)) {
2761 // fail to set key, should not happen as we have already checked the available space
2762 SLOGE("persist_set_key() error during setfield()");
2763 goto out;
2764 }
2765
2766 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002767 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002768
2769 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2770 // fail to set key, should not happen as we have already checked the available space.
2771 SLOGE("persist_set_key() error during setfield()");
2772 goto out;
2773 }
2774 }
2775
Ken Sumrall160b4d62013-04-22 12:15:39 -07002776 /* If we are running encrypted, save the persistent data now */
2777 if (encrypted) {
2778 if (save_persistent_data()) {
2779 SLOGE("Setfield error, cannot save persistent data");
2780 goto out;
2781 }
2782 }
2783
Rubin Xu85c01f92014-10-13 12:49:54 +01002784 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002785
2786out:
2787 return rc;
2788}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002789
2790/* Checks userdata. Attempt to mount the volume if default-
2791 * encrypted.
2792 * On success trigger next init phase and return 0.
2793 * Currently do not handle failure - see TODO below.
2794 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002795int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002796 int crypt_type = cryptfs_get_password_type();
2797 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2798 SLOGE("Bad crypt type - error");
2799 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002800 SLOGD(
2801 "Password is not default - "
2802 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002803 property_set("vold.decrypt", "trigger_restart_min_framework");
2804 return 0;
2805 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2806 SLOGD("Password is default - restarting filesystem");
2807 cryptfs_restart_internal(0);
2808 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002809 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002810 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002811 }
2812
Paul Lawrence6bfed202014-07-28 12:47:22 -07002813 /** Corrupt. Allow us to boot into framework, which will detect bad
2814 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002815 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002816 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002817 return 0;
2818}
2819
2820/* Returns type of the password, default, pattern, pin or password.
2821 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002822int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002823 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002824 SLOGE("cryptfs_get_password_type not valid for file encryption");
2825 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002826 }
2827
Paul Lawrencef4faa572014-01-29 13:31:03 -08002828 struct crypt_mnt_ftr crypt_ftr;
2829
2830 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2831 SLOGE("Error getting crypt footer and key\n");
2832 return -1;
2833 }
2834
Paul Lawrence6bfed202014-07-28 12:47:22 -07002835 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2836 return -1;
2837 }
2838
Paul Lawrencef4faa572014-01-29 13:31:03 -08002839 return crypt_ftr.crypt_type;
2840}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002841
Paul Crowley14c8c072018-09-18 13:30:21 -07002842const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002843 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002844 SLOGE("cryptfs_get_password not valid for file encryption");
2845 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002846 }
2847
Paul Lawrence399317e2014-03-10 13:20:50 -07002848 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002849 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002850 if (now.tv_sec < password_expiry_time) {
2851 return password;
2852 } else {
2853 cryptfs_clear_password();
2854 return 0;
2855 }
2856}
2857
Paul Crowley14c8c072018-09-18 13:30:21 -07002858void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002859 if (password) {
2860 size_t len = strlen(password);
2861 memset(password, 0, len);
2862 free(password);
2863 password = 0;
2864 password_expiry_time = 0;
2865 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002866}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002867
Paul Crowley14c8c072018-09-18 13:30:21 -07002868int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002869 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2870 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002871}