blob: 0b5265079336ce1779f655cee7185b4276c0680c [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
27#include "EncryptInplace.h"
28#include "Ext4Crypt.h"
29#include "Keymaster.h"
30#include "Process.h"
31#include "ScryptParameters.h"
32#include "VoldUtil.h"
33#include "VolumeManager.h"
34#include "secontext.h"
35
Logan Chien3f2b1222018-05-02 11:39:03 +080036#include <android-base/properties.h>
Logan Chiend557d762018-05-02 11:36:45 +080037#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080039#include <cutils/properties.h>
Paul Crowley3b71fc52017-10-09 10:55:21 -070040#include <ext4_utils/ext4_crypt.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070041#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080045#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080046#include <logwrap/logwrap.h>
47#include <openssl/evp.h>
48#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080050
51#include <ctype.h>
52#include <errno.h>
53#include <fcntl.h>
54#include <inttypes.h>
55#include <libgen.h>
56#include <linux/dm-ioctl.h>
57#include <linux/kdev_t.h>
58#include <math.h>
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <sys/ioctl.h>
63#include <sys/mount.h>
64#include <sys/param.h>
65#include <sys/stat.h>
66#include <sys/types.h>
67#include <sys/wait.h>
68#include <time.h>
69#include <unistd.h>
70
Wei Wang4375f1b2017-02-24 17:43:01 -080071extern "C" {
72#include <crypto_scrypt.h>
73}
Mark Salyzyn3e971272014-01-21 13:27:04 -080074
Mark Salyzyn5eecc442014-02-12 14:16:14 -080075#define UNUSED __attribute__((unused))
76
Ken Sumrall8f869aa2010-12-03 03:47:09 -080077#define DM_CRYPT_BUF_SIZE 4096
78
Jason parks70a4b3f2011-01-28 10:10:47 -060079#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080080
81constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
82constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070083constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080084
85// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070086static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060087
Paul Crowley14c8c072018-09-18 13:30:21 -070088#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070089
Paul Lawrence3bd36d52015-06-09 13:37:44 -070090#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080091
Paul Lawrence3d99eba2015-11-20 07:07:19 -080092#define CRYPTO_BLOCK_DEVICE "userdata"
93
94#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
95
Ken Sumrall29d8da82011-05-18 17:20:07 -070096#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070097#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070098
Ken Sumralle919efe2012-09-29 17:07:41 -070099#define TABLE_LOAD_RETRIES 10
100
Shawn Willden47ba10d2014-09-03 17:07:06 -0600101#define RSA_KEY_SIZE 2048
102#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
103#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600104#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700105
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700106#define RETRY_MOUNT_ATTEMPTS 10
107#define RETRY_MOUNT_DELAY_SECONDS 1
108
Paul Crowley5afbc622017-11-27 09:42:17 -0800109#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
110
Paul Crowley73473332017-11-21 15:43:51 -0800111static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
112
Greg Kaiser59ad0182018-02-16 13:01:36 -0800113static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700114static char* saved_mount_point;
115static int master_key_saved = 0;
116static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800117
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700118/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700119static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000120 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700121}
122
123/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700124static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800125 if (ftr->keymaster_blob_size) {
126 SLOGI("Already have key");
127 return 0;
128 }
129
Paul Crowley14c8c072018-09-18 13:30:21 -0700130 int rc = keymaster_create_key_for_cryptfs_scrypt(
131 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
132 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000133 if (rc) {
134 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800135 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000136 ftr->keymaster_blob_size = 0;
137 }
138 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700139 return -1;
140 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000141 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700142}
143
Shawn Willdene17a9c42014-09-08 13:04:08 -0600144/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700145static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
146 const size_t object_size, unsigned char** signature,
147 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600148 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600149 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600150 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600151
Shawn Willdene17a9c42014-09-08 13:04:08 -0600152 // To sign a message with RSA, the message must satisfy two
153 // constraints:
154 //
155 // 1. The message, when interpreted as a big-endian numeric value, must
156 // be strictly less than the public modulus of the RSA key. Note
157 // that because the most significant bit of the public modulus is
158 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
159 // key), an n-bit message with most significant bit 0 always
160 // satisfies this requirement.
161 //
162 // 2. The message must have the same length in bits as the public
163 // modulus of the RSA key. This requirement isn't mathematically
164 // necessary, but is necessary to ensure consistency in
165 // implementations.
166 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600167 case KDF_SCRYPT_KEYMASTER:
168 // This ensures the most significant byte of the signed message
169 // is zero. We could have zero-padded to the left instead, but
170 // this approach is slightly more robust against changes in
171 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600172 // so) because we really should be using a proper deterministic
173 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800174 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600175 SLOGI("Signing safely-padded object");
176 break;
177 default:
178 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000179 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600180 }
Paul Crowley73473332017-11-21 15:43:51 -0800181 for (;;) {
182 auto result = keymaster_sign_object_for_cryptfs_scrypt(
183 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
184 to_sign_size, signature, signature_size);
185 switch (result) {
186 case KeymasterSignResult::ok:
187 return 0;
188 case KeymasterSignResult::upgrade:
189 break;
190 default:
191 return -1;
192 }
193 SLOGD("Upgrading key");
194 if (keymaster_upgrade_key_for_cryptfs_scrypt(
195 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
196 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
197 &ftr->keymaster_blob_size) != 0) {
198 SLOGE("Failed to upgrade key");
199 return -1;
200 }
201 if (put_crypt_ftr_and_key(ftr) != 0) {
202 SLOGE("Failed to write upgraded key to disk");
203 }
204 SLOGD("Key upgraded successfully");
205 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600206}
207
Paul Lawrence399317e2014-03-10 13:20:50 -0700208/* Store password when userdata is successfully decrypted and mounted.
209 * Cleared by cryptfs_clear_password
210 *
211 * To avoid a double prompt at boot, we need to store the CryptKeeper
212 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
213 * Since the entire framework is torn down and rebuilt after encryption,
214 * we have to use a daemon or similar to store the password. Since vold
215 * is secured against IPC except from system processes, it seems a reasonable
216 * place to store this.
217 *
218 * password should be cleared once it has been used.
219 *
220 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800221 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700222static char* password = 0;
223static int password_expiry_time = 0;
224static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800225
Paul Crowley14c8c072018-09-18 13:30:21 -0700226enum class RebootType { reboot, recovery, shutdown };
227static void cryptfs_reboot(RebootType rt) {
228 switch (rt) {
229 case RebootType::reboot:
230 property_set(ANDROID_RB_PROPERTY, "reboot");
231 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800232
Paul Crowley14c8c072018-09-18 13:30:21 -0700233 case RebootType::recovery:
234 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
235 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800236
Paul Crowley14c8c072018-09-18 13:30:21 -0700237 case RebootType::shutdown:
238 property_set(ANDROID_RB_PROPERTY, "shutdown");
239 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700240 }
Paul Lawrence87999172014-02-20 12:21:31 -0800241
Ken Sumralladfba362013-06-04 16:37:52 -0700242 sleep(20);
243
244 /* Shouldn't get here, reboot should happen before sleep times out */
245 return;
246}
247
Paul Crowley14c8c072018-09-18 13:30:21 -0700248static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800249 memset(io, 0, dataSize);
250 io->data_size = dataSize;
251 io->data_start = sizeof(struct dm_ioctl);
252 io->version[0] = 4;
253 io->version[1] = 0;
254 io->version[2] = 0;
255 io->flags = flags;
256 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100257 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800258 }
259}
260
Greg Kaiser38723f22018-02-16 13:35:35 -0800261namespace {
262
263struct CryptoType;
264
265// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700266const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800267
268struct CryptoType {
269 // We should only be constructing CryptoTypes as part of
270 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
271 // which isn't pure or fully protected as a concession to being able to
272 // do it all at compile time. Add new CryptoTypes in
273 // supported_crypto_types[] below.
274 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
275 constexpr CryptoType set_keysize(uint32_t size) const {
276 return CryptoType(this->property_name, this->crypto_name, size);
277 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700278 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800279 return CryptoType(property, this->crypto_name, this->keysize);
280 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700281 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800282 return CryptoType(this->property_name, crypto, this->keysize);
283 }
284
Paul Crowley14c8c072018-09-18 13:30:21 -0700285 constexpr const char* get_property_name() const { return property_name; }
286 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800287 constexpr uint32_t get_keysize() const { return keysize; }
288
Paul Crowley14c8c072018-09-18 13:30:21 -0700289 private:
290 const char* property_name;
291 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800292 uint32_t keysize;
293
Paul Crowley14c8c072018-09-18 13:30:21 -0700294 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800295 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700296 friend const CryptoType& get_crypto_type();
297 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800298};
299
300// We only want to parse this read-only property once. But we need to wait
301// until the system is initialized before we can read it. So we use a static
302// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700303const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800304 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
305 return crypto_type;
306}
307
308constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700309 .set_property_name("AES-128-CBC")
310 .set_crypto_name("aes-cbc-essiv:sha256")
311 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800312
313constexpr CryptoType supported_crypto_types[] = {
314 default_crypto_type,
Greg Kaiser38723f22018-02-16 13:35:35 -0800315 // Add new CryptoTypes here. Order is not important.
316};
317
Greg Kaiser38723f22018-02-16 13:35:35 -0800318// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
319// We confirm all supported_crypto_types have a small enough keysize and
320// had both set_property_name() and set_crypto_name() called.
321
322template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700323constexpr size_t array_length(T (&)[N]) {
324 return N;
325}
Greg Kaiser38723f22018-02-16 13:35:35 -0800326
327constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
328 return (index >= array_length(supported_crypto_types));
329}
330
Paul Crowley14c8c072018-09-18 13:30:21 -0700331constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800332 return ((crypto_type.get_property_name() != nullptr) &&
333 (crypto_type.get_crypto_name() != nullptr) &&
334 (crypto_type.get_keysize() <= MAX_KEY_LEN));
335}
336
337// Note in C++11 that constexpr functions can only have a single line.
338// So our code is a bit convoluted (using recursion instead of a loop),
339// but it's asserting at compile time that all of our key lengths are valid.
340constexpr bool validateSupportedCryptoTypes(size_t index) {
341 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700342 (isValidCryptoType(supported_crypto_types[index]) &&
343 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800344}
345
346static_assert(validateSupportedCryptoTypes(0),
347 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
348 "incompletely constructed.");
349// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
350
Greg Kaiser38723f22018-02-16 13:35:35 -0800351// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700352const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800353 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
354 char paramstr[PROPERTY_VALUE_MAX];
355
Paul Crowley14c8c072018-09-18 13:30:21 -0700356 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
357 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800358 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
359 return ctype;
360 }
361 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700362 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
363 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800364 return default_crypto_type;
365}
366
367} // namespace
368
Kenny Rootc4c70f12013-06-14 12:11:38 -0700369/**
370 * Gets the default device scrypt parameters for key derivation time tuning.
371 * The parameters should lead to about one second derivation time for the
372 * given device.
373 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700374static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700375 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000376 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700377
Paul Crowley63c18d32016-02-10 14:02:47 +0000378 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
379 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
380 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
381 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700382 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000383 ftr->N_factor = Nf;
384 ftr->r_factor = rf;
385 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700386}
387
Greg Kaiser57f9af62018-02-16 13:13:58 -0800388uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800389 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800390}
391
Paul Crowley14c8c072018-09-18 13:30:21 -0700392const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800393 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800394}
395
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200396static uint64_t get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800397 int fd, block_size;
398 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200399 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800400
Paul Crowley14c8c072018-09-18 13:30:21 -0700401 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800402 SLOGE("Cannot open device to get filesystem size ");
403 return 0;
404 }
405
406 if (lseek64(fd, 1024, SEEK_SET) < 0) {
407 SLOGE("Cannot seek to superblock");
408 return 0;
409 }
410
411 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
412 SLOGE("Cannot read superblock");
413 return 0;
414 }
415
416 close(fd);
417
Daniel Rosenberge82df162014-08-15 22:19:23 +0000418 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
419 SLOGE("Not a valid ext4 superblock");
420 return 0;
421 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800422 block_size = 1024 << sb.s_log_block_size;
423 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200424 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800425
426 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200427 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800428}
429
Paul Crowley14c8c072018-09-18 13:30:21 -0700430static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
431 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200432 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700433 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700434 char key_loc[PROPERTY_VALUE_MAX];
435 char real_blkdev[PROPERTY_VALUE_MAX];
436 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700437
Paul Crowley14c8c072018-09-18 13:30:21 -0700438 if (!cached_data) {
439 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700440
Paul Crowley14c8c072018-09-18 13:30:21 -0700441 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200442 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700443 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
444 * encryption info footer and key, and plenty of bytes to spare for future
445 * growth.
446 */
447 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200448 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700449 cached_data = 1;
450 } else {
451 SLOGE("Cannot get size of block device %s\n", real_blkdev);
452 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700453 } else {
454 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
455 cached_off = 0;
456 cached_data = 1;
457 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700458 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700459
Paul Crowley14c8c072018-09-18 13:30:21 -0700460 if (cached_data) {
461 if (metadata_fname) {
462 *metadata_fname = cached_metadata_fname;
463 }
464 if (off) {
465 *off = cached_off;
466 }
467 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700468 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700469
Paul Crowley14c8c072018-09-18 13:30:21 -0700470 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700471}
472
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800473/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700474static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800475 SHA256_CTX c;
476 SHA256_Init(&c);
477 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
478 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
479 SHA256_Final(crypt_ftr->sha256, &c);
480}
481
Ken Sumralle8744072011-01-18 22:01:55 -0800482/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800483 * update the failed mount count but not change the key.
484 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700485static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
486 int fd;
487 unsigned int cnt;
488 /* starting_off is set to the SEEK_SET offset
489 * where the crypto structure starts
490 */
491 off64_t starting_off;
492 int rc = -1;
493 char* fname = NULL;
494 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800495
Paul Crowley14c8c072018-09-18 13:30:21 -0700496 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800497
Paul Crowley14c8c072018-09-18 13:30:21 -0700498 if (get_crypt_ftr_info(&fname, &starting_off)) {
499 SLOGE("Unable to get crypt_ftr_info\n");
500 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800501 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700502 if (fname[0] != '/') {
503 SLOGE("Unexpected value for crypto key location\n");
504 return -1;
505 }
506 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
507 SLOGE("Cannot open footer file %s for put\n", fname);
508 return -1;
509 }
Ken Sumralle8744072011-01-18 22:01:55 -0800510
Paul Crowley14c8c072018-09-18 13:30:21 -0700511 /* Seek to the start of the crypt footer */
512 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
513 SLOGE("Cannot seek to real block device footer\n");
514 goto errout;
515 }
516
517 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
518 SLOGE("Cannot write real block device footer\n");
519 goto errout;
520 }
521
522 fstat(fd, &statbuf);
523 /* If the keys are kept on a raw block device, do not try to truncate it. */
524 if (S_ISREG(statbuf.st_mode)) {
525 if (ftruncate(fd, 0x4000)) {
526 SLOGE("Cannot set footer file size\n");
527 goto errout;
528 }
529 }
530
531 /* Success! */
532 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800533
534errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700535 close(fd);
536 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800537}
538
Paul Crowley14c8c072018-09-18 13:30:21 -0700539static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800540 struct crypt_mnt_ftr copy;
541 memcpy(&copy, crypt_ftr, sizeof(copy));
542 set_ftr_sha(&copy);
543 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
544}
545
Paul Crowley14c8c072018-09-18 13:30:21 -0700546static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700547 return TEMP_FAILURE_RETRY(read(fd, buff, len));
548}
549
Paul Crowley14c8c072018-09-18 13:30:21 -0700550static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700551 return TEMP_FAILURE_RETRY(write(fd, buff, len));
552}
553
Paul Crowley14c8c072018-09-18 13:30:21 -0700554static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700555 memset(pdata, 0, len);
556 pdata->persist_magic = PERSIST_DATA_MAGIC;
557 pdata->persist_valid_entries = 0;
558}
559
560/* A routine to update the passed in crypt_ftr to the lastest version.
561 * fd is open read/write on the device that holds the crypto footer and persistent
562 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
563 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
564 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700565static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700566 int orig_major = crypt_ftr->major_version;
567 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700568
Kenny Root7434b312013-06-14 11:29:53 -0700569 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700570 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700571 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700572
Kenny Rootc4c70f12013-06-14 12:11:38 -0700573 SLOGW("upgrading crypto footer to 1.1");
574
Paul Crowley14c8c072018-09-18 13:30:21 -0700575 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700576 if (pdata == NULL) {
577 SLOGE("Cannot allocate persisent data\n");
578 return;
579 }
580 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
581
582 /* Need to initialize the persistent data area */
583 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
584 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100585 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700586 return;
587 }
588 /* Write all zeros to the first copy, making it invalid */
589 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
590
591 /* Write a valid but empty structure to the second copy */
592 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
593 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
594
595 /* Update the footer */
596 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
597 crypt_ftr->persist_data_offset[0] = pdata_offset;
598 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
599 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100600 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700601 }
602
Paul Lawrencef4faa572014-01-29 13:31:03 -0800603 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700604 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800605 /* But keep the old kdf_type.
606 * It will get updated later to KDF_SCRYPT after the password has been verified.
607 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700608 crypt_ftr->kdf_type = KDF_PBKDF2;
609 get_device_scrypt_params(crypt_ftr);
610 crypt_ftr->minor_version = 2;
611 }
612
Paul Lawrencef4faa572014-01-29 13:31:03 -0800613 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
614 SLOGW("upgrading crypto footer to 1.3");
615 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
616 crypt_ftr->minor_version = 3;
617 }
618
Kenny Root7434b312013-06-14 11:29:53 -0700619 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
620 if (lseek64(fd, offset, SEEK_SET) == -1) {
621 SLOGE("Cannot seek to crypt footer\n");
622 return;
623 }
624 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700625 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700626}
627
Paul Crowley14c8c072018-09-18 13:30:21 -0700628static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
629 int fd;
630 unsigned int cnt;
631 off64_t starting_off;
632 int rc = -1;
633 char* fname = NULL;
634 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700635
Paul Crowley14c8c072018-09-18 13:30:21 -0700636 if (get_crypt_ftr_info(&fname, &starting_off)) {
637 SLOGE("Unable to get crypt_ftr_info\n");
638 return -1;
639 }
640 if (fname[0] != '/') {
641 SLOGE("Unexpected value for crypto key location\n");
642 return -1;
643 }
644 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
645 SLOGE("Cannot open footer file %s for get\n", fname);
646 return -1;
647 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800648
Paul Crowley14c8c072018-09-18 13:30:21 -0700649 /* Make sure it's 16 Kbytes in length */
650 fstat(fd, &statbuf);
651 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
652 SLOGE("footer file %s is not the expected size!\n", fname);
653 goto errout;
654 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700655
Paul Crowley14c8c072018-09-18 13:30:21 -0700656 /* Seek to the start of the crypt footer */
657 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
658 SLOGE("Cannot seek to real block device footer\n");
659 goto errout;
660 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700661
Paul Crowley14c8c072018-09-18 13:30:21 -0700662 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
663 SLOGE("Cannot read real block device footer\n");
664 goto errout;
665 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800666
Paul Crowley14c8c072018-09-18 13:30:21 -0700667 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
668 SLOGE("Bad magic for real block device %s\n", fname);
669 goto errout;
670 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800671
Paul Crowley14c8c072018-09-18 13:30:21 -0700672 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
673 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
674 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
675 goto errout;
676 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800677
Paul Crowley14c8c072018-09-18 13:30:21 -0700678 // We risk buffer overflows with oversized keys, so we just reject them.
679 // 0-sized keys are problematic (essentially by-passing encryption), and
680 // AES-CBC key wrapping only works for multiples of 16 bytes.
681 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
682 (crypt_ftr->keysize > MAX_KEY_LEN)) {
683 SLOGE(
684 "Invalid keysize (%u) for block device %s; Must be non-zero, "
685 "divisible by 16, and <= %d\n",
686 crypt_ftr->keysize, fname, MAX_KEY_LEN);
687 goto errout;
688 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800689
Paul Crowley14c8c072018-09-18 13:30:21 -0700690 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
691 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
692 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
693 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800694
Paul Crowley14c8c072018-09-18 13:30:21 -0700695 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
696 * copy on disk before returning.
697 */
698 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
699 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
700 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800701
Paul Crowley14c8c072018-09-18 13:30:21 -0700702 /* Success! */
703 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800704
705errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700706 close(fd);
707 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800708}
709
Paul Crowley14c8c072018-09-18 13:30:21 -0700710static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700711 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
712 crypt_ftr->persist_data_offset[1]) {
713 SLOGE("Crypt_ftr persist data regions overlap");
714 return -1;
715 }
716
717 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
718 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
719 return -1;
720 }
721
722 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700723 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700724 CRYPT_FOOTER_OFFSET) {
725 SLOGE("Persistent data extends past crypto footer");
726 return -1;
727 }
728
729 return 0;
730}
731
Paul Crowley14c8c072018-09-18 13:30:21 -0700732static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700733 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700734 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700735 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700736 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700737 int found = 0;
738 int fd;
739 int ret;
740 int i;
741
742 if (persist_data) {
743 /* Nothing to do, we've already loaded or initialized it */
744 return 0;
745 }
746
Ken Sumrall160b4d62013-04-22 12:15:39 -0700747 /* If not encrypted, just allocate an empty table and initialize it */
748 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700749 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800750 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700751 if (pdata) {
752 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
753 persist_data = pdata;
754 return 0;
755 }
756 return -1;
757 }
758
Paul Crowley14c8c072018-09-18 13:30:21 -0700759 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700760 return -1;
761 }
762
Paul Crowley14c8c072018-09-18 13:30:21 -0700763 if ((crypt_ftr.major_version < 1) ||
764 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700765 SLOGE("Crypt_ftr version doesn't support persistent data");
766 return -1;
767 }
768
769 if (get_crypt_ftr_info(&fname, NULL)) {
770 return -1;
771 }
772
773 ret = validate_persistent_data_storage(&crypt_ftr);
774 if (ret) {
775 return -1;
776 }
777
Paul Crowley14c8c072018-09-18 13:30:21 -0700778 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700779 if (fd < 0) {
780 SLOGE("Cannot open %s metadata file", fname);
781 return -1;
782 }
783
Wei Wang4375f1b2017-02-24 17:43:01 -0800784 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800785 if (pdata == NULL) {
786 SLOGE("Cannot allocate memory for persistent data");
787 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700788 }
789
790 for (i = 0; i < 2; i++) {
791 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
792 SLOGE("Cannot seek to read persistent data on %s", fname);
793 goto err2;
794 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700795 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700796 SLOGE("Error reading persistent data on iteration %d", i);
797 goto err2;
798 }
799 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
800 found = 1;
801 break;
802 }
803 }
804
805 if (!found) {
806 SLOGI("Could not find valid persistent data, creating");
807 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
808 }
809
810 /* Success */
811 persist_data = pdata;
812 close(fd);
813 return 0;
814
815err2:
816 free(pdata);
817
818err:
819 close(fd);
820 return -1;
821}
822
Paul Crowley14c8c072018-09-18 13:30:21 -0700823static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700824 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700825 struct crypt_persist_data* pdata;
826 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700827 off64_t write_offset;
828 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700829 int fd;
830 int ret;
831
832 if (persist_data == NULL) {
833 SLOGE("No persistent data to save");
834 return -1;
835 }
836
Paul Crowley14c8c072018-09-18 13:30:21 -0700837 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700838 return -1;
839 }
840
Paul Crowley14c8c072018-09-18 13:30:21 -0700841 if ((crypt_ftr.major_version < 1) ||
842 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700843 SLOGE("Crypt_ftr version doesn't support persistent data");
844 return -1;
845 }
846
847 ret = validate_persistent_data_storage(&crypt_ftr);
848 if (ret) {
849 return -1;
850 }
851
852 if (get_crypt_ftr_info(&fname, NULL)) {
853 return -1;
854 }
855
Paul Crowley14c8c072018-09-18 13:30:21 -0700856 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700857 if (fd < 0) {
858 SLOGE("Cannot open %s metadata file", fname);
859 return -1;
860 }
861
Wei Wang4375f1b2017-02-24 17:43:01 -0800862 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700863 if (pdata == NULL) {
864 SLOGE("Cannot allocate persistant data");
865 goto err;
866 }
867
868 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
869 SLOGE("Cannot seek to read persistent data on %s", fname);
870 goto err2;
871 }
872
873 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700874 SLOGE("Error reading persistent data before save");
875 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700876 }
877
878 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
879 /* The first copy is the curent valid copy, so write to
880 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700881 write_offset = crypt_ftr.persist_data_offset[1];
882 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700883 } else {
884 /* The second copy must be the valid copy, so write to
885 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700886 write_offset = crypt_ftr.persist_data_offset[0];
887 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700888 }
889
890 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100891 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700892 SLOGE("Cannot seek to write persistent data");
893 goto err2;
894 }
895 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700896 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100897 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700898 SLOGE("Cannot seek to erase previous persistent data");
899 goto err2;
900 }
901 fsync(fd);
902 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -0700903 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700904 SLOGE("Cannot write to erase previous persistent data");
905 goto err2;
906 }
907 fsync(fd);
908 } else {
909 SLOGE("Cannot write to save persistent data");
910 goto err2;
911 }
912
913 /* Success */
914 free(pdata);
915 close(fd);
916 return 0;
917
918err2:
919 free(pdata);
920err:
921 close(fd);
922 return -1;
923}
924
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800925/* Convert a binary key of specified length into an ascii hex string equivalent,
926 * without the leading 0x and with null termination
927 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700928static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
929 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700930 unsigned int i, a;
931 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800932
Paul Crowley14c8c072018-09-18 13:30:21 -0700933 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700934 /* For each byte, write out two ascii hex digits */
935 nibble = (master_key[i] >> 4) & 0xf;
936 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800937
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700938 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -0700939 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700940 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700942 /* Add the null termination */
943 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800944}
945
Paul Crowley14c8c072018-09-18 13:30:21 -0700946static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
947 const unsigned char* master_key, const char* real_blk_name,
948 const char* name, int fd, const char* extra_params) {
949 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
950 struct dm_ioctl* io;
951 struct dm_target_spec* tgt;
952 char* crypt_params;
953 // We need two ASCII characters to represent each byte, and need space for
954 // the '\0' terminator.
955 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
956 size_t buff_offset;
957 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800958
Paul Crowley14c8c072018-09-18 13:30:21 -0700959 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800960
Paul Crowley14c8c072018-09-18 13:30:21 -0700961 /* Load the mapping table for this device */
962 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800963
Paul Crowley14c8c072018-09-18 13:30:21 -0700964 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
965 io->target_count = 1;
966 tgt->status = 0;
967 tgt->sector_start = 0;
968 tgt->length = crypt_ftr->fs_size;
969 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800970
Paul Crowley14c8c072018-09-18 13:30:21 -0700971 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
972 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800973
Paul Crowley14c8c072018-09-18 13:30:21 -0700974 buff_offset = crypt_params - buffer;
975 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
976 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
977 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
978 crypt_params += strlen(crypt_params) + 1;
979 crypt_params =
980 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
981 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800982
Paul Crowley14c8c072018-09-18 13:30:21 -0700983 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
984 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
985 break;
986 }
987 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800988 }
Ken Sumralldb5e0262013-02-05 17:39:48 -0800989
Paul Crowley14c8c072018-09-18 13:30:21 -0700990 if (i == TABLE_LOAD_RETRIES) {
991 /* We failed to load the table, return an error */
992 return -1;
993 } else {
994 return i + 1;
995 }
Ken Sumralldb5e0262013-02-05 17:39:48 -0800996}
997
Paul Crowley14c8c072018-09-18 13:30:21 -0700998static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -0800999 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001000 struct dm_ioctl* io;
1001 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001002
Paul Crowley14c8c072018-09-18 13:30:21 -07001003 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001004
1005 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1006
1007 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1008 return -1;
1009 }
1010
1011 /* Iterate over the returned versions, looking for name of "crypt".
1012 * When found, get and return the version.
1013 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001014 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001015 while (v->next) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001016 if (!strcmp(v->name, "crypt")) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001017 /* We found the crypt driver, return the version, and get out */
1018 version[0] = v->version[0];
1019 version[1] = v->version[1];
1020 version[2] = v->version[2];
1021 return 0;
1022 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001023 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001024 }
1025
1026 return -1;
1027}
1028
Paul Crowley5afbc622017-11-27 09:42:17 -08001029static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1030 if (extra_params_vec.empty()) return "";
1031 std::string extra_params = std::to_string(extra_params_vec.size());
1032 for (const auto& p : extra_params_vec) {
1033 extra_params.append(" ");
1034 extra_params.append(p);
1035 }
1036 return extra_params;
1037}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001038
Paul Crowley5afbc622017-11-27 09:42:17 -08001039static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1040 const char* real_blk_name, char* crypto_blk_name, const char* name,
1041 uint32_t flags) {
1042 char buffer[DM_CRYPT_BUF_SIZE];
1043 struct dm_ioctl* io;
1044 unsigned int minor;
1045 int fd = 0;
1046 int err;
1047 int retval = -1;
1048 int version[3];
1049 int load_count;
1050 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001051
Paul Crowley5afbc622017-11-27 09:42:17 -08001052 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1053 SLOGE("Cannot open device-mapper\n");
1054 goto errout;
1055 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001056
Paul Crowley5afbc622017-11-27 09:42:17 -08001057 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001058
Paul Crowley5afbc622017-11-27 09:42:17 -08001059 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1060 err = ioctl(fd, DM_DEV_CREATE, io);
1061 if (err) {
1062 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1063 goto errout;
1064 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001065
Paul Crowley5afbc622017-11-27 09:42:17 -08001066 /* Get the device status, in particular, the name of it's device file */
1067 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1068 if (ioctl(fd, DM_DEV_STATUS, io)) {
1069 SLOGE("Cannot retrieve dm-crypt device status\n");
1070 goto errout;
1071 }
1072 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1073 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001074
Paul Crowley5afbc622017-11-27 09:42:17 -08001075 if (!get_dm_crypt_version(fd, name, version)) {
1076 /* Support for allow_discards was added in version 1.11.0 */
1077 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1078 extra_params_vec.emplace_back("allow_discards");
1079 }
1080 }
1081 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1082 extra_params_vec.emplace_back("allow_encrypt_override");
1083 }
1084 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1085 extra_params_as_string(extra_params_vec).c_str());
1086 if (load_count < 0) {
1087 SLOGE("Cannot load dm-crypt mapping table.\n");
1088 goto errout;
1089 } else if (load_count > 1) {
1090 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1091 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001092
Paul Crowley5afbc622017-11-27 09:42:17 -08001093 /* Resume this device to activate it */
1094 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001095
Paul Crowley5afbc622017-11-27 09:42:17 -08001096 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1097 SLOGE("Cannot resume the dm-crypt device\n");
1098 goto errout;
1099 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001100
Paul Crowley5afbc622017-11-27 09:42:17 -08001101 /* We made it here with no errors. Woot! */
1102 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001103
1104errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001105 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001106
Paul Crowley14c8c072018-09-18 13:30:21 -07001107 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001108}
1109
Paul Crowley14c8c072018-09-18 13:30:21 -07001110static int delete_crypto_blk_dev(const char* name) {
1111 int fd;
1112 char buffer[DM_CRYPT_BUF_SIZE];
1113 struct dm_ioctl* io;
1114 int retval = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001115
Paul Crowley14c8c072018-09-18 13:30:21 -07001116 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1117 SLOGE("Cannot open device-mapper\n");
1118 goto errout;
1119 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001120
Paul Crowley14c8c072018-09-18 13:30:21 -07001121 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001122
Paul Crowley14c8c072018-09-18 13:30:21 -07001123 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1124 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1125 SLOGE("Cannot remove dm-crypt device\n");
1126 goto errout;
1127 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001128
Paul Crowley14c8c072018-09-18 13:30:21 -07001129 /* We made it here with no errors. Woot! */
1130 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131
1132errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001133 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001134
Paul Crowley14c8c072018-09-18 13:30:21 -07001135 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001136}
1137
Paul Crowley14c8c072018-09-18 13:30:21 -07001138static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1139 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001140 SLOGI("Using pbkdf2 for cryptfs KDF");
1141
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001142 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001143 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1144 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001145}
1146
Paul Crowley14c8c072018-09-18 13:30:21 -07001147static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001148 SLOGI("Using scrypt for cryptfs KDF");
1149
Paul Crowley14c8c072018-09-18 13:30:21 -07001150 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001151
1152 int N = 1 << ftr->N_factor;
1153 int r = 1 << ftr->r_factor;
1154 int p = 1 << ftr->p_factor;
1155
1156 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001157 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001158 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001159
Paul Crowley14c8c072018-09-18 13:30:21 -07001160 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001161}
1162
Paul Crowley14c8c072018-09-18 13:30:21 -07001163static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1164 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001165 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1166
1167 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001168 size_t signature_size;
1169 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001170 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001171
1172 int N = 1 << ftr->N_factor;
1173 int r = 1 << ftr->r_factor;
1174 int p = 1 << ftr->p_factor;
1175
Paul Crowley14c8c072018-09-18 13:30:21 -07001176 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001177 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001178
1179 if (rc) {
1180 SLOGE("scrypt failed");
1181 return -1;
1182 }
1183
Paul Crowley14c8c072018-09-18 13:30:21 -07001184 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001185 SLOGE("Signing failed");
1186 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001187 }
1188
Paul Crowley14c8c072018-09-18 13:30:21 -07001189 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1190 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001191 free(signature);
1192
1193 if (rc) {
1194 SLOGE("scrypt failed");
1195 return -1;
1196 }
1197
1198 return 0;
1199}
1200
Paul Crowley14c8c072018-09-18 13:30:21 -07001201static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1202 const unsigned char* decrypted_master_key,
1203 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1204 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001205 EVP_CIPHER_CTX e_ctx;
1206 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001207 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001208
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001209 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001210 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001211
1212 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001213 case KDF_SCRYPT_KEYMASTER:
1214 if (keymaster_create_key(crypt_ftr)) {
1215 SLOGE("keymaster_create_key failed");
1216 return -1;
1217 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001218
Paul Crowley14c8c072018-09-18 13:30:21 -07001219 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1220 SLOGE("scrypt failed");
1221 return -1;
1222 }
1223 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001224
Paul Crowley14c8c072018-09-18 13:30:21 -07001225 case KDF_SCRYPT:
1226 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1227 SLOGE("scrypt failed");
1228 return -1;
1229 }
1230 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001231
Paul Crowley14c8c072018-09-18 13:30:21 -07001232 default:
1233 SLOGE("Invalid kdf_type");
1234 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001235 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001236
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001237 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001238 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001239 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1240 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001241 SLOGE("EVP_EncryptInit failed\n");
1242 return -1;
1243 }
1244 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001245
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001246 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001247 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1248 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001249 SLOGE("EVP_EncryptUpdate failed\n");
1250 return -1;
1251 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001252 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001253 SLOGE("EVP_EncryptFinal failed\n");
1254 return -1;
1255 }
1256
Greg Kaiser59ad0182018-02-16 13:01:36 -08001257 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001258 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1259 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001261
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001262 /* Store the scrypt of the intermediate key, so we can validate if it's a
1263 password error or mount error when things go wrong.
1264 Note there's no need to check for errors, since if this is incorrect, we
1265 simply won't wipe userdata, which is the correct default behavior
1266 */
1267 int N = 1 << crypt_ftr->N_factor;
1268 int r = 1 << crypt_ftr->r_factor;
1269 int p = 1 << crypt_ftr->p_factor;
1270
Paul Crowley14c8c072018-09-18 13:30:21 -07001271 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1272 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001273 sizeof(crypt_ftr->scrypted_intermediate_key));
1274
1275 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001276 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001277 }
1278
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001279 EVP_CIPHER_CTX_cleanup(&e_ctx);
1280
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001281 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001282}
1283
Paul Crowley14c8c072018-09-18 13:30:21 -07001284static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1285 const unsigned char* encrypted_master_key, size_t keysize,
1286 unsigned char* decrypted_master_key, kdf_func kdf,
1287 void* kdf_params, unsigned char** intermediate_key,
1288 size_t* intermediate_key_size) {
1289 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1290 EVP_CIPHER_CTX d_ctx;
1291 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001292
Paul Crowley14c8c072018-09-18 13:30:21 -07001293 /* Turn the password into an intermediate key and IV that can decrypt the
1294 master key */
1295 if (kdf(passwd, salt, ikey, kdf_params)) {
1296 SLOGE("kdf failed");
1297 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001298 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001299
Paul Crowley14c8c072018-09-18 13:30:21 -07001300 /* Initialize the decryption engine */
1301 EVP_CIPHER_CTX_init(&d_ctx);
1302 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1303 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1304 return -1;
1305 }
1306 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1307 /* Decrypt the master key */
1308 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1309 keysize)) {
1310 return -1;
1311 }
1312 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1313 return -1;
1314 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001315
Paul Crowley14c8c072018-09-18 13:30:21 -07001316 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1317 return -1;
1318 }
1319
1320 /* Copy intermediate key if needed by params */
1321 if (intermediate_key && intermediate_key_size) {
1322 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1323 if (*intermediate_key) {
1324 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1325 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1326 }
1327 }
1328
1329 EVP_CIPHER_CTX_cleanup(&d_ctx);
1330
1331 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001332}
1333
Paul Crowley14c8c072018-09-18 13:30:21 -07001334static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001335 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001336 *kdf = scrypt_keymaster;
1337 *kdf_params = ftr;
1338 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001339 *kdf = scrypt;
1340 *kdf_params = ftr;
1341 } else {
1342 *kdf = pbkdf2;
1343 *kdf_params = NULL;
1344 }
1345}
1346
Paul Crowley14c8c072018-09-18 13:30:21 -07001347static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1348 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1349 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001350 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001351 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001352 int ret;
1353
1354 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001355 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1356 decrypted_master_key, kdf, kdf_params, intermediate_key,
1357 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001358 if (ret != 0) {
1359 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001360 }
1361
1362 return ret;
1363}
1364
Paul Crowley14c8c072018-09-18 13:30:21 -07001365static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1366 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001367 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001368 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001369
1370 /* Get some random bits for a key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001371 fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001372 read(fd, key_buf, sizeof(key_buf));
1373 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001374 close(fd);
1375
1376 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001377 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001378}
1379
Paul Crowley14c8c072018-09-18 13:30:21 -07001380int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001381 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001382#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001383
1384 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001385 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001386 if (umount(mountpoint) == 0) {
1387 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001388 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001389
1390 if (errno == EINVAL) {
1391 /* EINVAL is returned if the directory is not a mountpoint,
1392 * i.e. there is no filesystem mounted there. So just get out.
1393 */
1394 break;
1395 }
1396
1397 err = errno;
1398
1399 /* If allowed, be increasingly aggressive before the last two retries */
1400 if (kill) {
1401 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1402 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001403 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001404 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1405 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001406 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001407 }
1408 }
1409
1410 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001411 }
1412
1413 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001414 SLOGD("unmounting %s succeeded\n", mountpoint);
1415 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001416 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001417 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1418 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1419 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001420 }
1421
1422 return rc;
1423}
1424
Paul Crowley14c8c072018-09-18 13:30:21 -07001425static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001426 // NOTE: post_fs_data results in init calling back around to vold, so all
1427 // callers to this method must be async
1428
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001429 /* Do the prep of the /data filesystem */
1430 property_set("vold.post_fs_data_done", "0");
1431 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001432 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001433
Ken Sumrallc5872692013-05-14 15:26:31 -07001434 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001435 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001436 /* We timed out to prep /data in time. Continue wait. */
1437 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001438 }
Wei Wang42e38102017-06-07 10:46:12 -07001439 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001440}
1441
Paul Crowley14c8c072018-09-18 13:30:21 -07001442static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001443 // Mark the footer as bad
1444 struct crypt_mnt_ftr crypt_ftr;
1445 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1446 SLOGE("Failed to get crypto footer - panic");
1447 return;
1448 }
1449
1450 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1451 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1452 SLOGE("Failed to set crypto footer - panic");
1453 return;
1454 }
1455}
1456
Paul Crowley14c8c072018-09-18 13:30:21 -07001457static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001458 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001459 SLOGE("Failed to mount tmpfs on data - panic");
1460 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001461 }
1462
1463 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1464 SLOGE("Failed to trigger post fs data - panic");
1465 return;
1466 }
1467
1468 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1469 SLOGE("Failed to trigger restart min framework - panic");
1470 return;
1471 }
1472}
1473
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001474/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001475static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001476 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001477 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001478 static int restart_successful = 0;
1479
1480 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001481 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001482 SLOGE("Encrypted filesystem not validated, aborting");
1483 return -1;
1484 }
1485
1486 if (restart_successful) {
1487 SLOGE("System already restarted with encrypted disk, aborting");
1488 return -1;
1489 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001490
Paul Lawrencef4faa572014-01-29 13:31:03 -08001491 if (restart_main) {
1492 /* Here is where we shut down the framework. The init scripts
1493 * start all services in one of three classes: core, main or late_start.
1494 * On boot, we start core and main. Now, we stop main, but not core,
1495 * as core includes vold and a few other really important things that
1496 * we need to keep running. Once main has stopped, we should be able
1497 * to umount the tmpfs /data, then mount the encrypted /data.
1498 * We then restart the class main, and also the class late_start.
1499 * At the moment, I've only put a few things in late_start that I know
1500 * are not needed to bring up the framework, and that also cause problems
1501 * with unmounting the tmpfs /data, but I hope to add add more services
1502 * to the late_start class as we optimize this to decrease the delay
1503 * till the user is asked for the password to the filesystem.
1504 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001505
Paul Lawrencef4faa572014-01-29 13:31:03 -08001506 /* The init files are setup to stop the class main when vold.decrypt is
1507 * set to trigger_reset_main.
1508 */
1509 property_set("vold.decrypt", "trigger_reset_main");
1510 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001511
Paul Lawrencef4faa572014-01-29 13:31:03 -08001512 /* Ugh, shutting down the framework is not synchronous, so until it
1513 * can be fixed, this horrible hack will wait a moment for it all to
1514 * shut down before proceeding. Without it, some devices cannot
1515 * restart the graphics services.
1516 */
1517 sleep(2);
1518 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001519
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001520 /* Now that the framework is shutdown, we should be able to umount()
1521 * the tmpfs filesystem, and mount the real one.
1522 */
1523
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001524 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1525 if (strlen(crypto_blkdev) == 0) {
1526 SLOGE("fs_crypto_blkdev not set\n");
1527 return -1;
1528 }
1529
Paul Crowley14c8c072018-09-18 13:30:21 -07001530 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001531 /* If ro.crypto.readonly is set to 1, mount the decrypted
1532 * filesystem readonly. This is used when /data is mounted by
1533 * recovery mode.
1534 */
1535 char ro_prop[PROPERTY_VALUE_MAX];
1536 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001537 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001538 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001539 if (rec) {
1540 rec->flags |= MS_RDONLY;
1541 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001542 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001543
Ken Sumralle5032c42012-04-01 23:58:44 -07001544 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001545 int retries = RETRY_MOUNT_ATTEMPTS;
1546 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001547
1548 /*
1549 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1550 * partitions in the fsck domain.
1551 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001552 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001553 SLOGE("Failed to setexeccon");
1554 return -1;
1555 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001556 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001557 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1558 /* TODO: invoke something similar to
1559 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1560 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001561 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001562 if (--retries) {
1563 sleep(RETRY_MOUNT_DELAY_SECONDS);
1564 } else {
1565 /* Let's hope that a reboot clears away whatever is keeping
1566 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001567 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001568 }
1569 } else {
1570 SLOGE("Failed to mount decrypted data");
1571 cryptfs_set_corrupt();
1572 cryptfs_trigger_restart_min_framework();
1573 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001574 if (setexeccon(NULL)) {
1575 SLOGE("Failed to setexeccon");
1576 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001577 return -1;
1578 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001579 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001580 if (setexeccon(NULL)) {
1581 SLOGE("Failed to setexeccon");
1582 return -1;
1583 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584
Ken Sumralle5032c42012-04-01 23:58:44 -07001585 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001586 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001587 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001588
1589 /* startup service classes main and late_start */
1590 property_set("vold.decrypt", "trigger_restart_framework");
1591 SLOGD("Just triggered restart_framework\n");
1592
1593 /* Give it a few moments to get started */
1594 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001595 }
1596
Ken Sumrall0cc16632011-01-18 20:32:26 -08001597 if (rc == 0) {
1598 restart_successful = 1;
1599 }
1600
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001601 return rc;
1602}
1603
Paul Crowley14c8c072018-09-18 13:30:21 -07001604int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001605 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001606 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001607 SLOGE("cryptfs_restart not valid for file encryption:");
1608 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001609 }
1610
Paul Lawrencef4faa572014-01-29 13:31:03 -08001611 /* Call internal implementation forcing a restart of main service group */
1612 return cryptfs_restart_internal(1);
1613}
1614
Paul Crowley14c8c072018-09-18 13:30:21 -07001615static int do_crypto_complete(const char* mount_point) {
1616 struct crypt_mnt_ftr crypt_ftr;
1617 char encrypted_state[PROPERTY_VALUE_MAX];
1618 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001619
Paul Crowley14c8c072018-09-18 13:30:21 -07001620 property_get("ro.crypto.state", encrypted_state, "");
1621 if (strcmp(encrypted_state, "encrypted")) {
1622 SLOGE("not running with encryption, aborting");
1623 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001624 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001625
Paul Crowley14c8c072018-09-18 13:30:21 -07001626 // crypto_complete is full disk encrypted status
1627 if (e4crypt_is_native()) {
1628 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1629 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001630
Paul Crowley14c8c072018-09-18 13:30:21 -07001631 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1632 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001633
Paul Crowley14c8c072018-09-18 13:30:21 -07001634 /*
1635 * Only report this error if key_loc is a file and it exists.
1636 * If the device was never encrypted, and /data is not mountable for
1637 * some reason, returning 1 should prevent the UI from presenting the
1638 * a "enter password" screen, or worse, a "press button to wipe the
1639 * device" screen.
1640 */
1641 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1642 SLOGE("master key file does not exist, aborting");
1643 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1644 } else {
1645 SLOGE("Error getting crypt footer and key\n");
1646 return CRYPTO_COMPLETE_BAD_METADATA;
1647 }
1648 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001649
Paul Crowley14c8c072018-09-18 13:30:21 -07001650 // Test for possible error flags
1651 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1652 SLOGE("Encryption process is partway completed\n");
1653 return CRYPTO_COMPLETE_PARTIAL;
1654 }
1655
1656 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1657 SLOGE("Encryption process was interrupted but cannot continue\n");
1658 return CRYPTO_COMPLETE_INCONSISTENT;
1659 }
1660
1661 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1662 SLOGE("Encryption is successful but data is corrupt\n");
1663 return CRYPTO_COMPLETE_CORRUPT;
1664 }
1665
1666 /* We passed the test! We shall diminish, and return to the west */
1667 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001668}
1669
Paul Crowley14c8c072018-09-18 13:30:21 -07001670static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1671 const char* mount_point, const char* label) {
1672 unsigned char decrypted_master_key[MAX_KEY_LEN];
1673 char crypto_blkdev[MAXPATHLEN];
1674 char real_blkdev[MAXPATHLEN];
1675 char tmp_mount_point[64];
1676 unsigned int orig_failed_decrypt_count;
1677 int rc;
1678 int use_keymaster = 0;
1679 int upgrade = 0;
1680 unsigned char* intermediate_key = 0;
1681 size_t intermediate_key_size = 0;
1682 int N = 1 << crypt_ftr->N_factor;
1683 int r = 1 << crypt_ftr->r_factor;
1684 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001685
Paul Crowley14c8c072018-09-18 13:30:21 -07001686 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1687 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001688
Paul Crowley14c8c072018-09-18 13:30:21 -07001689 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1690 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1691 &intermediate_key_size)) {
1692 SLOGE("Failed to decrypt master key\n");
1693 rc = -1;
1694 goto errout;
1695 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001696 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001697
Paul Crowley14c8c072018-09-18 13:30:21 -07001698 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001699
Paul Crowley14c8c072018-09-18 13:30:21 -07001700 // Create crypto block device - all (non fatal) code paths
1701 // need it
1702 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
1703 0)) {
1704 SLOGE("Error creating decrypted block device\n");
1705 rc = -1;
1706 goto errout;
1707 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001708
Paul Crowley14c8c072018-09-18 13:30:21 -07001709 /* Work out if the problem is the password or the data */
1710 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001711
Paul Crowley14c8c072018-09-18 13:30:21 -07001712 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1713 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1714 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001715
Paul Crowley14c8c072018-09-18 13:30:21 -07001716 // Does the key match the crypto footer?
1717 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1718 sizeof(scrypted_intermediate_key)) == 0) {
1719 SLOGI("Password matches");
1720 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001721 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001722 /* Try mounting the file system anyway, just in case the problem's with
1723 * the footer, not the key. */
1724 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1725 mkdir(tmp_mount_point, 0755);
1726 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1727 SLOGE("Error temp mounting decrypted block device\n");
1728 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001729
Paul Crowley14c8c072018-09-18 13:30:21 -07001730 rc = ++crypt_ftr->failed_decrypt_count;
1731 put_crypt_ftr_and_key(crypt_ftr);
1732 } else {
1733 /* Success! */
1734 SLOGI("Password did not match but decrypted drive mounted - continue");
1735 umount(tmp_mount_point);
1736 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001737 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001738 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001739
Paul Crowley14c8c072018-09-18 13:30:21 -07001740 if (rc == 0) {
1741 crypt_ftr->failed_decrypt_count = 0;
1742 if (orig_failed_decrypt_count != 0) {
1743 put_crypt_ftr_and_key(crypt_ftr);
1744 }
1745
1746 /* Save the name of the crypto block device
1747 * so we can mount it when restarting the framework. */
1748 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1749
1750 /* Also save a the master key so we can reencrypted the key
1751 * the key when we want to change the password on it. */
1752 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1753 saved_mount_point = strdup(mount_point);
1754 master_key_saved = 1;
1755 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1756 rc = 0;
1757
1758 // Upgrade if we're not using the latest KDF.
1759 use_keymaster = keymaster_check_compatibility();
1760 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1761 // Don't allow downgrade
1762 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1763 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1764 upgrade = 1;
1765 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1766 crypt_ftr->kdf_type = KDF_SCRYPT;
1767 upgrade = 1;
1768 }
1769
1770 if (upgrade) {
1771 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1772 crypt_ftr->master_key, crypt_ftr);
1773 if (!rc) {
1774 rc = put_crypt_ftr_and_key(crypt_ftr);
1775 }
1776 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1777
1778 // Do not fail even if upgrade failed - machine is bootable
1779 // Note that if this code is ever hit, there is a *serious* problem
1780 // since KDFs should never fail. You *must* fix the kdf before
1781 // proceeding!
1782 if (rc) {
1783 SLOGW(
1784 "Upgrade failed with error %d,"
1785 " but continuing with previous state",
1786 rc);
1787 rc = 0;
1788 }
1789 }
1790 }
1791
1792errout:
1793 if (intermediate_key) {
1794 memset(intermediate_key, 0, intermediate_key_size);
1795 free(intermediate_key);
1796 }
1797 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001798}
1799
Ken Sumrall29d8da82011-05-18 17:20:07 -07001800/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001801 * Called by vold when it's asked to mount an encrypted external
1802 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001803 * as any metadata is been stored in a separate, small partition. We
1804 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001805 *
1806 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001807 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001808int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1809 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001810 uint64_t nr_sec = 0;
1811 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001812 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001813 return -1;
1814 }
1815
Jeff Sharkey9c484982015-03-31 10:35:33 -07001816 struct crypt_mnt_ftr ext_crypt_ftr;
1817 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1818 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001819 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001820 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001821 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001822 uint32_t flags = 0;
1823 if (e4crypt_is_native() &&
1824 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1825 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001826
Paul Crowley385cb8c2018-03-29 13:27:23 -07001827 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001828}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001829
Jeff Sharkey9c484982015-03-31 10:35:33 -07001830/*
1831 * Called by vold when it's asked to unmount an encrypted external
1832 * storage volume.
1833 */
1834int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001835 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001836}
1837
Paul Crowley14c8c072018-09-18 13:30:21 -07001838int cryptfs_crypto_complete(void) {
1839 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001840}
1841
Paul Crowley14c8c072018-09-18 13:30:21 -07001842int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001843 char encrypted_state[PROPERTY_VALUE_MAX];
1844 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001845 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1846 SLOGE(
1847 "encrypted fs already validated or not running with encryption,"
1848 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001849 return -1;
1850 }
1851
1852 if (get_crypt_ftr_and_key(crypt_ftr)) {
1853 SLOGE("Error getting crypt footer and key");
1854 return -1;
1855 }
1856
1857 return 0;
1858}
1859
Paul Crowley14c8c072018-09-18 13:30:21 -07001860int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001861 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001862 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001863 SLOGE("cryptfs_check_passwd not valid for file encryption");
1864 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001865 }
1866
Paul Lawrencef4faa572014-01-29 13:31:03 -08001867 struct crypt_mnt_ftr crypt_ftr;
1868 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001869
Paul Lawrencef4faa572014-01-29 13:31:03 -08001870 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001871 if (rc) {
1872 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001873 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001874 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001875
Paul Crowley14c8c072018-09-18 13:30:21 -07001876 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001877 if (rc) {
1878 SLOGE("Password did not match");
1879 return rc;
1880 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001881
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001882 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1883 // Here we have a default actual password but a real password
1884 // we must test against the scrypted value
1885 // First, we must delete the crypto block device that
1886 // test_mount_encrypted_fs leaves behind as a side effect
1887 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001888 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1889 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001890 if (rc) {
1891 SLOGE("Default password did not match on reboot encryption");
1892 return rc;
1893 }
1894
1895 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1896 put_crypt_ftr_and_key(&crypt_ftr);
1897 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1898 if (rc) {
1899 SLOGE("Could not change password on reboot encryption");
1900 return rc;
1901 }
1902 }
1903
1904 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001905 cryptfs_clear_password();
1906 password = strdup(passwd);
1907 struct timespec now;
1908 clock_gettime(CLOCK_BOOTTIME, &now);
1909 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001910 }
1911
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001912 return rc;
1913}
1914
Paul Crowley14c8c072018-09-18 13:30:21 -07001915int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001916 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001917 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001918 char encrypted_state[PROPERTY_VALUE_MAX];
1919 int rc;
1920
1921 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001922 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001923 SLOGE("device not encrypted, aborting");
1924 return -2;
1925 }
1926
1927 if (!master_key_saved) {
1928 SLOGE("encrypted fs not yet mounted, aborting");
1929 return -1;
1930 }
1931
1932 if (!saved_mount_point) {
1933 SLOGE("encrypted fs failed to save mount point, aborting");
1934 return -1;
1935 }
1936
Ken Sumrall160b4d62013-04-22 12:15:39 -07001937 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001938 SLOGE("Error getting crypt footer and key\n");
1939 return -1;
1940 }
1941
1942 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1943 /* If the device has no password, then just say the password is valid */
1944 rc = 0;
1945 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001946 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001947 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1948 /* They match, the password is correct */
1949 rc = 0;
1950 } else {
1951 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1952 sleep(1);
1953 rc = 1;
1954 }
1955 }
1956
1957 return rc;
1958}
1959
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001960/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08001961 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001962 * Presumably, at a minimum, the caller will update the
1963 * filesystem size and crypto_type_name after calling this function.
1964 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001965static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001966 off64_t off;
1967
1968 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001969 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001970 ftr->major_version = CURRENT_MAJOR_VERSION;
1971 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001972 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08001973 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07001974
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001975 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001976 case 1:
1977 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1978 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001979
Paul Crowley14c8c072018-09-18 13:30:21 -07001980 case 0:
1981 ftr->kdf_type = KDF_SCRYPT;
1982 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001983
Paul Crowley14c8c072018-09-18 13:30:21 -07001984 default:
1985 SLOGE("keymaster_check_compatibility failed");
1986 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001987 }
1988
Kenny Rootc4c70f12013-06-14 12:11:38 -07001989 get_device_scrypt_params(ftr);
1990
Ken Sumrall160b4d62013-04-22 12:15:39 -07001991 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1992 if (get_crypt_ftr_info(NULL, &off) == 0) {
1993 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07001994 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001995 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001996
1997 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001998}
1999
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002000#define FRAMEWORK_BOOT_WAIT 60
2001
Paul Crowley14c8c072018-09-18 13:30:21 -07002002static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2003 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002004 if (fd == -1) {
2005 SLOGE("Error opening file %s", filename);
2006 return -1;
2007 }
2008
2009 char block[CRYPT_INPLACE_BUFSIZE];
2010 memset(block, 0, sizeof(block));
2011 if (unix_read(fd, block, sizeof(block)) < 0) {
2012 SLOGE("Error reading file %s", filename);
2013 close(fd);
2014 return -1;
2015 }
2016
2017 close(fd);
2018
2019 SHA256_CTX c;
2020 SHA256_Init(&c);
2021 SHA256_Update(&c, block, sizeof(block));
2022 SHA256_Final(buf, &c);
2023
2024 return 0;
2025}
2026
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002027static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2028 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002029 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002030 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002031
Paul Lawrence87999172014-02-20 12:21:31 -08002032 /* The size of the userdata partition, and add in the vold volumes below */
2033 tot_encryption_size = crypt_ftr->fs_size;
2034
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002035 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002036 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002037
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002038 if (rc == ENABLE_INPLACE_ERR_DEV) {
2039 /* Hack for b/17898962 */
2040 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2041 cryptfs_reboot(RebootType::reboot);
2042 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002043
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002044 if (!rc) {
2045 crypt_ftr->encrypted_upto = cur_encryption_done;
2046 }
Paul Lawrence87999172014-02-20 12:21:31 -08002047
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002048 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2049 /* The inplace routine never actually sets the progress to 100% due
2050 * to the round down nature of integer division, so set it here */
2051 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002052 }
2053
2054 return rc;
2055}
2056
Paul Crowleyb64933a2017-10-31 08:25:55 -07002057static int vold_unmountAll(void) {
2058 VolumeManager* vm = VolumeManager::Instance();
2059 return vm->unmountAll();
2060}
2061
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002062int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002063 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002064 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002065 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002066 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002067 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002068 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002069 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002070 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002071 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002072 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002073 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002074 bool onlyCreateHeader = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002075
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002076 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002077 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2078 /* An encryption was underway and was interrupted */
2079 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2080 crypt_ftr.encrypted_upto = 0;
2081 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002082
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002083 /* At this point, we are in an inconsistent state. Until we successfully
2084 complete encryption, a reboot will leave us broken. So mark the
2085 encryption failed in case that happens.
2086 On successfully completing encryption, remove this flag */
2087 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002088
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002089 put_crypt_ftr_and_key(&crypt_ftr);
2090 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2091 if (!check_ftr_sha(&crypt_ftr)) {
2092 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2093 put_crypt_ftr_and_key(&crypt_ftr);
2094 goto error_unencrypted;
2095 }
2096
2097 /* Doing a reboot-encryption*/
2098 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2099 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2100 rebootEncryption = true;
2101 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002102 } else {
2103 // We don't want to accidentally reference invalid data.
2104 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002105 }
2106
2107 property_get("ro.crypto.state", encrypted_state, "");
2108 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2109 SLOGE("Device is already running encrypted, aborting");
2110 goto error_unencrypted;
2111 }
2112
2113 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002114 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2115 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002116
Ken Sumrall3ed82362011-01-28 23:31:16 -08002117 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002118 uint64_t nr_sec;
2119 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002120 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2121 goto error_unencrypted;
2122 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002123
2124 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002125 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002126 uint64_t fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002127 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002128 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002129
Paul Lawrence87999172014-02-20 12:21:31 -08002130 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002131
2132 if (fs_size_sec > max_fs_size_sec) {
2133 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2134 goto error_unencrypted;
2135 }
2136 }
2137
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002138 /* Get a wakelock as this may take a while, and we don't want the
2139 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2140 * wants to keep the screen on, it can grab a full wakelock.
2141 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002142 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002143 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2144
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002145 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002146 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002147 */
2148 property_set("vold.decrypt", "trigger_shutdown_framework");
2149 SLOGD("Just asked init to shut down class main\n");
2150
Jeff Sharkey9c484982015-03-31 10:35:33 -07002151 /* Ask vold to unmount all devices that it manages */
2152 if (vold_unmountAll()) {
2153 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002154 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002155
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002156 /* no_ui means we are being called from init, not settings.
2157 Now we always reboot from settings, so !no_ui means reboot
2158 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002159 if (!no_ui) {
2160 /* Try fallback, which is to reboot and try there */
2161 onlyCreateHeader = true;
2162 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2163 if (breadcrumb == 0) {
2164 SLOGE("Failed to create breadcrumb file");
2165 goto error_shutting_down;
2166 }
2167 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002168 }
2169
2170 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002171 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002172 /* Now that /data is unmounted, we need to mount a tmpfs
2173 * /data, set a property saying we're doing inplace encryption,
2174 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002175 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002176 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002177 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002178 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002179 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002180 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002181
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002182 /* restart the framework. */
2183 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002184 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002185
Ken Sumrall92736ef2012-10-17 20:57:14 -07002186 /* Ugh, shutting down the framework is not synchronous, so until it
2187 * can be fixed, this horrible hack will wait a moment for it all to
2188 * shut down before proceeding. Without it, some devices cannot
2189 * restart the graphics services.
2190 */
2191 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002192 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002193
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002194 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002195 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002196 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002197 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2198 goto error_shutting_down;
2199 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002200
Paul Lawrence87999172014-02-20 12:21:31 -08002201 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002202 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002203 } else {
2204 crypt_ftr.fs_size = nr_sec;
2205 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002206 /* At this point, we are in an inconsistent state. Until we successfully
2207 complete encryption, a reboot will leave us broken. So mark the
2208 encryption failed in case that happens.
2209 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002210 if (onlyCreateHeader) {
2211 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2212 } else {
2213 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2214 }
Paul Lawrence87999172014-02-20 12:21:31 -08002215 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002216 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2217 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002218
Paul Lawrence87999172014-02-20 12:21:31 -08002219 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002220 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2221 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002222 SLOGE("Cannot create encrypted master key\n");
2223 goto error_shutting_down;
2224 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002225
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002226 /* Replace scrypted intermediate key if we are preparing for a reboot */
2227 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002228 unsigned char fake_master_key[MAX_KEY_LEN];
2229 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002230 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002231 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2232 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002233 }
2234
Paul Lawrence87999172014-02-20 12:21:31 -08002235 /* Write the key to the end of the partition */
2236 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002237
Paul Lawrence87999172014-02-20 12:21:31 -08002238 /* If any persistent data has been remembered, save it.
2239 * If none, create a valid empty table and save that.
2240 */
2241 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002242 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2243 if (pdata) {
2244 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2245 persist_data = pdata;
2246 }
Paul Lawrence87999172014-02-20 12:21:31 -08002247 }
2248 if (persist_data) {
2249 save_persistent_data();
2250 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002251 }
2252
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002253 if (onlyCreateHeader) {
2254 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002255 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002256 }
2257
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002258 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002259 /* startup service classes main and late_start */
2260 property_set("vold.decrypt", "trigger_restart_min_framework");
2261 SLOGD("Just triggered restart_min_framework\n");
2262
2263 /* OK, the framework is restarted and will soon be showing a
2264 * progress bar. Time to setup an encrypted mapping, and
2265 * either write a new filesystem, or encrypt in place updating
2266 * the progress bar as we work.
2267 */
2268 }
2269
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002270 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002271 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002272 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002273
Paul Lawrence87999172014-02-20 12:21:31 -08002274 /* If we are continuing, check checksums match */
2275 rc = 0;
2276 if (previously_encrypted_upto) {
2277 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2278 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002279
Paul Crowley14c8c072018-09-18 13:30:21 -07002280 if (!rc &&
2281 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002282 SLOGE("Checksums do not match - trigger wipe");
2283 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002284 }
2285 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002286
Paul Lawrence87999172014-02-20 12:21:31 -08002287 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002288 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002289 previously_encrypted_upto);
2290 }
2291
2292 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002293 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002294 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002295 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002296 SLOGE("Error calculating checksum for continuing encryption");
2297 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002298 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002299 }
2300
2301 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002302 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002303
Paul Crowley14c8c072018-09-18 13:30:21 -07002304 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002305 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002306 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002307
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002308 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002309 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2310 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002311 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002312 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002313
Paul Lawrence6bfed202014-07-28 12:47:22 -07002314 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002315
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002316 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2317 char value[PROPERTY_VALUE_MAX];
2318 property_get("ro.crypto.state", value, "");
2319 if (!strcmp(value, "")) {
2320 /* default encryption - continue first boot sequence */
2321 property_set("ro.crypto.state", "encrypted");
2322 property_set("ro.crypto.type", "block");
2323 release_wake_lock(lockid);
2324 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2325 // Bring up cryptkeeper that will check the password and set it
2326 property_set("vold.decrypt", "trigger_shutdown_framework");
2327 sleep(2);
2328 property_set("vold.encrypt_progress", "");
2329 cryptfs_trigger_restart_min_framework();
2330 } else {
2331 cryptfs_check_passwd(DEFAULT_PASSWORD);
2332 cryptfs_restart_internal(1);
2333 }
2334 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002335 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002336 sleep(2); /* Give the UI a chance to show 100% progress */
2337 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002338 }
Paul Lawrence87999172014-02-20 12:21:31 -08002339 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002340 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002341 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002342 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002343 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002344 char value[PROPERTY_VALUE_MAX];
2345
Ken Sumrall319369a2012-06-27 16:30:18 -07002346 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002347 if (!strcmp(value, "1")) {
2348 /* wipe data if encryption failed */
2349 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002350 std::string err;
2351 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002352 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002353 if (!write_bootloader_message(options, &err)) {
2354 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002355 }
Josh Gaofec44372017-08-28 13:22:55 -07002356 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002357 } else {
2358 /* set property to trigger dialog */
2359 property_set("vold.encrypt_progress", "error_partially_encrypted");
2360 release_wake_lock(lockid);
2361 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002362 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002363 }
2364
Ken Sumrall3ed82362011-01-28 23:31:16 -08002365 /* hrm, the encrypt step claims success, but the reboot failed.
2366 * This should not happen.
2367 * Set the property and return. Hope the framework can deal with it.
2368 */
2369 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002370 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002371 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002372
2373error_unencrypted:
2374 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002375 if (lockid[0]) {
2376 release_wake_lock(lockid);
2377 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002378 return -1;
2379
2380error_shutting_down:
2381 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2382 * but the framework is stopped and not restarted to show the error, so it's up to
2383 * vold to restart the system.
2384 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002385 SLOGE(
2386 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2387 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002388 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002389
2390 /* shouldn't get here */
2391 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002392 if (lockid[0]) {
2393 release_wake_lock(lockid);
2394 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002395 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002396}
2397
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002398int cryptfs_enable(int type, const char* passwd, int no_ui) {
2399 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002400}
2401
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002402int cryptfs_enable_default(int no_ui) {
2403 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002404}
2405
Paul Crowley14c8c072018-09-18 13:30:21 -07002406int cryptfs_changepw(int crypt_type, const char* newpw) {
Paul Crowley38132a12016-02-09 09:50:32 +00002407 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002408 SLOGE("cryptfs_changepw not valid for file encryption");
2409 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002410 }
2411
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002412 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002413 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002414
2415 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002416 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002417 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002418 return -1;
2419 }
2420
Paul Lawrencef4faa572014-01-29 13:31:03 -08002421 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2422 SLOGE("Invalid crypt_type %d", crypt_type);
2423 return -1;
2424 }
2425
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002426 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002427 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002428 SLOGE("Error getting crypt footer and key");
2429 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002430 }
2431
Paul Lawrencef4faa572014-01-29 13:31:03 -08002432 crypt_ftr.crypt_type = crypt_type;
2433
Paul Crowley14c8c072018-09-18 13:30:21 -07002434 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2435 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002436 if (rc) {
2437 SLOGE("Encrypt master key failed: %d", rc);
2438 return -1;
2439 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002440 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002441 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002442
2443 return 0;
2444}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002445
Rubin Xu85c01f92014-10-13 12:49:54 +01002446static unsigned int persist_get_max_entries(int encrypted) {
2447 struct crypt_mnt_ftr crypt_ftr;
2448 unsigned int dsize;
2449 unsigned int max_persistent_entries;
2450
2451 /* If encrypted, use the values from the crypt_ftr, otherwise
2452 * use the values for the current spec.
2453 */
2454 if (encrypted) {
2455 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2456 return -1;
2457 }
2458 dsize = crypt_ftr.persist_data_size;
2459 } else {
2460 dsize = CRYPT_PERSIST_DATA_SIZE;
2461 }
2462
Paul Crowley14c8c072018-09-18 13:30:21 -07002463 max_persistent_entries =
2464 (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
Rubin Xu85c01f92014-10-13 12:49:54 +01002465
2466 return max_persistent_entries;
2467}
2468
Paul Crowley14c8c072018-09-18 13:30:21 -07002469static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002470 unsigned int i;
2471
2472 if (persist_data == NULL) {
2473 return -1;
2474 }
2475 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2476 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2477 /* We found it! */
2478 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2479 return 0;
2480 }
2481 }
2482
2483 return -1;
2484}
2485
Paul Crowley14c8c072018-09-18 13:30:21 -07002486static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002487 unsigned int i;
2488 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002489 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002490
2491 if (persist_data == NULL) {
2492 return -1;
2493 }
2494
Rubin Xu85c01f92014-10-13 12:49:54 +01002495 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002496
2497 num = persist_data->persist_valid_entries;
2498
2499 for (i = 0; i < num; i++) {
2500 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2501 /* We found an existing entry, update it! */
2502 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2503 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2504 return 0;
2505 }
2506 }
2507
2508 /* We didn't find it, add it to the end, if there is room */
2509 if (persist_data->persist_valid_entries < max_persistent_entries) {
2510 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2511 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2512 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2513 persist_data->persist_valid_entries++;
2514 return 0;
2515 }
2516
2517 return -1;
2518}
2519
Rubin Xu85c01f92014-10-13 12:49:54 +01002520/**
2521 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2522 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2523 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002524int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002525 std::string key_ = key;
2526 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002527
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002528 std::string parsed_field;
2529 unsigned parsed_index;
2530
2531 std::string::size_type split = key_.find_last_of('_');
2532 if (split == std::string::npos) {
2533 parsed_field = key_;
2534 parsed_index = 0;
2535 } else {
2536 parsed_field = key_.substr(0, split);
2537 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002538 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002539
2540 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002541}
2542
2543/*
2544 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2545 * remaining entries starting from index will be deleted.
2546 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2547 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2548 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2549 *
2550 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002551static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002552 unsigned int i;
2553 unsigned int j;
2554 unsigned int num;
2555
2556 if (persist_data == NULL) {
2557 return PERSIST_DEL_KEY_ERROR_OTHER;
2558 }
2559
2560 num = persist_data->persist_valid_entries;
2561
Paul Crowley14c8c072018-09-18 13:30:21 -07002562 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002563 // Filter out to-be-deleted entries in place.
2564 for (i = 0; i < num; i++) {
2565 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2566 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2567 j++;
2568 }
2569 }
2570
2571 if (j < num) {
2572 persist_data->persist_valid_entries = j;
2573 // Zeroise the remaining entries
2574 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2575 return PERSIST_DEL_KEY_OK;
2576 } else {
2577 // Did not find an entry matching the given fieldname
2578 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2579 }
2580}
2581
Paul Crowley14c8c072018-09-18 13:30:21 -07002582static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002583 unsigned int i;
2584 unsigned int count;
2585
2586 if (persist_data == NULL) {
2587 return -1;
2588 }
2589
2590 count = 0;
2591 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2592 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2593 count++;
2594 }
2595 }
2596
2597 return count;
2598}
2599
Ken Sumrall160b4d62013-04-22 12:15:39 -07002600/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002601int cryptfs_getfield(const char* fieldname, char* value, int len) {
Paul Crowley38132a12016-02-09 09:50:32 +00002602 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002603 SLOGE("Cannot get field when file encrypted");
2604 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002605 }
2606
Ken Sumrall160b4d62013-04-22 12:15:39 -07002607 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002608 /* CRYPTO_GETFIELD_OK is success,
2609 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2610 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2611 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002612 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002613 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2614 int i;
2615 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002616
2617 if (persist_data == NULL) {
2618 load_persistent_data();
2619 if (persist_data == NULL) {
2620 SLOGE("Getfield error, cannot load persistent data");
2621 goto out;
2622 }
2623 }
2624
Rubin Xu85c01f92014-10-13 12:49:54 +01002625 // Read value from persistent entries. If the original value is split into multiple entries,
2626 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002627 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002628 // 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 -07002629 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002630 // value too small
2631 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2632 goto out;
2633 }
2634 rc = CRYPTO_GETFIELD_OK;
2635
2636 for (i = 1; /* break explicitly */; i++) {
2637 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002638 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002639 // If the fieldname is very long, we stop as soon as it begins to overflow the
2640 // maximum field length. At this point we have in fact fully read out the original
2641 // value because cryptfs_setfield would not allow fields with longer names to be
2642 // written in the first place.
2643 break;
2644 }
2645 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002646 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2647 // value too small.
2648 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2649 goto out;
2650 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002651 } else {
2652 // Exhaust all entries.
2653 break;
2654 }
2655 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002656 } else {
2657 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002658 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002659 }
2660
2661out:
2662 return rc;
2663}
2664
2665/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002666int cryptfs_setfield(const char* fieldname, const char* value) {
Paul Crowley38132a12016-02-09 09:50:32 +00002667 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002668 SLOGE("Cannot set field when file encrypted");
2669 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002670 }
2671
Ken Sumrall160b4d62013-04-22 12:15:39 -07002672 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002673 /* 0 is success, negative values are error */
2674 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002675 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002676 unsigned int field_id;
2677 char temp_field[PROPERTY_KEY_MAX];
2678 unsigned int num_entries;
2679 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002680
2681 if (persist_data == NULL) {
2682 load_persistent_data();
2683 if (persist_data == NULL) {
2684 SLOGE("Setfield error, cannot load persistent data");
2685 goto out;
2686 }
2687 }
2688
2689 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002690 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002691 encrypted = 1;
2692 }
2693
Rubin Xu85c01f92014-10-13 12:49:54 +01002694 // Compute the number of entries required to store value, each entry can store up to
2695 // (PROPERTY_VALUE_MAX - 1) chars
2696 if (strlen(value) == 0) {
2697 // Empty value also needs one entry to store.
2698 num_entries = 1;
2699 } else {
2700 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2701 }
2702
2703 max_keylen = strlen(fieldname);
2704 if (num_entries > 1) {
2705 // Need an extra "_%d" suffix.
2706 max_keylen += 1 + log10(num_entries);
2707 }
2708 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2709 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002710 goto out;
2711 }
2712
Rubin Xu85c01f92014-10-13 12:49:54 +01002713 // Make sure we have enough space to write the new value
2714 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2715 persist_get_max_entries(encrypted)) {
2716 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2717 goto out;
2718 }
2719
2720 // Now that we know persist_data has enough space for value, let's delete the old field first
2721 // to make up space.
2722 persist_del_keys(fieldname, 0);
2723
2724 if (persist_set_key(fieldname, value, encrypted)) {
2725 // fail to set key, should not happen as we have already checked the available space
2726 SLOGE("persist_set_key() error during setfield()");
2727 goto out;
2728 }
2729
2730 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002731 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002732
2733 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2734 // fail to set key, should not happen as we have already checked the available space.
2735 SLOGE("persist_set_key() error during setfield()");
2736 goto out;
2737 }
2738 }
2739
Ken Sumrall160b4d62013-04-22 12:15:39 -07002740 /* If we are running encrypted, save the persistent data now */
2741 if (encrypted) {
2742 if (save_persistent_data()) {
2743 SLOGE("Setfield error, cannot save persistent data");
2744 goto out;
2745 }
2746 }
2747
Rubin Xu85c01f92014-10-13 12:49:54 +01002748 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002749
2750out:
2751 return rc;
2752}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002753
2754/* Checks userdata. Attempt to mount the volume if default-
2755 * encrypted.
2756 * On success trigger next init phase and return 0.
2757 * Currently do not handle failure - see TODO below.
2758 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002759int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002760 int crypt_type = cryptfs_get_password_type();
2761 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2762 SLOGE("Bad crypt type - error");
2763 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002764 SLOGD(
2765 "Password is not default - "
2766 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002767 property_set("vold.decrypt", "trigger_restart_min_framework");
2768 return 0;
2769 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2770 SLOGD("Password is default - restarting filesystem");
2771 cryptfs_restart_internal(0);
2772 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002773 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002774 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002775 }
2776
Paul Lawrence6bfed202014-07-28 12:47:22 -07002777 /** Corrupt. Allow us to boot into framework, which will detect bad
2778 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002779 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002780 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002781 return 0;
2782}
2783
2784/* Returns type of the password, default, pattern, pin or password.
2785 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002786int cryptfs_get_password_type(void) {
Paul Crowley38132a12016-02-09 09:50:32 +00002787 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002788 SLOGE("cryptfs_get_password_type not valid for file encryption");
2789 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002790 }
2791
Paul Lawrencef4faa572014-01-29 13:31:03 -08002792 struct crypt_mnt_ftr crypt_ftr;
2793
2794 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2795 SLOGE("Error getting crypt footer and key\n");
2796 return -1;
2797 }
2798
Paul Lawrence6bfed202014-07-28 12:47:22 -07002799 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2800 return -1;
2801 }
2802
Paul Lawrencef4faa572014-01-29 13:31:03 -08002803 return crypt_ftr.crypt_type;
2804}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002805
Paul Crowley14c8c072018-09-18 13:30:21 -07002806const char* cryptfs_get_password() {
Paul Crowley38132a12016-02-09 09:50:32 +00002807 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002808 SLOGE("cryptfs_get_password not valid for file encryption");
2809 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002810 }
2811
Paul Lawrence399317e2014-03-10 13:20:50 -07002812 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002813 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002814 if (now.tv_sec < password_expiry_time) {
2815 return password;
2816 } else {
2817 cryptfs_clear_password();
2818 return 0;
2819 }
2820}
2821
Paul Crowley14c8c072018-09-18 13:30:21 -07002822void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002823 if (password) {
2824 size_t len = strlen(password);
2825 memset(password, 0, len);
2826 free(password);
2827 password = 0;
2828 password_expiry_time = 0;
2829 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002830}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002831
Paul Crowley14c8c072018-09-18 13:30:21 -07002832int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002833 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07002834 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07002835}