blob: 403282e22bccae454d2e711b6c428bc52d44d799 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
Logan Chiend557d762018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
Daniel Rosenberg65f99c92018-08-28 01:58:49 -070027#include "Checkpoint.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070029#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080030#include "Keymaster.h"
31#include "Process.h"
32#include "ScryptParameters.h"
Paul Crowleycfe39722018-10-30 15:59:24 -070033#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080034#include "VoldUtil.h"
35#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080036
Eric Biggersed45ec32019-01-25 10:47:55 -080037#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080039#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080040#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070043#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070045#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070046#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070047#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080048#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080049#include <logwrap/logwrap.h>
50#include <openssl/evp.h>
51#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080052#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070053#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080054
55#include <ctype.h>
56#include <errno.h>
57#include <fcntl.h>
58#include <inttypes.h>
59#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080060#include <linux/kdev_t.h>
61#include <math.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080065#include <sys/mount.h>
66#include <sys/param.h>
67#include <sys/stat.h>
68#include <sys/types.h>
69#include <sys/wait.h>
70#include <time.h>
71#include <unistd.h>
72
Wei Wang4375f1b2017-02-24 17:43:01 -080073extern "C" {
74#include <crypto_scrypt.h>
75}
Mark Salyzyn3e971272014-01-21 13:27:04 -080076
Eric Biggersed45ec32019-01-25 10:47:55 -080077using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080078using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080079using android::fs_mgr::GetEntryForMountPoint;
David Andersonb9224732019-05-13 13:02:54 -070080using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070081using namespace std::chrono_literals;
82
Mark Salyzyn5eecc442014-02-12 14:16:14 -080083#define UNUSED __attribute__((unused))
84
Jason parks70a4b3f2011-01-28 10:10:47 -060085#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080086
87constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
88constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070089constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080090
91// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070092static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060093
Paul Crowley14c8c072018-09-18 13:30:21 -070094#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070095
Paul Lawrence3bd36d52015-06-09 13:37:44 -070096#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080097
Paul Lawrence3d99eba2015-11-20 07:07:19 -080098#define CRYPTO_BLOCK_DEVICE "userdata"
99
100#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
101
Ken Sumrall29d8da82011-05-18 17:20:07 -0700102#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700103#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700104
Ken Sumralle919efe2012-09-29 17:07:41 -0700105#define TABLE_LOAD_RETRIES 10
106
Shawn Willden47ba10d2014-09-03 17:07:06 -0600107#define RSA_KEY_SIZE 2048
108#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
109#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600110#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700111
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700112#define RETRY_MOUNT_ATTEMPTS 10
113#define RETRY_MOUNT_DELAY_SECONDS 1
114
Paul Crowley5afbc622017-11-27 09:42:17 -0800115#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
116
Paul Crowley73473332017-11-21 15:43:51 -0800117static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
118
Greg Kaiser59ad0182018-02-16 13:01:36 -0800119static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700120static char* saved_mount_point;
121static int master_key_saved = 0;
122static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800123
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700124/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700125static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000126 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700127}
128
129/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700130static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800131 if (ftr->keymaster_blob_size) {
132 SLOGI("Already have key");
133 return 0;
134 }
135
Paul Crowley14c8c072018-09-18 13:30:21 -0700136 int rc = keymaster_create_key_for_cryptfs_scrypt(
137 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
138 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000139 if (rc) {
140 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800141 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000142 ftr->keymaster_blob_size = 0;
143 }
144 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700145 return -1;
146 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000147 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700148}
149
Shawn Willdene17a9c42014-09-08 13:04:08 -0600150/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700151static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
152 const size_t object_size, unsigned char** signature,
153 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600154 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600155 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600156 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600157
Shawn Willdene17a9c42014-09-08 13:04:08 -0600158 // To sign a message with RSA, the message must satisfy two
159 // constraints:
160 //
161 // 1. The message, when interpreted as a big-endian numeric value, must
162 // be strictly less than the public modulus of the RSA key. Note
163 // that because the most significant bit of the public modulus is
164 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
165 // key), an n-bit message with most significant bit 0 always
166 // satisfies this requirement.
167 //
168 // 2. The message must have the same length in bits as the public
169 // modulus of the RSA key. This requirement isn't mathematically
170 // necessary, but is necessary to ensure consistency in
171 // implementations.
172 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600173 case KDF_SCRYPT_KEYMASTER:
174 // This ensures the most significant byte of the signed message
175 // is zero. We could have zero-padded to the left instead, but
176 // this approach is slightly more robust against changes in
177 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600178 // so) because we really should be using a proper deterministic
179 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800180 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600181 SLOGI("Signing safely-padded object");
182 break;
183 default:
184 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000185 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600186 }
Paul Crowley73473332017-11-21 15:43:51 -0800187 for (;;) {
188 auto result = keymaster_sign_object_for_cryptfs_scrypt(
189 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
190 to_sign_size, signature, signature_size);
191 switch (result) {
192 case KeymasterSignResult::ok:
193 return 0;
194 case KeymasterSignResult::upgrade:
195 break;
196 default:
197 return -1;
198 }
199 SLOGD("Upgrading key");
200 if (keymaster_upgrade_key_for_cryptfs_scrypt(
201 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
202 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
203 &ftr->keymaster_blob_size) != 0) {
204 SLOGE("Failed to upgrade key");
205 return -1;
206 }
207 if (put_crypt_ftr_and_key(ftr) != 0) {
208 SLOGE("Failed to write upgraded key to disk");
209 }
210 SLOGD("Key upgraded successfully");
211 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600212}
213
Paul Lawrence399317e2014-03-10 13:20:50 -0700214/* Store password when userdata is successfully decrypted and mounted.
215 * Cleared by cryptfs_clear_password
216 *
217 * To avoid a double prompt at boot, we need to store the CryptKeeper
218 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
219 * Since the entire framework is torn down and rebuilt after encryption,
220 * we have to use a daemon or similar to store the password. Since vold
221 * is secured against IPC except from system processes, it seems a reasonable
222 * place to store this.
223 *
224 * password should be cleared once it has been used.
225 *
226 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800227 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700228static char* password = 0;
229static int password_expiry_time = 0;
230static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800231
Paul Crowley14c8c072018-09-18 13:30:21 -0700232enum class RebootType { reboot, recovery, shutdown };
233static void cryptfs_reboot(RebootType rt) {
234 switch (rt) {
235 case RebootType::reboot:
236 property_set(ANDROID_RB_PROPERTY, "reboot");
237 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800238
Paul Crowley14c8c072018-09-18 13:30:21 -0700239 case RebootType::recovery:
240 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
241 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800242
Paul Crowley14c8c072018-09-18 13:30:21 -0700243 case RebootType::shutdown:
244 property_set(ANDROID_RB_PROPERTY, "shutdown");
245 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700246 }
Paul Lawrence87999172014-02-20 12:21:31 -0800247
Ken Sumralladfba362013-06-04 16:37:52 -0700248 sleep(20);
249
250 /* Shouldn't get here, reboot should happen before sleep times out */
251 return;
252}
253
Greg Kaiser38723f22018-02-16 13:35:35 -0800254namespace {
255
256struct CryptoType;
257
258// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700259const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800260
261struct CryptoType {
262 // We should only be constructing CryptoTypes as part of
263 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
264 // which isn't pure or fully protected as a concession to being able to
265 // do it all at compile time. Add new CryptoTypes in
266 // supported_crypto_types[] below.
267 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
268 constexpr CryptoType set_keysize(uint32_t size) const {
269 return CryptoType(this->property_name, this->crypto_name, size);
270 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700271 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800272 return CryptoType(property, this->crypto_name, this->keysize);
273 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700274 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800275 return CryptoType(this->property_name, crypto, this->keysize);
276 }
277
Paul Crowley14c8c072018-09-18 13:30:21 -0700278 constexpr const char* get_property_name() const { return property_name; }
279 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800280 constexpr uint32_t get_keysize() const { return keysize; }
281
Paul Crowley14c8c072018-09-18 13:30:21 -0700282 private:
283 const char* property_name;
284 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800285 uint32_t keysize;
286
Paul Crowley14c8c072018-09-18 13:30:21 -0700287 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800288 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700289 friend const CryptoType& get_crypto_type();
290 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800291};
292
293// We only want to parse this read-only property once. But we need to wait
294// until the system is initialized before we can read it. So we use a static
295// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700296const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800297 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
298 return crypto_type;
299}
300
301constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700302 .set_property_name("AES-128-CBC")
303 .set_crypto_name("aes-cbc-essiv:sha256")
304 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800305
306constexpr CryptoType supported_crypto_types[] = {
307 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800308 CryptoType()
309 .set_property_name("adiantum")
310 .set_crypto_name("xchacha12,aes-adiantum-plain64")
311 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800312 // Add new CryptoTypes here. Order is not important.
313};
314
Greg Kaiser38723f22018-02-16 13:35:35 -0800315// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
316// We confirm all supported_crypto_types have a small enough keysize and
317// had both set_property_name() and set_crypto_name() called.
318
319template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700320constexpr size_t array_length(T (&)[N]) {
321 return N;
322}
Greg Kaiser38723f22018-02-16 13:35:35 -0800323
324constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
325 return (index >= array_length(supported_crypto_types));
326}
327
Paul Crowley14c8c072018-09-18 13:30:21 -0700328constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800329 return ((crypto_type.get_property_name() != nullptr) &&
330 (crypto_type.get_crypto_name() != nullptr) &&
331 (crypto_type.get_keysize() <= MAX_KEY_LEN));
332}
333
334// Note in C++11 that constexpr functions can only have a single line.
335// So our code is a bit convoluted (using recursion instead of a loop),
336// but it's asserting at compile time that all of our key lengths are valid.
337constexpr bool validateSupportedCryptoTypes(size_t index) {
338 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700339 (isValidCryptoType(supported_crypto_types[index]) &&
340 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800341}
342
343static_assert(validateSupportedCryptoTypes(0),
344 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
345 "incompletely constructed.");
346// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
347
Greg Kaiser38723f22018-02-16 13:35:35 -0800348// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700349const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800350 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
351 char paramstr[PROPERTY_VALUE_MAX];
352
Paul Crowley14c8c072018-09-18 13:30:21 -0700353 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
354 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800355 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
356 return ctype;
357 }
358 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700359 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
360 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800361 return default_crypto_type;
362}
363
364} // namespace
365
Kenny Rootc4c70f12013-06-14 12:11:38 -0700366/**
367 * Gets the default device scrypt parameters for key derivation time tuning.
368 * The parameters should lead to about one second derivation time for the
369 * given device.
370 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700371static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700372 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000373 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700374
Paul Crowley63c18d32016-02-10 14:02:47 +0000375 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
376 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
377 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
378 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700379 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000380 ftr->N_factor = Nf;
381 ftr->r_factor = rf;
382 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700383}
384
Greg Kaiser57f9af62018-02-16 13:13:58 -0800385uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800386 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800387}
388
Paul Crowley14c8c072018-09-18 13:30:21 -0700389const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800390 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800391}
392
Tom Cherry4c5bde22019-01-29 14:34:01 -0800393static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800394 int fd, block_size;
395 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200396 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800397
Paul Crowley14c8c072018-09-18 13:30:21 -0700398 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800399 SLOGE("Cannot open device to get filesystem size ");
400 return 0;
401 }
402
403 if (lseek64(fd, 1024, SEEK_SET) < 0) {
404 SLOGE("Cannot seek to superblock");
405 return 0;
406 }
407
408 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
409 SLOGE("Cannot read superblock");
410 return 0;
411 }
412
413 close(fd);
414
Daniel Rosenberge82df162014-08-15 22:19:23 +0000415 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
416 SLOGE("Not a valid ext4 superblock");
417 return 0;
418 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800419 block_size = 1024 << sb.s_log_block_size;
420 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200421 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800422
423 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200424 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800425}
426
Tom Cherry4c5bde22019-01-29 14:34:01 -0800427static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
428 for (const auto& entry : fstab_default) {
429 if (!entry.fs_mgr_flags.vold_managed &&
430 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
431 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
432 if (key_loc != nullptr) {
433 *key_loc = entry.key_loc;
434 }
435 if (real_blk_device != nullptr) {
436 *real_blk_device = entry.blk_device;
437 }
438 return;
439 }
440 }
441}
442
Paul Crowley14c8c072018-09-18 13:30:21 -0700443static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
444 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200445 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700446 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700447 char key_loc[PROPERTY_VALUE_MAX];
448 char real_blkdev[PROPERTY_VALUE_MAX];
449 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700450
Paul Crowley14c8c072018-09-18 13:30:21 -0700451 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800452 std::string key_loc;
453 std::string real_blkdev;
454 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700455
Tom Cherry4c5bde22019-01-29 14:34:01 -0800456 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200457 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700458 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
459 * encryption info footer and key, and plenty of bytes to spare for future
460 * growth.
461 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800462 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200463 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700464 cached_data = 1;
465 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800466 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700467 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700468 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800469 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700470 cached_off = 0;
471 cached_data = 1;
472 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700473 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700474
Paul Crowley14c8c072018-09-18 13:30:21 -0700475 if (cached_data) {
476 if (metadata_fname) {
477 *metadata_fname = cached_metadata_fname;
478 }
479 if (off) {
480 *off = cached_off;
481 }
482 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700483 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700484
Paul Crowley14c8c072018-09-18 13:30:21 -0700485 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700486}
487
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800488/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700489static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800490 SHA256_CTX c;
491 SHA256_Init(&c);
492 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
493 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
494 SHA256_Final(crypt_ftr->sha256, &c);
495}
496
Ken Sumralle8744072011-01-18 22:01:55 -0800497/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800498 * update the failed mount count but not change the key.
499 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700500static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
501 int fd;
502 unsigned int cnt;
503 /* starting_off is set to the SEEK_SET offset
504 * where the crypto structure starts
505 */
506 off64_t starting_off;
507 int rc = -1;
508 char* fname = NULL;
509 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800510
Paul Crowley14c8c072018-09-18 13:30:21 -0700511 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800512
Paul Crowley14c8c072018-09-18 13:30:21 -0700513 if (get_crypt_ftr_info(&fname, &starting_off)) {
514 SLOGE("Unable to get crypt_ftr_info\n");
515 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800516 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700517 if (fname[0] != '/') {
518 SLOGE("Unexpected value for crypto key location\n");
519 return -1;
520 }
521 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
522 SLOGE("Cannot open footer file %s for put\n", fname);
523 return -1;
524 }
Ken Sumralle8744072011-01-18 22:01:55 -0800525
Paul Crowley14c8c072018-09-18 13:30:21 -0700526 /* Seek to the start of the crypt footer */
527 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
528 SLOGE("Cannot seek to real block device footer\n");
529 goto errout;
530 }
531
532 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
533 SLOGE("Cannot write real block device footer\n");
534 goto errout;
535 }
536
537 fstat(fd, &statbuf);
538 /* If the keys are kept on a raw block device, do not try to truncate it. */
539 if (S_ISREG(statbuf.st_mode)) {
540 if (ftruncate(fd, 0x4000)) {
541 SLOGE("Cannot set footer file size\n");
542 goto errout;
543 }
544 }
545
546 /* Success! */
547 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800548
549errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700550 close(fd);
551 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800552}
553
Paul Crowley14c8c072018-09-18 13:30:21 -0700554static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800555 struct crypt_mnt_ftr copy;
556 memcpy(&copy, crypt_ftr, sizeof(copy));
557 set_ftr_sha(&copy);
558 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
559}
560
Paul Crowley14c8c072018-09-18 13:30:21 -0700561static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700562 return TEMP_FAILURE_RETRY(read(fd, buff, len));
563}
564
Paul Crowley14c8c072018-09-18 13:30:21 -0700565static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700566 return TEMP_FAILURE_RETRY(write(fd, buff, len));
567}
568
Paul Crowley14c8c072018-09-18 13:30:21 -0700569static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700570 memset(pdata, 0, len);
571 pdata->persist_magic = PERSIST_DATA_MAGIC;
572 pdata->persist_valid_entries = 0;
573}
574
575/* A routine to update the passed in crypt_ftr to the lastest version.
576 * fd is open read/write on the device that holds the crypto footer and persistent
577 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
578 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
579 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700580static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700581 int orig_major = crypt_ftr->major_version;
582 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700583
Kenny Root7434b312013-06-14 11:29:53 -0700584 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700585 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700586 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700587
Kenny Rootc4c70f12013-06-14 12:11:38 -0700588 SLOGW("upgrading crypto footer to 1.1");
589
Paul Crowley14c8c072018-09-18 13:30:21 -0700590 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700591 if (pdata == NULL) {
592 SLOGE("Cannot allocate persisent data\n");
593 return;
594 }
595 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
596
597 /* Need to initialize the persistent data area */
598 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
599 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100600 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700601 return;
602 }
603 /* Write all zeros to the first copy, making it invalid */
604 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
605
606 /* Write a valid but empty structure to the second copy */
607 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
608 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
609
610 /* Update the footer */
611 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
612 crypt_ftr->persist_data_offset[0] = pdata_offset;
613 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
614 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100615 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700616 }
617
Paul Lawrencef4faa572014-01-29 13:31:03 -0800618 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700619 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800620 /* But keep the old kdf_type.
621 * It will get updated later to KDF_SCRYPT after the password has been verified.
622 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700623 crypt_ftr->kdf_type = KDF_PBKDF2;
624 get_device_scrypt_params(crypt_ftr);
625 crypt_ftr->minor_version = 2;
626 }
627
Paul Lawrencef4faa572014-01-29 13:31:03 -0800628 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
629 SLOGW("upgrading crypto footer to 1.3");
630 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
631 crypt_ftr->minor_version = 3;
632 }
633
Kenny Root7434b312013-06-14 11:29:53 -0700634 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
635 if (lseek64(fd, offset, SEEK_SET) == -1) {
636 SLOGE("Cannot seek to crypt footer\n");
637 return;
638 }
639 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700640 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700641}
642
Paul Crowley14c8c072018-09-18 13:30:21 -0700643static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
644 int fd;
645 unsigned int cnt;
646 off64_t starting_off;
647 int rc = -1;
648 char* fname = NULL;
649 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700650
Paul Crowley14c8c072018-09-18 13:30:21 -0700651 if (get_crypt_ftr_info(&fname, &starting_off)) {
652 SLOGE("Unable to get crypt_ftr_info\n");
653 return -1;
654 }
655 if (fname[0] != '/') {
656 SLOGE("Unexpected value for crypto key location\n");
657 return -1;
658 }
659 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
660 SLOGE("Cannot open footer file %s for get\n", fname);
661 return -1;
662 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800663
Paul Crowley14c8c072018-09-18 13:30:21 -0700664 /* Make sure it's 16 Kbytes in length */
665 fstat(fd, &statbuf);
666 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
667 SLOGE("footer file %s is not the expected size!\n", fname);
668 goto errout;
669 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700670
Paul Crowley14c8c072018-09-18 13:30:21 -0700671 /* Seek to the start of the crypt footer */
672 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
673 SLOGE("Cannot seek to real block device footer\n");
674 goto errout;
675 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700676
Paul Crowley14c8c072018-09-18 13:30:21 -0700677 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
678 SLOGE("Cannot read real block device footer\n");
679 goto errout;
680 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800681
Paul Crowley14c8c072018-09-18 13:30:21 -0700682 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
683 SLOGE("Bad magic for real block device %s\n", fname);
684 goto errout;
685 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800686
Paul Crowley14c8c072018-09-18 13:30:21 -0700687 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
688 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
689 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
690 goto errout;
691 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800692
Paul Crowley14c8c072018-09-18 13:30:21 -0700693 // We risk buffer overflows with oversized keys, so we just reject them.
694 // 0-sized keys are problematic (essentially by-passing encryption), and
695 // AES-CBC key wrapping only works for multiples of 16 bytes.
696 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
697 (crypt_ftr->keysize > MAX_KEY_LEN)) {
698 SLOGE(
699 "Invalid keysize (%u) for block device %s; Must be non-zero, "
700 "divisible by 16, and <= %d\n",
701 crypt_ftr->keysize, fname, MAX_KEY_LEN);
702 goto errout;
703 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800704
Paul Crowley14c8c072018-09-18 13:30:21 -0700705 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
706 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
707 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
708 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800709
Paul Crowley14c8c072018-09-18 13:30:21 -0700710 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
711 * copy on disk before returning.
712 */
713 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
714 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
715 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800716
Paul Crowley14c8c072018-09-18 13:30:21 -0700717 /* Success! */
718 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800719
720errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700721 close(fd);
722 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800723}
724
Paul Crowley14c8c072018-09-18 13:30:21 -0700725static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700726 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
727 crypt_ftr->persist_data_offset[1]) {
728 SLOGE("Crypt_ftr persist data regions overlap");
729 return -1;
730 }
731
732 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
733 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
734 return -1;
735 }
736
737 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700738 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700739 CRYPT_FOOTER_OFFSET) {
740 SLOGE("Persistent data extends past crypto footer");
741 return -1;
742 }
743
744 return 0;
745}
746
Paul Crowley14c8c072018-09-18 13:30:21 -0700747static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700748 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700749 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700750 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700751 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700752 int found = 0;
753 int fd;
754 int ret;
755 int i;
756
757 if (persist_data) {
758 /* Nothing to do, we've already loaded or initialized it */
759 return 0;
760 }
761
Ken Sumrall160b4d62013-04-22 12:15:39 -0700762 /* If not encrypted, just allocate an empty table and initialize it */
763 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700764 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800765 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700766 if (pdata) {
767 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
768 persist_data = pdata;
769 return 0;
770 }
771 return -1;
772 }
773
Paul Crowley14c8c072018-09-18 13:30:21 -0700774 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700775 return -1;
776 }
777
Paul Crowley14c8c072018-09-18 13:30:21 -0700778 if ((crypt_ftr.major_version < 1) ||
779 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700780 SLOGE("Crypt_ftr version doesn't support persistent data");
781 return -1;
782 }
783
784 if (get_crypt_ftr_info(&fname, NULL)) {
785 return -1;
786 }
787
788 ret = validate_persistent_data_storage(&crypt_ftr);
789 if (ret) {
790 return -1;
791 }
792
Paul Crowley14c8c072018-09-18 13:30:21 -0700793 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700794 if (fd < 0) {
795 SLOGE("Cannot open %s metadata file", fname);
796 return -1;
797 }
798
Wei Wang4375f1b2017-02-24 17:43:01 -0800799 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800800 if (pdata == NULL) {
801 SLOGE("Cannot allocate memory for persistent data");
802 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700803 }
804
805 for (i = 0; i < 2; i++) {
806 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
807 SLOGE("Cannot seek to read persistent data on %s", fname);
808 goto err2;
809 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700810 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700811 SLOGE("Error reading persistent data on iteration %d", i);
812 goto err2;
813 }
814 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
815 found = 1;
816 break;
817 }
818 }
819
820 if (!found) {
821 SLOGI("Could not find valid persistent data, creating");
822 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
823 }
824
825 /* Success */
826 persist_data = pdata;
827 close(fd);
828 return 0;
829
830err2:
831 free(pdata);
832
833err:
834 close(fd);
835 return -1;
836}
837
Paul Crowley14c8c072018-09-18 13:30:21 -0700838static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700839 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700840 struct crypt_persist_data* pdata;
841 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700842 off64_t write_offset;
843 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700844 int fd;
845 int ret;
846
847 if (persist_data == NULL) {
848 SLOGE("No persistent data to save");
849 return -1;
850 }
851
Paul Crowley14c8c072018-09-18 13:30:21 -0700852 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700853 return -1;
854 }
855
Paul Crowley14c8c072018-09-18 13:30:21 -0700856 if ((crypt_ftr.major_version < 1) ||
857 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700858 SLOGE("Crypt_ftr version doesn't support persistent data");
859 return -1;
860 }
861
862 ret = validate_persistent_data_storage(&crypt_ftr);
863 if (ret) {
864 return -1;
865 }
866
867 if (get_crypt_ftr_info(&fname, NULL)) {
868 return -1;
869 }
870
Paul Crowley14c8c072018-09-18 13:30:21 -0700871 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700872 if (fd < 0) {
873 SLOGE("Cannot open %s metadata file", fname);
874 return -1;
875 }
876
Wei Wang4375f1b2017-02-24 17:43:01 -0800877 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700878 if (pdata == NULL) {
879 SLOGE("Cannot allocate persistant data");
880 goto err;
881 }
882
883 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
884 SLOGE("Cannot seek to read persistent data on %s", fname);
885 goto err2;
886 }
887
888 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700889 SLOGE("Error reading persistent data before save");
890 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700891 }
892
893 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
894 /* The first copy is the curent valid copy, so write to
895 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700896 write_offset = crypt_ftr.persist_data_offset[1];
897 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700898 } else {
899 /* The second copy must be the valid copy, so write to
900 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700901 write_offset = crypt_ftr.persist_data_offset[0];
902 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700903 }
904
905 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100906 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700907 SLOGE("Cannot seek to write persistent data");
908 goto err2;
909 }
910 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700911 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100912 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700913 SLOGE("Cannot seek to erase previous persistent data");
914 goto err2;
915 }
916 fsync(fd);
917 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -0700918 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700919 SLOGE("Cannot write to erase previous persistent data");
920 goto err2;
921 }
922 fsync(fd);
923 } else {
924 SLOGE("Cannot write to save persistent data");
925 goto err2;
926 }
927
928 /* Success */
929 free(pdata);
930 close(fd);
931 return 0;
932
933err2:
934 free(pdata);
935err:
936 close(fd);
937 return -1;
938}
939
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800940/* Convert a binary key of specified length into an ascii hex string equivalent,
941 * without the leading 0x and with null termination
942 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700943static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
944 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700945 unsigned int i, a;
946 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800947
Paul Crowley14c8c072018-09-18 13:30:21 -0700948 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700949 /* For each byte, write out two ascii hex digits */
950 nibble = (master_key[i] >> 4) & 0xf;
951 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800952
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700953 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -0700954 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700955 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800956
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700957 /* Add the null termination */
958 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800959}
960
Eric Biggersed45ec32019-01-25 10:47:55 -0800961/*
962 * If the ro.crypto.fde_sector_size system property is set, append the
963 * parameters to make dm-crypt use the specified crypto sector size and round
964 * the crypto device size down to a crypto sector boundary.
965 */
David Andersonb9224732019-05-13 13:02:54 -0700966static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -0800967 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -0800968 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -0800969
Eric Biggersed45ec32019-01-25 10:47:55 -0800970 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
971 unsigned int sector_size;
972
973 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
974 (sector_size & (sector_size - 1)) != 0) {
975 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
976 DM_CRYPT_SECTOR_SIZE, value);
977 return -1;
978 }
979
David Andersonb9224732019-05-13 13:02:54 -0700980 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -0800981
982 // With this option, IVs will match the sector numbering, instead
983 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -0700984 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -0800985
986 // Round the crypto device size down to a crypto sector boundary.
987 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -0800988 }
Eric Biggersed45ec32019-01-25 10:47:55 -0800989 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -0800990}
991
Paul Crowley5afbc622017-11-27 09:42:17 -0800992static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
993 const char* real_blk_name, char* crypto_blk_name, const char* name,
994 uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -0700995 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800996
David Andersonb9224732019-05-13 13:02:54 -0700997 // We need two ASCII characters to represent each byte, and need space for
998 // the '\0' terminator.
999 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1000 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001001
David Andersonb9224732019-05-13 13:02:54 -07001002 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1003 (const char*)crypt_ftr->crypto_type_name,
1004 master_key_ascii, 0, real_blk_name, 0);
1005 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001006
Paul Crowley5afbc622017-11-27 09:42:17 -08001007 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001008 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001009 }
David Andersonb9224732019-05-13 13:02:54 -07001010 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001011 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001012 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001013 }
David Andersonb9224732019-05-13 13:02:54 -07001014
1015 DmTable table;
1016 table.AddTarget(std::move(target));
1017
1018 int load_count = 1;
1019 while (load_count < TABLE_LOAD_RETRIES) {
1020 if (dm.CreateDevice(name, table)) {
1021 break;
1022 }
1023 load_count++;
1024 }
1025
1026 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001027 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001028 return -1;
1029 }
1030 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001031 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1032 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001033
David Andersonb9224732019-05-13 13:02:54 -07001034 std::string path;
1035 if (!dm.GetDmDevicePathByName(name, &path)) {
1036 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1037 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001038 }
David Andersonb9224732019-05-13 13:02:54 -07001039 snprintf(crypto_blk_name, MAXPATHLEN, "%s", path.c_str());
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001040
Paul Crowleycfe39722018-10-30 15:59:24 -07001041 /* Ensure the dm device has been created before returning. */
1042 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1043 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001044 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001045 }
David Andersonb9224732019-05-13 13:02:54 -07001046 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001047}
1048
David Andersonb9224732019-05-13 13:02:54 -07001049static int delete_crypto_blk_dev(const std::string& name) {
1050 auto& dm = DeviceMapper::Instance();
1051 if (!dm.DeleteDevice(name)) {
1052 SLOGE("Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
1053 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001054 }
David Andersonb9224732019-05-13 13:02:54 -07001055 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001056}
1057
Paul Crowley14c8c072018-09-18 13:30:21 -07001058static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1059 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001060 SLOGI("Using pbkdf2 for cryptfs KDF");
1061
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001062 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001063 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1064 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001065}
1066
Paul Crowley14c8c072018-09-18 13:30:21 -07001067static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001068 SLOGI("Using scrypt for cryptfs KDF");
1069
Paul Crowley14c8c072018-09-18 13:30:21 -07001070 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001071
1072 int N = 1 << ftr->N_factor;
1073 int r = 1 << ftr->r_factor;
1074 int p = 1 << ftr->p_factor;
1075
1076 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001077 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001078 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001079
Paul Crowley14c8c072018-09-18 13:30:21 -07001080 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001081}
1082
Paul Crowley14c8c072018-09-18 13:30:21 -07001083static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1084 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001085 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1086
1087 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001088 size_t signature_size;
1089 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001090 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001091
1092 int N = 1 << ftr->N_factor;
1093 int r = 1 << ftr->r_factor;
1094 int p = 1 << ftr->p_factor;
1095
Paul Crowley14c8c072018-09-18 13:30:21 -07001096 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001097 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001098
1099 if (rc) {
1100 SLOGE("scrypt failed");
1101 return -1;
1102 }
1103
Paul Crowley14c8c072018-09-18 13:30:21 -07001104 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001105 SLOGE("Signing failed");
1106 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001107 }
1108
Paul Crowley14c8c072018-09-18 13:30:21 -07001109 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1110 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001111 free(signature);
1112
1113 if (rc) {
1114 SLOGE("scrypt failed");
1115 return -1;
1116 }
1117
1118 return 0;
1119}
1120
Paul Crowley14c8c072018-09-18 13:30:21 -07001121static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1122 const unsigned char* decrypted_master_key,
1123 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1124 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001125 EVP_CIPHER_CTX e_ctx;
1126 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001127 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001128
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001129 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001130 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001131
1132 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001133 case KDF_SCRYPT_KEYMASTER:
1134 if (keymaster_create_key(crypt_ftr)) {
1135 SLOGE("keymaster_create_key failed");
1136 return -1;
1137 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001138
Paul Crowley14c8c072018-09-18 13:30:21 -07001139 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1140 SLOGE("scrypt failed");
1141 return -1;
1142 }
1143 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001144
Paul Crowley14c8c072018-09-18 13:30:21 -07001145 case KDF_SCRYPT:
1146 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1147 SLOGE("scrypt failed");
1148 return -1;
1149 }
1150 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001151
Paul Crowley14c8c072018-09-18 13:30:21 -07001152 default:
1153 SLOGE("Invalid kdf_type");
1154 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001155 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001156
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001158 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001159 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1160 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 SLOGE("EVP_EncryptInit failed\n");
1162 return -1;
1163 }
1164 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001165
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001166 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001167 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1168 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001169 SLOGE("EVP_EncryptUpdate failed\n");
1170 return -1;
1171 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001172 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001173 SLOGE("EVP_EncryptFinal failed\n");
1174 return -1;
1175 }
1176
Greg Kaiser59ad0182018-02-16 13:01:36 -08001177 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001178 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1179 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001180 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001181
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001182 /* Store the scrypt of the intermediate key, so we can validate if it's a
1183 password error or mount error when things go wrong.
1184 Note there's no need to check for errors, since if this is incorrect, we
1185 simply won't wipe userdata, which is the correct default behavior
1186 */
1187 int N = 1 << crypt_ftr->N_factor;
1188 int r = 1 << crypt_ftr->r_factor;
1189 int p = 1 << crypt_ftr->p_factor;
1190
Paul Crowley14c8c072018-09-18 13:30:21 -07001191 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1192 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001193 sizeof(crypt_ftr->scrypted_intermediate_key));
1194
1195 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001196 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001197 }
1198
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001199 EVP_CIPHER_CTX_cleanup(&e_ctx);
1200
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001201 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001202}
1203
Paul Crowley14c8c072018-09-18 13:30:21 -07001204static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1205 const unsigned char* encrypted_master_key, size_t keysize,
1206 unsigned char* decrypted_master_key, kdf_func kdf,
1207 void* kdf_params, unsigned char** intermediate_key,
1208 size_t* intermediate_key_size) {
1209 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1210 EVP_CIPHER_CTX d_ctx;
1211 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212
Paul Crowley14c8c072018-09-18 13:30:21 -07001213 /* Turn the password into an intermediate key and IV that can decrypt the
1214 master key */
1215 if (kdf(passwd, salt, ikey, kdf_params)) {
1216 SLOGE("kdf failed");
1217 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001218 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001219
Paul Crowley14c8c072018-09-18 13:30:21 -07001220 /* Initialize the decryption engine */
1221 EVP_CIPHER_CTX_init(&d_ctx);
1222 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1223 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1224 return -1;
1225 }
1226 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1227 /* Decrypt the master key */
1228 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1229 keysize)) {
1230 return -1;
1231 }
1232 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1233 return -1;
1234 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001235
Paul Crowley14c8c072018-09-18 13:30:21 -07001236 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1237 return -1;
1238 }
1239
1240 /* Copy intermediate key if needed by params */
1241 if (intermediate_key && intermediate_key_size) {
1242 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1243 if (*intermediate_key) {
1244 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1245 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1246 }
1247 }
1248
1249 EVP_CIPHER_CTX_cleanup(&d_ctx);
1250
1251 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001252}
1253
Paul Crowley14c8c072018-09-18 13:30:21 -07001254static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001255 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001256 *kdf = scrypt_keymaster;
1257 *kdf_params = ftr;
1258 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001259 *kdf = scrypt;
1260 *kdf_params = ftr;
1261 } else {
1262 *kdf = pbkdf2;
1263 *kdf_params = NULL;
1264 }
1265}
1266
Paul Crowley14c8c072018-09-18 13:30:21 -07001267static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1268 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1269 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001270 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001271 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001272 int ret;
1273
1274 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001275 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1276 decrypted_master_key, kdf, kdf_params, intermediate_key,
1277 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001278 if (ret != 0) {
1279 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001280 }
1281
1282 return ret;
1283}
1284
Paul Crowley14c8c072018-09-18 13:30:21 -07001285static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1286 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001287 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001288
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001289 /* Get some random bits for a key and salt */
1290 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1291 return -1;
1292 }
1293 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1294 return -1;
1295 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001296
1297 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001298 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001299}
1300
Paul Crowley14c8c072018-09-18 13:30:21 -07001301int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001302 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001303#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001304
1305 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001306 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001307 if (umount(mountpoint) == 0) {
1308 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001309 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001310
1311 if (errno == EINVAL) {
1312 /* EINVAL is returned if the directory is not a mountpoint,
1313 * i.e. there is no filesystem mounted there. So just get out.
1314 */
1315 break;
1316 }
1317
1318 err = errno;
1319
1320 /* If allowed, be increasingly aggressive before the last two retries */
1321 if (kill) {
1322 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1323 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001324 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001325 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1326 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001327 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001328 }
1329 }
1330
1331 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001332 }
1333
1334 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001335 SLOGD("unmounting %s succeeded\n", mountpoint);
1336 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001337 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001338 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1339 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1340 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001341 }
1342
1343 return rc;
1344}
1345
Paul Crowley14c8c072018-09-18 13:30:21 -07001346static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001347 // NOTE: post_fs_data results in init calling back around to vold, so all
1348 // callers to this method must be async
1349
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001350 /* Do the prep of the /data filesystem */
1351 property_set("vold.post_fs_data_done", "0");
1352 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001353 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001354
Ken Sumrallc5872692013-05-14 15:26:31 -07001355 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001356 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001357 /* We timed out to prep /data in time. Continue wait. */
1358 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001359 }
Wei Wang42e38102017-06-07 10:46:12 -07001360 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001361}
1362
Paul Crowley14c8c072018-09-18 13:30:21 -07001363static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001364 // Mark the footer as bad
1365 struct crypt_mnt_ftr crypt_ftr;
1366 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1367 SLOGE("Failed to get crypto footer - panic");
1368 return;
1369 }
1370
1371 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1372 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1373 SLOGE("Failed to set crypto footer - panic");
1374 return;
1375 }
1376}
1377
Paul Crowley14c8c072018-09-18 13:30:21 -07001378static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001379 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001380 SLOGE("Failed to mount tmpfs on data - panic");
1381 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001382 }
1383
1384 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1385 SLOGE("Failed to trigger post fs data - panic");
1386 return;
1387 }
1388
1389 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1390 SLOGE("Failed to trigger restart min framework - panic");
1391 return;
1392 }
1393}
1394
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001395/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001396static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001397 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001398 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001399 static int restart_successful = 0;
1400
1401 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001402 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001403 SLOGE("Encrypted filesystem not validated, aborting");
1404 return -1;
1405 }
1406
1407 if (restart_successful) {
1408 SLOGE("System already restarted with encrypted disk, aborting");
1409 return -1;
1410 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001411
Paul Lawrencef4faa572014-01-29 13:31:03 -08001412 if (restart_main) {
1413 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001414 * start all services in one of these classes: core, early_hal, hal,
1415 * main and late_start. To get to the minimal UI for PIN entry, we
1416 * need to start core, early_hal, hal and main. When we want to
1417 * shutdown the framework again, we need to stop most of the services in
1418 * these classes, but only those services that were started after
1419 * /data was mounted. This excludes critical services like vold and
1420 * ueventd, which need to keep running. We could possible stop
1421 * even fewer services, but because we want services to pick up APEX
1422 * libraries from the real /data, restarting is better, as it makes
1423 * these devices consistent with FBE devices and lets them use the
1424 * most recent code.
1425 *
1426 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001427 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001428 * We then restart the class core, hal, main, and also the class
1429 * late_start.
1430 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001431 * At the moment, I've only put a few things in late_start that I know
1432 * are not needed to bring up the framework, and that also cause problems
1433 * with unmounting the tmpfs /data, but I hope to add add more services
1434 * to the late_start class as we optimize this to decrease the delay
1435 * till the user is asked for the password to the filesystem.
1436 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001437
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001438 /* The init files are setup to stop the right set of services when
1439 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001440 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001441 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001442 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001443
Paul Lawrencef4faa572014-01-29 13:31:03 -08001444 /* Ugh, shutting down the framework is not synchronous, so until it
1445 * can be fixed, this horrible hack will wait a moment for it all to
1446 * shut down before proceeding. Without it, some devices cannot
1447 * restart the graphics services.
1448 */
1449 sleep(2);
1450 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001451
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001452 /* Now that the framework is shutdown, we should be able to umount()
1453 * the tmpfs filesystem, and mount the real one.
1454 */
1455
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001456 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1457 if (strlen(crypto_blkdev) == 0) {
1458 SLOGE("fs_crypto_blkdev not set\n");
1459 return -1;
1460 }
1461
Paul Crowley14c8c072018-09-18 13:30:21 -07001462 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001463 /* If ro.crypto.readonly is set to 1, mount the decrypted
1464 * filesystem readonly. This is used when /data is mounted by
1465 * recovery mode.
1466 */
1467 char ro_prop[PROPERTY_VALUE_MAX];
1468 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001469 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001470 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1471 if (entry != nullptr) {
1472 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001473 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001474 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001475
Ken Sumralle5032c42012-04-01 23:58:44 -07001476 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001477 int retries = RETRY_MOUNT_ATTEMPTS;
1478 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001479
1480 /*
1481 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1482 * partitions in the fsck domain.
1483 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001484 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001485 SLOGE("Failed to setexeccon");
1486 return -1;
1487 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001488 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001489 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001490 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001491 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1492 /* TODO: invoke something similar to
1493 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1494 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001495 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001496 if (--retries) {
1497 sleep(RETRY_MOUNT_DELAY_SECONDS);
1498 } else {
1499 /* Let's hope that a reboot clears away whatever is keeping
1500 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001501 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001502 }
1503 } else {
1504 SLOGE("Failed to mount decrypted data");
1505 cryptfs_set_corrupt();
1506 cryptfs_trigger_restart_min_framework();
1507 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001508 if (setexeccon(NULL)) {
1509 SLOGE("Failed to setexeccon");
1510 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001511 return -1;
1512 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001513 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001514 if (setexeccon(NULL)) {
1515 SLOGE("Failed to setexeccon");
1516 return -1;
1517 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001518
Ken Sumralle5032c42012-04-01 23:58:44 -07001519 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001520 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001521 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001522
1523 /* startup service classes main and late_start */
1524 property_set("vold.decrypt", "trigger_restart_framework");
1525 SLOGD("Just triggered restart_framework\n");
1526
1527 /* Give it a few moments to get started */
1528 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001529 }
1530
Ken Sumrall0cc16632011-01-18 20:32:26 -08001531 if (rc == 0) {
1532 restart_successful = 1;
1533 }
1534
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001535 return rc;
1536}
1537
Paul Crowley14c8c072018-09-18 13:30:21 -07001538int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001539 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001540 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001541 SLOGE("cryptfs_restart not valid for file encryption:");
1542 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001543 }
1544
Paul Lawrencef4faa572014-01-29 13:31:03 -08001545 /* Call internal implementation forcing a restart of main service group */
1546 return cryptfs_restart_internal(1);
1547}
1548
Paul Crowley14c8c072018-09-18 13:30:21 -07001549static int do_crypto_complete(const char* mount_point) {
1550 struct crypt_mnt_ftr crypt_ftr;
1551 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001552
Paul Crowley14c8c072018-09-18 13:30:21 -07001553 property_get("ro.crypto.state", encrypted_state, "");
1554 if (strcmp(encrypted_state, "encrypted")) {
1555 SLOGE("not running with encryption, aborting");
1556 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001557 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001558
Paul Crowley14c8c072018-09-18 13:30:21 -07001559 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001560 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001561 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1562 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001563
Paul Crowley14c8c072018-09-18 13:30:21 -07001564 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001565 std::string key_loc;
1566 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001567
Paul Crowley14c8c072018-09-18 13:30:21 -07001568 /*
1569 * Only report this error if key_loc is a file and it exists.
1570 * If the device was never encrypted, and /data is not mountable for
1571 * some reason, returning 1 should prevent the UI from presenting the
1572 * a "enter password" screen, or worse, a "press button to wipe the
1573 * device" screen.
1574 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001575 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001576 SLOGE("master key file does not exist, aborting");
1577 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1578 } else {
1579 SLOGE("Error getting crypt footer and key\n");
1580 return CRYPTO_COMPLETE_BAD_METADATA;
1581 }
1582 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001583
Paul Crowley14c8c072018-09-18 13:30:21 -07001584 // Test for possible error flags
1585 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1586 SLOGE("Encryption process is partway completed\n");
1587 return CRYPTO_COMPLETE_PARTIAL;
1588 }
1589
1590 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1591 SLOGE("Encryption process was interrupted but cannot continue\n");
1592 return CRYPTO_COMPLETE_INCONSISTENT;
1593 }
1594
1595 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1596 SLOGE("Encryption is successful but data is corrupt\n");
1597 return CRYPTO_COMPLETE_CORRUPT;
1598 }
1599
1600 /* We passed the test! We shall diminish, and return to the west */
1601 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001602}
1603
Paul Crowley14c8c072018-09-18 13:30:21 -07001604static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1605 const char* mount_point, const char* label) {
1606 unsigned char decrypted_master_key[MAX_KEY_LEN];
1607 char crypto_blkdev[MAXPATHLEN];
Tom Cherry4c5bde22019-01-29 14:34:01 -08001608 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001609 char tmp_mount_point[64];
1610 unsigned int orig_failed_decrypt_count;
1611 int rc;
1612 int use_keymaster = 0;
1613 int upgrade = 0;
1614 unsigned char* intermediate_key = 0;
1615 size_t intermediate_key_size = 0;
1616 int N = 1 << crypt_ftr->N_factor;
1617 int r = 1 << crypt_ftr->r_factor;
1618 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001619
Paul Crowley14c8c072018-09-18 13:30:21 -07001620 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1621 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001622
Paul Crowley14c8c072018-09-18 13:30:21 -07001623 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1624 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1625 &intermediate_key_size)) {
1626 SLOGE("Failed to decrypt master key\n");
1627 rc = -1;
1628 goto errout;
1629 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001630 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001631
Tom Cherry4c5bde22019-01-29 14:34:01 -08001632 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001633
Paul Crowley14c8c072018-09-18 13:30:21 -07001634 // Create crypto block device - all (non fatal) code paths
1635 // need it
Tom Cherry4c5bde22019-01-29 14:34:01 -08001636 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
1637 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001638 SLOGE("Error creating decrypted block device\n");
1639 rc = -1;
1640 goto errout;
1641 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001642
Paul Crowley14c8c072018-09-18 13:30:21 -07001643 /* Work out if the problem is the password or the data */
1644 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001645
Paul Crowley14c8c072018-09-18 13:30:21 -07001646 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1647 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1648 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001649
Paul Crowley14c8c072018-09-18 13:30:21 -07001650 // Does the key match the crypto footer?
1651 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1652 sizeof(scrypted_intermediate_key)) == 0) {
1653 SLOGI("Password matches");
1654 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001655 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001656 /* Try mounting the file system anyway, just in case the problem's with
1657 * the footer, not the key. */
1658 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1659 mkdir(tmp_mount_point, 0755);
Tom Cherry4c5bde22019-01-29 14:34:01 -08001660 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001661 SLOGE("Error temp mounting decrypted block device\n");
1662 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001663
Paul Crowley14c8c072018-09-18 13:30:21 -07001664 rc = ++crypt_ftr->failed_decrypt_count;
1665 put_crypt_ftr_and_key(crypt_ftr);
1666 } else {
1667 /* Success! */
1668 SLOGI("Password did not match but decrypted drive mounted - continue");
1669 umount(tmp_mount_point);
1670 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001671 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001672 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001673
Paul Crowley14c8c072018-09-18 13:30:21 -07001674 if (rc == 0) {
1675 crypt_ftr->failed_decrypt_count = 0;
1676 if (orig_failed_decrypt_count != 0) {
1677 put_crypt_ftr_and_key(crypt_ftr);
1678 }
1679
1680 /* Save the name of the crypto block device
1681 * so we can mount it when restarting the framework. */
1682 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1683
1684 /* Also save a the master key so we can reencrypted the key
1685 * the key when we want to change the password on it. */
1686 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1687 saved_mount_point = strdup(mount_point);
1688 master_key_saved = 1;
1689 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1690 rc = 0;
1691
1692 // Upgrade if we're not using the latest KDF.
1693 use_keymaster = keymaster_check_compatibility();
1694 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1695 // Don't allow downgrade
1696 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1697 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1698 upgrade = 1;
1699 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1700 crypt_ftr->kdf_type = KDF_SCRYPT;
1701 upgrade = 1;
1702 }
1703
1704 if (upgrade) {
1705 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1706 crypt_ftr->master_key, crypt_ftr);
1707 if (!rc) {
1708 rc = put_crypt_ftr_and_key(crypt_ftr);
1709 }
1710 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1711
1712 // Do not fail even if upgrade failed - machine is bootable
1713 // Note that if this code is ever hit, there is a *serious* problem
1714 // since KDFs should never fail. You *must* fix the kdf before
1715 // proceeding!
1716 if (rc) {
1717 SLOGW(
1718 "Upgrade failed with error %d,"
1719 " but continuing with previous state",
1720 rc);
1721 rc = 0;
1722 }
1723 }
1724 }
1725
1726errout:
1727 if (intermediate_key) {
1728 memset(intermediate_key, 0, intermediate_key_size);
1729 free(intermediate_key);
1730 }
1731 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001732}
1733
Ken Sumrall29d8da82011-05-18 17:20:07 -07001734/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001735 * Called by vold when it's asked to mount an encrypted external
1736 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001737 * as any metadata is been stored in a separate, small partition. We
1738 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001739 *
1740 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001741 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001742int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1743 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001744 uint64_t nr_sec = 0;
1745 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001746 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001747 return -1;
1748 }
1749
Jeff Sharkey9c484982015-03-31 10:35:33 -07001750 struct crypt_mnt_ftr ext_crypt_ftr;
1751 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1752 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001753 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001754 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001755 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001756 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001757 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001758 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1759 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001760
Paul Crowley385cb8c2018-03-29 13:27:23 -07001761 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001762}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001763
Jeff Sharkey9c484982015-03-31 10:35:33 -07001764/*
1765 * Called by vold when it's asked to unmount an encrypted external
1766 * storage volume.
1767 */
1768int cryptfs_revert_ext_volume(const char* label) {
David Andersonb9224732019-05-13 13:02:54 -07001769 return delete_crypto_blk_dev(label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001770}
1771
Paul Crowley14c8c072018-09-18 13:30:21 -07001772int cryptfs_crypto_complete(void) {
1773 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001774}
1775
Paul Crowley14c8c072018-09-18 13:30:21 -07001776int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001777 char encrypted_state[PROPERTY_VALUE_MAX];
1778 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001779 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1780 SLOGE(
1781 "encrypted fs already validated or not running with encryption,"
1782 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001783 return -1;
1784 }
1785
1786 if (get_crypt_ftr_and_key(crypt_ftr)) {
1787 SLOGE("Error getting crypt footer and key");
1788 return -1;
1789 }
1790
1791 return 0;
1792}
1793
Paul Crowley14c8c072018-09-18 13:30:21 -07001794int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001795 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001796 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001797 SLOGE("cryptfs_check_passwd not valid for file encryption");
1798 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001799 }
1800
Paul Lawrencef4faa572014-01-29 13:31:03 -08001801 struct crypt_mnt_ftr crypt_ftr;
1802 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001803
Paul Lawrencef4faa572014-01-29 13:31:03 -08001804 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001805 if (rc) {
1806 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001807 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001808 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001809
Paul Crowley14c8c072018-09-18 13:30:21 -07001810 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001811 if (rc) {
1812 SLOGE("Password did not match");
1813 return rc;
1814 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001815
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001816 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1817 // Here we have a default actual password but a real password
1818 // we must test against the scrypted value
1819 // First, we must delete the crypto block device that
1820 // test_mount_encrypted_fs leaves behind as a side effect
1821 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001822 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1823 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001824 if (rc) {
1825 SLOGE("Default password did not match on reboot encryption");
1826 return rc;
1827 }
1828
1829 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1830 put_crypt_ftr_and_key(&crypt_ftr);
1831 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1832 if (rc) {
1833 SLOGE("Could not change password on reboot encryption");
1834 return rc;
1835 }
1836 }
1837
1838 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001839 cryptfs_clear_password();
1840 password = strdup(passwd);
1841 struct timespec now;
1842 clock_gettime(CLOCK_BOOTTIME, &now);
1843 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001844 }
1845
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001846 return rc;
1847}
1848
Paul Crowley14c8c072018-09-18 13:30:21 -07001849int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001850 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001851 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001852 char encrypted_state[PROPERTY_VALUE_MAX];
1853 int rc;
1854
1855 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001856 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001857 SLOGE("device not encrypted, aborting");
1858 return -2;
1859 }
1860
1861 if (!master_key_saved) {
1862 SLOGE("encrypted fs not yet mounted, aborting");
1863 return -1;
1864 }
1865
1866 if (!saved_mount_point) {
1867 SLOGE("encrypted fs failed to save mount point, aborting");
1868 return -1;
1869 }
1870
Ken Sumrall160b4d62013-04-22 12:15:39 -07001871 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001872 SLOGE("Error getting crypt footer and key\n");
1873 return -1;
1874 }
1875
1876 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1877 /* If the device has no password, then just say the password is valid */
1878 rc = 0;
1879 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001880 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001881 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1882 /* They match, the password is correct */
1883 rc = 0;
1884 } else {
1885 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1886 sleep(1);
1887 rc = 1;
1888 }
1889 }
1890
1891 return rc;
1892}
1893
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001894/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08001895 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001896 * Presumably, at a minimum, the caller will update the
1897 * filesystem size and crypto_type_name after calling this function.
1898 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001899static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001900 off64_t off;
1901
1902 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001904 ftr->major_version = CURRENT_MAJOR_VERSION;
1905 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001906 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08001907 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07001908
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001909 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001910 case 1:
1911 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1912 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001913
Paul Crowley14c8c072018-09-18 13:30:21 -07001914 case 0:
1915 ftr->kdf_type = KDF_SCRYPT;
1916 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001917
Paul Crowley14c8c072018-09-18 13:30:21 -07001918 default:
1919 SLOGE("keymaster_check_compatibility failed");
1920 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001921 }
1922
Kenny Rootc4c70f12013-06-14 12:11:38 -07001923 get_device_scrypt_params(ftr);
1924
Ken Sumrall160b4d62013-04-22 12:15:39 -07001925 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1926 if (get_crypt_ftr_info(NULL, &off) == 0) {
1927 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07001928 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001929 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001930
1931 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001932}
1933
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001934#define FRAMEWORK_BOOT_WAIT 60
1935
Paul Crowley14c8c072018-09-18 13:30:21 -07001936static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
1937 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001938 if (fd == -1) {
1939 SLOGE("Error opening file %s", filename);
1940 return -1;
1941 }
1942
1943 char block[CRYPT_INPLACE_BUFSIZE];
1944 memset(block, 0, sizeof(block));
1945 if (unix_read(fd, block, sizeof(block)) < 0) {
1946 SLOGE("Error reading file %s", filename);
1947 close(fd);
1948 return -1;
1949 }
1950
1951 close(fd);
1952
1953 SHA256_CTX c;
1954 SHA256_Init(&c);
1955 SHA256_Update(&c, block, sizeof(block));
1956 SHA256_Final(buf, &c);
1957
1958 return 0;
1959}
1960
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001961static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
1962 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001963 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08001964 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001965
Paul Lawrence87999172014-02-20 12:21:31 -08001966 /* The size of the userdata partition, and add in the vold volumes below */
1967 tot_encryption_size = crypt_ftr->fs_size;
1968
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001969 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08001970 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08001971
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001972 if (rc == ENABLE_INPLACE_ERR_DEV) {
1973 /* Hack for b/17898962 */
1974 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
1975 cryptfs_reboot(RebootType::reboot);
1976 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07001977
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001978 if (!rc) {
1979 crypt_ftr->encrypted_upto = cur_encryption_done;
1980 }
Paul Lawrence87999172014-02-20 12:21:31 -08001981
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001982 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
1983 /* The inplace routine never actually sets the progress to 100% due
1984 * to the round down nature of integer division, so set it here */
1985 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08001986 }
1987
1988 return rc;
1989}
1990
Paul Crowleyb64933a2017-10-31 08:25:55 -07001991static int vold_unmountAll(void) {
1992 VolumeManager* vm = VolumeManager::Instance();
1993 return vm->unmountAll();
1994}
1995
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001996int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001997 char crypto_blkdev[MAXPATHLEN];
1998 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001999 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002000 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002001 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002002 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002003 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002004 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002005 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002006 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002007 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002008 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002009 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002010 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002011
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002012 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002013 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2014 /* An encryption was underway and was interrupted */
2015 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2016 crypt_ftr.encrypted_upto = 0;
2017 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002018
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002019 /* At this point, we are in an inconsistent state. Until we successfully
2020 complete encryption, a reboot will leave us broken. So mark the
2021 encryption failed in case that happens.
2022 On successfully completing encryption, remove this flag */
2023 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002024
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002025 put_crypt_ftr_and_key(&crypt_ftr);
2026 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2027 if (!check_ftr_sha(&crypt_ftr)) {
2028 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2029 put_crypt_ftr_and_key(&crypt_ftr);
2030 goto error_unencrypted;
2031 }
2032
2033 /* Doing a reboot-encryption*/
2034 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2035 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2036 rebootEncryption = true;
2037 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002038 } else {
2039 // We don't want to accidentally reference invalid data.
2040 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002041 }
2042
2043 property_get("ro.crypto.state", encrypted_state, "");
2044 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2045 SLOGE("Device is already running encrypted, aborting");
2046 goto error_unencrypted;
2047 }
2048
Tom Cherry4c5bde22019-01-29 14:34:01 -08002049 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002050
Ken Sumrall3ed82362011-01-28 23:31:16 -08002051 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002052 uint64_t nr_sec;
2053 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002054 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002055 goto error_unencrypted;
2056 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002057
2058 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002059 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002060 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002061 fs_size_sec = get_fs_size(real_blkdev.c_str());
2062 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002063
Paul Lawrence87999172014-02-20 12:21:31 -08002064 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002065
2066 if (fs_size_sec > max_fs_size_sec) {
2067 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2068 goto error_unencrypted;
2069 }
2070 }
2071
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002072 /* Get a wakelock as this may take a while, and we don't want the
2073 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2074 * wants to keep the screen on, it can grab a full wakelock.
2075 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002076 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002077 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002078
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002079 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002080 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002081 */
2082 property_set("vold.decrypt", "trigger_shutdown_framework");
2083 SLOGD("Just asked init to shut down class main\n");
2084
Jeff Sharkey9c484982015-03-31 10:35:33 -07002085 /* Ask vold to unmount all devices that it manages */
2086 if (vold_unmountAll()) {
2087 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002088 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002089
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002090 /* no_ui means we are being called from init, not settings.
2091 Now we always reboot from settings, so !no_ui means reboot
2092 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002093 if (!no_ui) {
2094 /* Try fallback, which is to reboot and try there */
2095 onlyCreateHeader = true;
2096 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2097 if (breadcrumb == 0) {
2098 SLOGE("Failed to create breadcrumb file");
2099 goto error_shutting_down;
2100 }
2101 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002102 }
2103
2104 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002105 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002106 /* Now that /data is unmounted, we need to mount a tmpfs
2107 * /data, set a property saying we're doing inplace encryption,
2108 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002109 */
xzj7e38a3a2018-10-12 10:17:11 +08002110 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002111 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002112 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002113 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002114 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002115 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002116
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002117 /* restart the framework. */
2118 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002119 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002120
Ken Sumrall92736ef2012-10-17 20:57:14 -07002121 /* Ugh, shutting down the framework is not synchronous, so until it
2122 * can be fixed, this horrible hack will wait a moment for it all to
2123 * shut down before proceeding. Without it, some devices cannot
2124 * restart the graphics services.
2125 */
2126 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002127 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002128
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002129 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002130 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002131 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002132 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2133 goto error_shutting_down;
2134 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002135
Tom Cherry4c5bde22019-01-29 14:34:01 -08002136 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002137 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002138 } else {
2139 crypt_ftr.fs_size = nr_sec;
2140 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002141 /* At this point, we are in an inconsistent state. Until we successfully
2142 complete encryption, a reboot will leave us broken. So mark the
2143 encryption failed in case that happens.
2144 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002145 if (onlyCreateHeader) {
2146 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2147 } else {
2148 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2149 }
Paul Lawrence87999172014-02-20 12:21:31 -08002150 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002151 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2152 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002153
Paul Lawrence87999172014-02-20 12:21:31 -08002154 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002155 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2156 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002157 SLOGE("Cannot create encrypted master key\n");
2158 goto error_shutting_down;
2159 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002160
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002161 /* Replace scrypted intermediate key if we are preparing for a reboot */
2162 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002163 unsigned char fake_master_key[MAX_KEY_LEN];
2164 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002165 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002166 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2167 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002168 }
2169
Paul Lawrence87999172014-02-20 12:21:31 -08002170 /* Write the key to the end of the partition */
2171 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002172
Paul Lawrence87999172014-02-20 12:21:31 -08002173 /* If any persistent data has been remembered, save it.
2174 * If none, create a valid empty table and save that.
2175 */
2176 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002177 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2178 if (pdata) {
2179 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2180 persist_data = pdata;
2181 }
Paul Lawrence87999172014-02-20 12:21:31 -08002182 }
2183 if (persist_data) {
2184 save_persistent_data();
2185 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002186 }
2187
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002188 if (onlyCreateHeader) {
2189 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002190 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002191 }
2192
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002193 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002194 /* startup service classes main and late_start */
2195 property_set("vold.decrypt", "trigger_restart_min_framework");
2196 SLOGD("Just triggered restart_min_framework\n");
2197
2198 /* OK, the framework is restarted and will soon be showing a
2199 * progress bar. Time to setup an encrypted mapping, and
2200 * either write a new filesystem, or encrypt in place updating
2201 * the progress bar as we work.
2202 */
2203 }
2204
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002205 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Tom Cherry4c5bde22019-01-29 14:34:01 -08002206 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002207 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002208
Paul Lawrence87999172014-02-20 12:21:31 -08002209 /* If we are continuing, check checksums match */
2210 rc = 0;
2211 if (previously_encrypted_upto) {
2212 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2213 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002214
Paul Crowley14c8c072018-09-18 13:30:21 -07002215 if (!rc &&
2216 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002217 SLOGE("Checksums do not match - trigger wipe");
2218 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002219 }
2220 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002221
Paul Lawrence87999172014-02-20 12:21:31 -08002222 if (!rc) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002223 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002224 previously_encrypted_upto);
2225 }
2226
2227 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002228 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002229 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002230 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002231 SLOGE("Error calculating checksum for continuing encryption");
2232 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002233 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002234 }
2235
2236 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002237 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002238
Paul Crowley14c8c072018-09-18 13:30:21 -07002239 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002240 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002241 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002242
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002243 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002244 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2245 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002246 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002247 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002248
Paul Lawrence6bfed202014-07-28 12:47:22 -07002249 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002250
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002251 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2252 char value[PROPERTY_VALUE_MAX];
2253 property_get("ro.crypto.state", value, "");
2254 if (!strcmp(value, "")) {
2255 /* default encryption - continue first boot sequence */
2256 property_set("ro.crypto.state", "encrypted");
2257 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002258 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002259 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2260 // Bring up cryptkeeper that will check the password and set it
2261 property_set("vold.decrypt", "trigger_shutdown_framework");
2262 sleep(2);
2263 property_set("vold.encrypt_progress", "");
2264 cryptfs_trigger_restart_min_framework();
2265 } else {
2266 cryptfs_check_passwd(DEFAULT_PASSWORD);
2267 cryptfs_restart_internal(1);
2268 }
2269 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002270 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002271 sleep(2); /* Give the UI a chance to show 100% progress */
2272 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002273 }
Paul Lawrence87999172014-02-20 12:21:31 -08002274 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002275 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002276 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002277 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002278 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002279 char value[PROPERTY_VALUE_MAX];
2280
Ken Sumrall319369a2012-06-27 16:30:18 -07002281 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002282 if (!strcmp(value, "1")) {
2283 /* wipe data if encryption failed */
2284 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002285 std::string err;
2286 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002287 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002288 if (!write_bootloader_message(options, &err)) {
2289 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002290 }
Josh Gaofec44372017-08-28 13:22:55 -07002291 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002292 } else {
2293 /* set property to trigger dialog */
2294 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002295 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002296 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002297 }
2298
Ken Sumrall3ed82362011-01-28 23:31:16 -08002299 /* hrm, the encrypt step claims success, but the reboot failed.
2300 * This should not happen.
2301 * Set the property and return. Hope the framework can deal with it.
2302 */
2303 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002304 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002305
2306error_unencrypted:
2307 property_set("vold.encrypt_progress", "error_not_encrypted");
2308 return -1;
2309
2310error_shutting_down:
2311 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2312 * but the framework is stopped and not restarted to show the error, so it's up to
2313 * vold to restart the system.
2314 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002315 SLOGE(
2316 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2317 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002318 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002319
2320 /* shouldn't get here */
2321 property_set("vold.encrypt_progress", "error_shutting_down");
2322 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002323}
2324
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002325int cryptfs_enable(int type, const char* passwd, int no_ui) {
2326 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002327}
2328
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002329int cryptfs_enable_default(int no_ui) {
2330 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002331}
2332
Paul Crowley14c8c072018-09-18 13:30:21 -07002333int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002334 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002335 SLOGE("cryptfs_changepw not valid for file encryption");
2336 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002337 }
2338
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002339 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002340 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002341
2342 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002343 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002344 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002345 return -1;
2346 }
2347
Paul Lawrencef4faa572014-01-29 13:31:03 -08002348 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2349 SLOGE("Invalid crypt_type %d", crypt_type);
2350 return -1;
2351 }
2352
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002353 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002354 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002355 SLOGE("Error getting crypt footer and key");
2356 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002357 }
2358
Paul Lawrencef4faa572014-01-29 13:31:03 -08002359 crypt_ftr.crypt_type = crypt_type;
2360
Paul Crowley14c8c072018-09-18 13:30:21 -07002361 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2362 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002363 if (rc) {
2364 SLOGE("Encrypt master key failed: %d", rc);
2365 return -1;
2366 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002367 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002368 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002369
2370 return 0;
2371}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002372
Rubin Xu85c01f92014-10-13 12:49:54 +01002373static unsigned int persist_get_max_entries(int encrypted) {
2374 struct crypt_mnt_ftr crypt_ftr;
2375 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002376
2377 /* If encrypted, use the values from the crypt_ftr, otherwise
2378 * use the values for the current spec.
2379 */
2380 if (encrypted) {
2381 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002382 /* Something is wrong, assume no space for entries */
2383 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002384 }
2385 dsize = crypt_ftr.persist_data_size;
2386 } else {
2387 dsize = CRYPT_PERSIST_DATA_SIZE;
2388 }
2389
Rubin Xuf83cc612018-10-09 16:13:38 +01002390 if (dsize > sizeof(struct crypt_persist_data)) {
2391 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2392 } else {
2393 return 0;
2394 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002395}
2396
Paul Crowley14c8c072018-09-18 13:30:21 -07002397static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002398 unsigned int i;
2399
2400 if (persist_data == NULL) {
2401 return -1;
2402 }
2403 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2404 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2405 /* We found it! */
2406 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2407 return 0;
2408 }
2409 }
2410
2411 return -1;
2412}
2413
Paul Crowley14c8c072018-09-18 13:30:21 -07002414static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002415 unsigned int i;
2416 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002417 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002418
2419 if (persist_data == NULL) {
2420 return -1;
2421 }
2422
Rubin Xu85c01f92014-10-13 12:49:54 +01002423 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002424
2425 num = persist_data->persist_valid_entries;
2426
2427 for (i = 0; i < num; i++) {
2428 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2429 /* We found an existing entry, update it! */
2430 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2431 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2432 return 0;
2433 }
2434 }
2435
2436 /* We didn't find it, add it to the end, if there is room */
2437 if (persist_data->persist_valid_entries < max_persistent_entries) {
2438 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2439 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2440 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2441 persist_data->persist_valid_entries++;
2442 return 0;
2443 }
2444
2445 return -1;
2446}
2447
Rubin Xu85c01f92014-10-13 12:49:54 +01002448/**
2449 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2450 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2451 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002452int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002453 std::string key_ = key;
2454 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002455
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002456 std::string parsed_field;
2457 unsigned parsed_index;
2458
2459 std::string::size_type split = key_.find_last_of('_');
2460 if (split == std::string::npos) {
2461 parsed_field = key_;
2462 parsed_index = 0;
2463 } else {
2464 parsed_field = key_.substr(0, split);
2465 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002466 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002467
2468 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002469}
2470
2471/*
2472 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2473 * remaining entries starting from index will be deleted.
2474 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2475 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2476 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2477 *
2478 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002479static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002480 unsigned int i;
2481 unsigned int j;
2482 unsigned int num;
2483
2484 if (persist_data == NULL) {
2485 return PERSIST_DEL_KEY_ERROR_OTHER;
2486 }
2487
2488 num = persist_data->persist_valid_entries;
2489
Paul Crowley14c8c072018-09-18 13:30:21 -07002490 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002491 // Filter out to-be-deleted entries in place.
2492 for (i = 0; i < num; i++) {
2493 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2494 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2495 j++;
2496 }
2497 }
2498
2499 if (j < num) {
2500 persist_data->persist_valid_entries = j;
2501 // Zeroise the remaining entries
2502 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2503 return PERSIST_DEL_KEY_OK;
2504 } else {
2505 // Did not find an entry matching the given fieldname
2506 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2507 }
2508}
2509
Paul Crowley14c8c072018-09-18 13:30:21 -07002510static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002511 unsigned int i;
2512 unsigned int count;
2513
2514 if (persist_data == NULL) {
2515 return -1;
2516 }
2517
2518 count = 0;
2519 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2520 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2521 count++;
2522 }
2523 }
2524
2525 return count;
2526}
2527
Ken Sumrall160b4d62013-04-22 12:15:39 -07002528/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002529int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002530 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002531 SLOGE("Cannot get field when file encrypted");
2532 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002533 }
2534
Ken Sumrall160b4d62013-04-22 12:15:39 -07002535 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002536 /* CRYPTO_GETFIELD_OK is success,
2537 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2538 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2539 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002540 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002541 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2542 int i;
2543 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002544
2545 if (persist_data == NULL) {
2546 load_persistent_data();
2547 if (persist_data == NULL) {
2548 SLOGE("Getfield error, cannot load persistent data");
2549 goto out;
2550 }
2551 }
2552
Rubin Xu85c01f92014-10-13 12:49:54 +01002553 // Read value from persistent entries. If the original value is split into multiple entries,
2554 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002555 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002556 // 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 -07002557 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002558 // value too small
2559 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2560 goto out;
2561 }
2562 rc = CRYPTO_GETFIELD_OK;
2563
2564 for (i = 1; /* break explicitly */; i++) {
2565 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002566 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002567 // If the fieldname is very long, we stop as soon as it begins to overflow the
2568 // maximum field length. At this point we have in fact fully read out the original
2569 // value because cryptfs_setfield would not allow fields with longer names to be
2570 // written in the first place.
2571 break;
2572 }
2573 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002574 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2575 // value too small.
2576 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2577 goto out;
2578 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002579 } else {
2580 // Exhaust all entries.
2581 break;
2582 }
2583 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002584 } else {
2585 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002586 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002587 }
2588
2589out:
2590 return rc;
2591}
2592
2593/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002594int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002595 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002596 SLOGE("Cannot set field when file encrypted");
2597 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002598 }
2599
Ken Sumrall160b4d62013-04-22 12:15:39 -07002600 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002601 /* 0 is success, negative values are error */
2602 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002603 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002604 unsigned int field_id;
2605 char temp_field[PROPERTY_KEY_MAX];
2606 unsigned int num_entries;
2607 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002608
2609 if (persist_data == NULL) {
2610 load_persistent_data();
2611 if (persist_data == NULL) {
2612 SLOGE("Setfield error, cannot load persistent data");
2613 goto out;
2614 }
2615 }
2616
2617 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002618 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002619 encrypted = 1;
2620 }
2621
Rubin Xu85c01f92014-10-13 12:49:54 +01002622 // Compute the number of entries required to store value, each entry can store up to
2623 // (PROPERTY_VALUE_MAX - 1) chars
2624 if (strlen(value) == 0) {
2625 // Empty value also needs one entry to store.
2626 num_entries = 1;
2627 } else {
2628 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2629 }
2630
2631 max_keylen = strlen(fieldname);
2632 if (num_entries > 1) {
2633 // Need an extra "_%d" suffix.
2634 max_keylen += 1 + log10(num_entries);
2635 }
2636 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2637 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002638 goto out;
2639 }
2640
Rubin Xu85c01f92014-10-13 12:49:54 +01002641 // Make sure we have enough space to write the new value
2642 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2643 persist_get_max_entries(encrypted)) {
2644 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2645 goto out;
2646 }
2647
2648 // Now that we know persist_data has enough space for value, let's delete the old field first
2649 // to make up space.
2650 persist_del_keys(fieldname, 0);
2651
2652 if (persist_set_key(fieldname, value, encrypted)) {
2653 // fail to set key, should not happen as we have already checked the available space
2654 SLOGE("persist_set_key() error during setfield()");
2655 goto out;
2656 }
2657
2658 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002659 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002660
2661 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2662 // fail to set key, should not happen as we have already checked the available space.
2663 SLOGE("persist_set_key() error during setfield()");
2664 goto out;
2665 }
2666 }
2667
Ken Sumrall160b4d62013-04-22 12:15:39 -07002668 /* If we are running encrypted, save the persistent data now */
2669 if (encrypted) {
2670 if (save_persistent_data()) {
2671 SLOGE("Setfield error, cannot save persistent data");
2672 goto out;
2673 }
2674 }
2675
Rubin Xu85c01f92014-10-13 12:49:54 +01002676 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002677
2678out:
2679 return rc;
2680}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002681
2682/* Checks userdata. Attempt to mount the volume if default-
2683 * encrypted.
2684 * On success trigger next init phase and return 0.
2685 * Currently do not handle failure - see TODO below.
2686 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002687int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002688 int crypt_type = cryptfs_get_password_type();
2689 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2690 SLOGE("Bad crypt type - error");
2691 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002692 SLOGD(
2693 "Password is not default - "
2694 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002695 property_set("vold.decrypt", "trigger_restart_min_framework");
2696 return 0;
2697 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2698 SLOGD("Password is default - restarting filesystem");
2699 cryptfs_restart_internal(0);
2700 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002701 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002702 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002703 }
2704
Paul Lawrence6bfed202014-07-28 12:47:22 -07002705 /** Corrupt. Allow us to boot into framework, which will detect bad
2706 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002707 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002708 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002709 return 0;
2710}
2711
2712/* Returns type of the password, default, pattern, pin or password.
2713 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002714int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002715 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002716 SLOGE("cryptfs_get_password_type not valid for file encryption");
2717 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002718 }
2719
Paul Lawrencef4faa572014-01-29 13:31:03 -08002720 struct crypt_mnt_ftr crypt_ftr;
2721
2722 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2723 SLOGE("Error getting crypt footer and key\n");
2724 return -1;
2725 }
2726
Paul Lawrence6bfed202014-07-28 12:47:22 -07002727 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2728 return -1;
2729 }
2730
Paul Lawrencef4faa572014-01-29 13:31:03 -08002731 return crypt_ftr.crypt_type;
2732}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002733
Paul Crowley14c8c072018-09-18 13:30:21 -07002734const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002735 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002736 SLOGE("cryptfs_get_password not valid for file encryption");
2737 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002738 }
2739
Paul Lawrence399317e2014-03-10 13:20:50 -07002740 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002741 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002742 if (now.tv_sec < password_expiry_time) {
2743 return password;
2744 } else {
2745 cryptfs_clear_password();
2746 return 0;
2747 }
2748}
2749
Paul Crowley14c8c072018-09-18 13:30:21 -07002750void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002751 if (password) {
2752 size_t len = strlen(password);
2753 memset(password, 0, len);
2754 free(password);
2755 password = 0;
2756 password_expiry_time = 0;
2757 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002758}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002759
Paul Crowley14c8c072018-09-18 13:30:21 -07002760int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002761 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2762 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002763}