blob: 01ac694897e5da8fa4e9d7725d9432bafcdc7101 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
Logan Chiend557d762018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
Daniel Rosenberg65f99c92018-08-28 01:58:49 -070027#include "Checkpoint.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070029#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080030#include "Keymaster.h"
31#include "Process.h"
32#include "ScryptParameters.h"
Paul Crowleycfe39722018-10-30 15:59:24 -070033#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080034#include "VoldUtil.h"
35#include "VolumeManager.h"
36#include "secontext.h"
37
Eric Biggersed45ec32019-01-25 10:47:55 -080038#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080039#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080040#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080041#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080043#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070044#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080045#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070046#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070047#include <fscrypt/fscrypt.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080048#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080049#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080050#include <logwrap/logwrap.h>
51#include <openssl/evp.h>
52#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080053#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080054
55#include <ctype.h>
56#include <errno.h>
57#include <fcntl.h>
58#include <inttypes.h>
59#include <libgen.h>
60#include <linux/dm-ioctl.h>
61#include <linux/kdev_t.h>
62#include <math.h>
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include <sys/ioctl.h>
67#include <sys/mount.h>
68#include <sys/param.h>
69#include <sys/stat.h>
70#include <sys/types.h>
71#include <sys/wait.h>
72#include <time.h>
73#include <unistd.h>
74
Wei Wang4375f1b2017-02-24 17:43:01 -080075extern "C" {
76#include <crypto_scrypt.h>
77}
Mark Salyzyn3e971272014-01-21 13:27:04 -080078
Eric Biggersed45ec32019-01-25 10:47:55 -080079using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080080using android::base::StringPrintf;
Paul Crowleycfe39722018-10-30 15:59:24 -070081using namespace std::chrono_literals;
82
Mark Salyzyn5eecc442014-02-12 14:16:14 -080083#define UNUSED __attribute__((unused))
84
Ken Sumrall8f869aa2010-12-03 03:47:09 -080085#define DM_CRYPT_BUF_SIZE 4096
86
Jason parks70a4b3f2011-01-28 10:10:47 -060087#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080088
89constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
90constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070091constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080092
93// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070094static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060095
Paul Crowley14c8c072018-09-18 13:30:21 -070096#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070097
Paul Lawrence3bd36d52015-06-09 13:37:44 -070098#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080099
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800100#define CRYPTO_BLOCK_DEVICE "userdata"
101
102#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
103
Ken Sumrall29d8da82011-05-18 17:20:07 -0700104#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700105#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700106
Ken Sumralle919efe2012-09-29 17:07:41 -0700107#define TABLE_LOAD_RETRIES 10
108
Shawn Willden47ba10d2014-09-03 17:07:06 -0600109#define RSA_KEY_SIZE 2048
110#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
111#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600112#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700113
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700114#define RETRY_MOUNT_ATTEMPTS 10
115#define RETRY_MOUNT_DELAY_SECONDS 1
116
Paul Crowley5afbc622017-11-27 09:42:17 -0800117#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
118
Paul Crowley73473332017-11-21 15:43:51 -0800119static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
120
Greg Kaiser59ad0182018-02-16 13:01:36 -0800121static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700122static char* saved_mount_point;
123static int master_key_saved = 0;
124static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800125
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700126/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700127static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000128 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700129}
130
131/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700132static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800133 if (ftr->keymaster_blob_size) {
134 SLOGI("Already have key");
135 return 0;
136 }
137
Paul Crowley14c8c072018-09-18 13:30:21 -0700138 int rc = keymaster_create_key_for_cryptfs_scrypt(
139 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
140 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000141 if (rc) {
142 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800143 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000144 ftr->keymaster_blob_size = 0;
145 }
146 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700147 return -1;
148 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000149 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700150}
151
Shawn Willdene17a9c42014-09-08 13:04:08 -0600152/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700153static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
154 const size_t object_size, unsigned char** signature,
155 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600156 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600157 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600158 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600159
Shawn Willdene17a9c42014-09-08 13:04:08 -0600160 // To sign a message with RSA, the message must satisfy two
161 // constraints:
162 //
163 // 1. The message, when interpreted as a big-endian numeric value, must
164 // be strictly less than the public modulus of the RSA key. Note
165 // that because the most significant bit of the public modulus is
166 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
167 // key), an n-bit message with most significant bit 0 always
168 // satisfies this requirement.
169 //
170 // 2. The message must have the same length in bits as the public
171 // modulus of the RSA key. This requirement isn't mathematically
172 // necessary, but is necessary to ensure consistency in
173 // implementations.
174 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600175 case KDF_SCRYPT_KEYMASTER:
176 // This ensures the most significant byte of the signed message
177 // is zero. We could have zero-padded to the left instead, but
178 // this approach is slightly more robust against changes in
179 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600180 // so) because we really should be using a proper deterministic
181 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800182 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600183 SLOGI("Signing safely-padded object");
184 break;
185 default:
186 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000187 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600188 }
Paul Crowley73473332017-11-21 15:43:51 -0800189 for (;;) {
190 auto result = keymaster_sign_object_for_cryptfs_scrypt(
191 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
192 to_sign_size, signature, signature_size);
193 switch (result) {
194 case KeymasterSignResult::ok:
195 return 0;
196 case KeymasterSignResult::upgrade:
197 break;
198 default:
199 return -1;
200 }
201 SLOGD("Upgrading key");
202 if (keymaster_upgrade_key_for_cryptfs_scrypt(
203 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
204 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
205 &ftr->keymaster_blob_size) != 0) {
206 SLOGE("Failed to upgrade key");
207 return -1;
208 }
209 if (put_crypt_ftr_and_key(ftr) != 0) {
210 SLOGE("Failed to write upgraded key to disk");
211 }
212 SLOGD("Key upgraded successfully");
213 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600214}
215
Paul Lawrence399317e2014-03-10 13:20:50 -0700216/* Store password when userdata is successfully decrypted and mounted.
217 * Cleared by cryptfs_clear_password
218 *
219 * To avoid a double prompt at boot, we need to store the CryptKeeper
220 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
221 * Since the entire framework is torn down and rebuilt after encryption,
222 * we have to use a daemon or similar to store the password. Since vold
223 * is secured against IPC except from system processes, it seems a reasonable
224 * place to store this.
225 *
226 * password should be cleared once it has been used.
227 *
228 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800229 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700230static char* password = 0;
231static int password_expiry_time = 0;
232static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800233
Paul Crowley14c8c072018-09-18 13:30:21 -0700234enum class RebootType { reboot, recovery, shutdown };
235static void cryptfs_reboot(RebootType rt) {
236 switch (rt) {
237 case RebootType::reboot:
238 property_set(ANDROID_RB_PROPERTY, "reboot");
239 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800240
Paul Crowley14c8c072018-09-18 13:30:21 -0700241 case RebootType::recovery:
242 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
243 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800244
Paul Crowley14c8c072018-09-18 13:30:21 -0700245 case RebootType::shutdown:
246 property_set(ANDROID_RB_PROPERTY, "shutdown");
247 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700248 }
Paul Lawrence87999172014-02-20 12:21:31 -0800249
Ken Sumralladfba362013-06-04 16:37:52 -0700250 sleep(20);
251
252 /* Shouldn't get here, reboot should happen before sleep times out */
253 return;
254}
255
Paul Crowley14c8c072018-09-18 13:30:21 -0700256static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800257 memset(io, 0, dataSize);
258 io->data_size = dataSize;
259 io->data_start = sizeof(struct dm_ioctl);
260 io->version[0] = 4;
261 io->version[1] = 0;
262 io->version[2] = 0;
263 io->flags = flags;
264 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100265 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800266 }
267}
268
Greg Kaiser38723f22018-02-16 13:35:35 -0800269namespace {
270
271struct CryptoType;
272
273// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700274const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800275
276struct CryptoType {
277 // We should only be constructing CryptoTypes as part of
278 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
279 // which isn't pure or fully protected as a concession to being able to
280 // do it all at compile time. Add new CryptoTypes in
281 // supported_crypto_types[] below.
282 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
283 constexpr CryptoType set_keysize(uint32_t size) const {
284 return CryptoType(this->property_name, this->crypto_name, size);
285 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700286 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800287 return CryptoType(property, this->crypto_name, this->keysize);
288 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700289 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800290 return CryptoType(this->property_name, crypto, this->keysize);
291 }
292
Paul Crowley14c8c072018-09-18 13:30:21 -0700293 constexpr const char* get_property_name() const { return property_name; }
294 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800295 constexpr uint32_t get_keysize() const { return keysize; }
296
Paul Crowley14c8c072018-09-18 13:30:21 -0700297 private:
298 const char* property_name;
299 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800300 uint32_t keysize;
301
Paul Crowley14c8c072018-09-18 13:30:21 -0700302 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800303 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700304 friend const CryptoType& get_crypto_type();
305 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800306};
307
308// We only want to parse this read-only property once. But we need to wait
309// until the system is initialized before we can read it. So we use a static
310// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700311const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800312 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
313 return crypto_type;
314}
315
316constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700317 .set_property_name("AES-128-CBC")
318 .set_crypto_name("aes-cbc-essiv:sha256")
319 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800320
321constexpr CryptoType supported_crypto_types[] = {
322 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800323 CryptoType()
324 .set_property_name("adiantum")
325 .set_crypto_name("xchacha12,aes-adiantum-plain64")
326 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800327 // Add new CryptoTypes here. Order is not important.
328};
329
Greg Kaiser38723f22018-02-16 13:35:35 -0800330// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
331// We confirm all supported_crypto_types have a small enough keysize and
332// had both set_property_name() and set_crypto_name() called.
333
334template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700335constexpr size_t array_length(T (&)[N]) {
336 return N;
337}
Greg Kaiser38723f22018-02-16 13:35:35 -0800338
339constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
340 return (index >= array_length(supported_crypto_types));
341}
342
Paul Crowley14c8c072018-09-18 13:30:21 -0700343constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800344 return ((crypto_type.get_property_name() != nullptr) &&
345 (crypto_type.get_crypto_name() != nullptr) &&
346 (crypto_type.get_keysize() <= MAX_KEY_LEN));
347}
348
349// Note in C++11 that constexpr functions can only have a single line.
350// So our code is a bit convoluted (using recursion instead of a loop),
351// but it's asserting at compile time that all of our key lengths are valid.
352constexpr bool validateSupportedCryptoTypes(size_t index) {
353 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700354 (isValidCryptoType(supported_crypto_types[index]) &&
355 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800356}
357
358static_assert(validateSupportedCryptoTypes(0),
359 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
360 "incompletely constructed.");
361// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
362
Greg Kaiser38723f22018-02-16 13:35:35 -0800363// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700364const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800365 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
366 char paramstr[PROPERTY_VALUE_MAX];
367
Paul Crowley14c8c072018-09-18 13:30:21 -0700368 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
369 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800370 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
371 return ctype;
372 }
373 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700374 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
375 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800376 return default_crypto_type;
377}
378
379} // namespace
380
Kenny Rootc4c70f12013-06-14 12:11:38 -0700381/**
382 * Gets the default device scrypt parameters for key derivation time tuning.
383 * The parameters should lead to about one second derivation time for the
384 * given device.
385 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700386static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700387 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000388 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700389
Paul Crowley63c18d32016-02-10 14:02:47 +0000390 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
391 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
392 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
393 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700394 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000395 ftr->N_factor = Nf;
396 ftr->r_factor = rf;
397 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700398}
399
Greg Kaiser57f9af62018-02-16 13:13:58 -0800400uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800401 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800402}
403
Paul Crowley14c8c072018-09-18 13:30:21 -0700404const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800405 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800406}
407
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200408static uint64_t get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800409 int fd, block_size;
410 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200411 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800412
Paul Crowley14c8c072018-09-18 13:30:21 -0700413 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800414 SLOGE("Cannot open device to get filesystem size ");
415 return 0;
416 }
417
418 if (lseek64(fd, 1024, SEEK_SET) < 0) {
419 SLOGE("Cannot seek to superblock");
420 return 0;
421 }
422
423 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
424 SLOGE("Cannot read superblock");
425 return 0;
426 }
427
428 close(fd);
429
Daniel Rosenberge82df162014-08-15 22:19:23 +0000430 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
431 SLOGE("Not a valid ext4 superblock");
432 return 0;
433 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800434 block_size = 1024 << sb.s_log_block_size;
435 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200436 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800437
438 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200439 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800440}
441
Paul Crowley14c8c072018-09-18 13:30:21 -0700442static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
443 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200444 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700445 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700446 char key_loc[PROPERTY_VALUE_MAX];
447 char real_blkdev[PROPERTY_VALUE_MAX];
448 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700449
Paul Crowley14c8c072018-09-18 13:30:21 -0700450 if (!cached_data) {
451 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700452
Paul Crowley14c8c072018-09-18 13:30:21 -0700453 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200454 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700455 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
456 * encryption info footer and key, and plenty of bytes to spare for future
457 * growth.
458 */
459 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200460 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700461 cached_data = 1;
462 } else {
463 SLOGE("Cannot get size of block device %s\n", real_blkdev);
464 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700465 } else {
466 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
467 cached_off = 0;
468 cached_data = 1;
469 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700470 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700471
Paul Crowley14c8c072018-09-18 13:30:21 -0700472 if (cached_data) {
473 if (metadata_fname) {
474 *metadata_fname = cached_metadata_fname;
475 }
476 if (off) {
477 *off = cached_off;
478 }
479 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700480 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700481
Paul Crowley14c8c072018-09-18 13:30:21 -0700482 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700483}
484
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800485/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700486static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800487 SHA256_CTX c;
488 SHA256_Init(&c);
489 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
490 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
491 SHA256_Final(crypt_ftr->sha256, &c);
492}
493
Ken Sumralle8744072011-01-18 22:01:55 -0800494/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800495 * update the failed mount count but not change the key.
496 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700497static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
498 int fd;
499 unsigned int cnt;
500 /* starting_off is set to the SEEK_SET offset
501 * where the crypto structure starts
502 */
503 off64_t starting_off;
504 int rc = -1;
505 char* fname = NULL;
506 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800507
Paul Crowley14c8c072018-09-18 13:30:21 -0700508 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800509
Paul Crowley14c8c072018-09-18 13:30:21 -0700510 if (get_crypt_ftr_info(&fname, &starting_off)) {
511 SLOGE("Unable to get crypt_ftr_info\n");
512 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800513 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700514 if (fname[0] != '/') {
515 SLOGE("Unexpected value for crypto key location\n");
516 return -1;
517 }
518 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
519 SLOGE("Cannot open footer file %s for put\n", fname);
520 return -1;
521 }
Ken Sumralle8744072011-01-18 22:01:55 -0800522
Paul Crowley14c8c072018-09-18 13:30:21 -0700523 /* Seek to the start of the crypt footer */
524 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
525 SLOGE("Cannot seek to real block device footer\n");
526 goto errout;
527 }
528
529 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
530 SLOGE("Cannot write real block device footer\n");
531 goto errout;
532 }
533
534 fstat(fd, &statbuf);
535 /* If the keys are kept on a raw block device, do not try to truncate it. */
536 if (S_ISREG(statbuf.st_mode)) {
537 if (ftruncate(fd, 0x4000)) {
538 SLOGE("Cannot set footer file size\n");
539 goto errout;
540 }
541 }
542
543 /* Success! */
544 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800545
546errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700547 close(fd);
548 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800549}
550
Paul Crowley14c8c072018-09-18 13:30:21 -0700551static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800552 struct crypt_mnt_ftr copy;
553 memcpy(&copy, crypt_ftr, sizeof(copy));
554 set_ftr_sha(&copy);
555 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
556}
557
Paul Crowley14c8c072018-09-18 13:30:21 -0700558static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700559 return TEMP_FAILURE_RETRY(read(fd, buff, len));
560}
561
Paul Crowley14c8c072018-09-18 13:30:21 -0700562static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700563 return TEMP_FAILURE_RETRY(write(fd, buff, len));
564}
565
Paul Crowley14c8c072018-09-18 13:30:21 -0700566static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700567 memset(pdata, 0, len);
568 pdata->persist_magic = PERSIST_DATA_MAGIC;
569 pdata->persist_valid_entries = 0;
570}
571
572/* A routine to update the passed in crypt_ftr to the lastest version.
573 * fd is open read/write on the device that holds the crypto footer and persistent
574 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
575 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
576 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700577static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700578 int orig_major = crypt_ftr->major_version;
579 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700580
Kenny Root7434b312013-06-14 11:29:53 -0700581 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700582 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700583 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700584
Kenny Rootc4c70f12013-06-14 12:11:38 -0700585 SLOGW("upgrading crypto footer to 1.1");
586
Paul Crowley14c8c072018-09-18 13:30:21 -0700587 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700588 if (pdata == NULL) {
589 SLOGE("Cannot allocate persisent data\n");
590 return;
591 }
592 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
593
594 /* Need to initialize the persistent data area */
595 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
596 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100597 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700598 return;
599 }
600 /* Write all zeros to the first copy, making it invalid */
601 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
602
603 /* Write a valid but empty structure to the second copy */
604 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
605 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
606
607 /* Update the footer */
608 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
609 crypt_ftr->persist_data_offset[0] = pdata_offset;
610 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
611 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100612 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700613 }
614
Paul Lawrencef4faa572014-01-29 13:31:03 -0800615 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700616 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800617 /* But keep the old kdf_type.
618 * It will get updated later to KDF_SCRYPT after the password has been verified.
619 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700620 crypt_ftr->kdf_type = KDF_PBKDF2;
621 get_device_scrypt_params(crypt_ftr);
622 crypt_ftr->minor_version = 2;
623 }
624
Paul Lawrencef4faa572014-01-29 13:31:03 -0800625 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
626 SLOGW("upgrading crypto footer to 1.3");
627 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
628 crypt_ftr->minor_version = 3;
629 }
630
Kenny Root7434b312013-06-14 11:29:53 -0700631 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
632 if (lseek64(fd, offset, SEEK_SET) == -1) {
633 SLOGE("Cannot seek to crypt footer\n");
634 return;
635 }
636 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700637 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700638}
639
Paul Crowley14c8c072018-09-18 13:30:21 -0700640static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
641 int fd;
642 unsigned int cnt;
643 off64_t starting_off;
644 int rc = -1;
645 char* fname = NULL;
646 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700647
Paul Crowley14c8c072018-09-18 13:30:21 -0700648 if (get_crypt_ftr_info(&fname, &starting_off)) {
649 SLOGE("Unable to get crypt_ftr_info\n");
650 return -1;
651 }
652 if (fname[0] != '/') {
653 SLOGE("Unexpected value for crypto key location\n");
654 return -1;
655 }
656 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
657 SLOGE("Cannot open footer file %s for get\n", fname);
658 return -1;
659 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800660
Paul Crowley14c8c072018-09-18 13:30:21 -0700661 /* Make sure it's 16 Kbytes in length */
662 fstat(fd, &statbuf);
663 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
664 SLOGE("footer file %s is not the expected size!\n", fname);
665 goto errout;
666 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700667
Paul Crowley14c8c072018-09-18 13:30:21 -0700668 /* Seek to the start of the crypt footer */
669 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
670 SLOGE("Cannot seek to real block device footer\n");
671 goto errout;
672 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700673
Paul Crowley14c8c072018-09-18 13:30:21 -0700674 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
675 SLOGE("Cannot read real block device footer\n");
676 goto errout;
677 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800678
Paul Crowley14c8c072018-09-18 13:30:21 -0700679 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
680 SLOGE("Bad magic for real block device %s\n", fname);
681 goto errout;
682 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800683
Paul Crowley14c8c072018-09-18 13:30:21 -0700684 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
685 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
686 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
687 goto errout;
688 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800689
Paul Crowley14c8c072018-09-18 13:30:21 -0700690 // We risk buffer overflows with oversized keys, so we just reject them.
691 // 0-sized keys are problematic (essentially by-passing encryption), and
692 // AES-CBC key wrapping only works for multiples of 16 bytes.
693 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
694 (crypt_ftr->keysize > MAX_KEY_LEN)) {
695 SLOGE(
696 "Invalid keysize (%u) for block device %s; Must be non-zero, "
697 "divisible by 16, and <= %d\n",
698 crypt_ftr->keysize, fname, MAX_KEY_LEN);
699 goto errout;
700 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800701
Paul Crowley14c8c072018-09-18 13:30:21 -0700702 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
703 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
704 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
705 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800706
Paul Crowley14c8c072018-09-18 13:30:21 -0700707 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
708 * copy on disk before returning.
709 */
710 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
711 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
712 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800713
Paul Crowley14c8c072018-09-18 13:30:21 -0700714 /* Success! */
715 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800716
717errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700718 close(fd);
719 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800720}
721
Paul Crowley14c8c072018-09-18 13:30:21 -0700722static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700723 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
724 crypt_ftr->persist_data_offset[1]) {
725 SLOGE("Crypt_ftr persist data regions overlap");
726 return -1;
727 }
728
729 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
730 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
731 return -1;
732 }
733
734 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700735 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700736 CRYPT_FOOTER_OFFSET) {
737 SLOGE("Persistent data extends past crypto footer");
738 return -1;
739 }
740
741 return 0;
742}
743
Paul Crowley14c8c072018-09-18 13:30:21 -0700744static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700745 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700746 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700747 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700748 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700749 int found = 0;
750 int fd;
751 int ret;
752 int i;
753
754 if (persist_data) {
755 /* Nothing to do, we've already loaded or initialized it */
756 return 0;
757 }
758
Ken Sumrall160b4d62013-04-22 12:15:39 -0700759 /* If not encrypted, just allocate an empty table and initialize it */
760 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700761 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800762 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700763 if (pdata) {
764 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
765 persist_data = pdata;
766 return 0;
767 }
768 return -1;
769 }
770
Paul Crowley14c8c072018-09-18 13:30:21 -0700771 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700772 return -1;
773 }
774
Paul Crowley14c8c072018-09-18 13:30:21 -0700775 if ((crypt_ftr.major_version < 1) ||
776 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700777 SLOGE("Crypt_ftr version doesn't support persistent data");
778 return -1;
779 }
780
781 if (get_crypt_ftr_info(&fname, NULL)) {
782 return -1;
783 }
784
785 ret = validate_persistent_data_storage(&crypt_ftr);
786 if (ret) {
787 return -1;
788 }
789
Paul Crowley14c8c072018-09-18 13:30:21 -0700790 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700791 if (fd < 0) {
792 SLOGE("Cannot open %s metadata file", fname);
793 return -1;
794 }
795
Wei Wang4375f1b2017-02-24 17:43:01 -0800796 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800797 if (pdata == NULL) {
798 SLOGE("Cannot allocate memory for persistent data");
799 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700800 }
801
802 for (i = 0; i < 2; i++) {
803 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
804 SLOGE("Cannot seek to read persistent data on %s", fname);
805 goto err2;
806 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700807 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700808 SLOGE("Error reading persistent data on iteration %d", i);
809 goto err2;
810 }
811 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
812 found = 1;
813 break;
814 }
815 }
816
817 if (!found) {
818 SLOGI("Could not find valid persistent data, creating");
819 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
820 }
821
822 /* Success */
823 persist_data = pdata;
824 close(fd);
825 return 0;
826
827err2:
828 free(pdata);
829
830err:
831 close(fd);
832 return -1;
833}
834
Paul Crowley14c8c072018-09-18 13:30:21 -0700835static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700836 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700837 struct crypt_persist_data* pdata;
838 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700839 off64_t write_offset;
840 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700841 int fd;
842 int ret;
843
844 if (persist_data == NULL) {
845 SLOGE("No persistent data to save");
846 return -1;
847 }
848
Paul Crowley14c8c072018-09-18 13:30:21 -0700849 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700850 return -1;
851 }
852
Paul Crowley14c8c072018-09-18 13:30:21 -0700853 if ((crypt_ftr.major_version < 1) ||
854 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700855 SLOGE("Crypt_ftr version doesn't support persistent data");
856 return -1;
857 }
858
859 ret = validate_persistent_data_storage(&crypt_ftr);
860 if (ret) {
861 return -1;
862 }
863
864 if (get_crypt_ftr_info(&fname, NULL)) {
865 return -1;
866 }
867
Paul Crowley14c8c072018-09-18 13:30:21 -0700868 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700869 if (fd < 0) {
870 SLOGE("Cannot open %s metadata file", fname);
871 return -1;
872 }
873
Wei Wang4375f1b2017-02-24 17:43:01 -0800874 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700875 if (pdata == NULL) {
876 SLOGE("Cannot allocate persistant data");
877 goto err;
878 }
879
880 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
881 SLOGE("Cannot seek to read persistent data on %s", fname);
882 goto err2;
883 }
884
885 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700886 SLOGE("Error reading persistent data before save");
887 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700888 }
889
890 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
891 /* The first copy is the curent valid copy, so write to
892 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700893 write_offset = crypt_ftr.persist_data_offset[1];
894 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700895 } else {
896 /* The second copy must be the valid copy, so write to
897 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700898 write_offset = crypt_ftr.persist_data_offset[0];
899 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700900 }
901
902 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100903 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700904 SLOGE("Cannot seek to write persistent data");
905 goto err2;
906 }
907 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700908 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100909 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700910 SLOGE("Cannot seek to erase previous persistent data");
911 goto err2;
912 }
913 fsync(fd);
914 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -0700915 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700916 SLOGE("Cannot write to erase previous persistent data");
917 goto err2;
918 }
919 fsync(fd);
920 } else {
921 SLOGE("Cannot write to save persistent data");
922 goto err2;
923 }
924
925 /* Success */
926 free(pdata);
927 close(fd);
928 return 0;
929
930err2:
931 free(pdata);
932err:
933 close(fd);
934 return -1;
935}
936
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800937/* Convert a binary key of specified length into an ascii hex string equivalent,
938 * without the leading 0x and with null termination
939 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700940static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
941 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700942 unsigned int i, a;
943 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800944
Paul Crowley14c8c072018-09-18 13:30:21 -0700945 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700946 /* For each byte, write out two ascii hex digits */
947 nibble = (master_key[i] >> 4) & 0xf;
948 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800949
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700950 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -0700951 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700952 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800953
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700954 /* Add the null termination */
955 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800956}
957
Paul Crowley14c8c072018-09-18 13:30:21 -0700958static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
959 const unsigned char* master_key, const char* real_blk_name,
960 const char* name, int fd, const char* extra_params) {
961 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
962 struct dm_ioctl* io;
963 struct dm_target_spec* tgt;
964 char* crypt_params;
965 // We need two ASCII characters to represent each byte, and need space for
966 // the '\0' terminator.
967 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
968 size_t buff_offset;
969 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800970
Paul Crowley14c8c072018-09-18 13:30:21 -0700971 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800972
Paul Crowley14c8c072018-09-18 13:30:21 -0700973 /* Load the mapping table for this device */
974 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800975
Paul Crowley14c8c072018-09-18 13:30:21 -0700976 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
977 io->target_count = 1;
978 tgt->status = 0;
979 tgt->sector_start = 0;
980 tgt->length = crypt_ftr->fs_size;
981 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800982
Paul Crowley14c8c072018-09-18 13:30:21 -0700983 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
984 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800985
Paul Crowley14c8c072018-09-18 13:30:21 -0700986 buff_offset = crypt_params - buffer;
987 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
988 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
989 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
990 crypt_params += strlen(crypt_params) + 1;
991 crypt_params =
992 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
993 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800994
Paul Crowley14c8c072018-09-18 13:30:21 -0700995 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
996 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
997 break;
998 }
999 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001000 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001001
Paul Crowley14c8c072018-09-18 13:30:21 -07001002 if (i == TABLE_LOAD_RETRIES) {
1003 /* We failed to load the table, return an error */
1004 return -1;
1005 } else {
1006 return i + 1;
1007 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001008}
1009
Paul Crowley14c8c072018-09-18 13:30:21 -07001010static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001011 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001012 struct dm_ioctl* io;
1013 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001014
Paul Crowley14c8c072018-09-18 13:30:21 -07001015 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001016
1017 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1018
1019 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1020 return -1;
1021 }
1022
1023 /* Iterate over the returned versions, looking for name of "crypt".
1024 * When found, get and return the version.
1025 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001026 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001027 while (v->next) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001028 if (!strcmp(v->name, "crypt")) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001029 /* We found the crypt driver, return the version, and get out */
1030 version[0] = v->version[0];
1031 version[1] = v->version[1];
1032 version[2] = v->version[2];
1033 return 0;
1034 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001035 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001036 }
1037
1038 return -1;
1039}
1040
Paul Crowley5afbc622017-11-27 09:42:17 -08001041static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1042 if (extra_params_vec.empty()) return "";
1043 std::string extra_params = std::to_string(extra_params_vec.size());
1044 for (const auto& p : extra_params_vec) {
1045 extra_params.append(" ");
1046 extra_params.append(p);
1047 }
1048 return extra_params;
1049}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001050
Eric Biggersed45ec32019-01-25 10:47:55 -08001051/*
1052 * If the ro.crypto.fde_sector_size system property is set, append the
1053 * parameters to make dm-crypt use the specified crypto sector size and round
1054 * the crypto device size down to a crypto sector boundary.
1055 */
1056static int add_sector_size_param(std::vector<std::string>* extra_params_vec,
1057 struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001058 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001059 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001060
Eric Biggersed45ec32019-01-25 10:47:55 -08001061 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1062 unsigned int sector_size;
1063
1064 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1065 (sector_size & (sector_size - 1)) != 0) {
1066 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1067 DM_CRYPT_SECTOR_SIZE, value);
1068 return -1;
1069 }
1070
1071 std::string param = StringPrintf("sector_size:%u", sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001072 extra_params_vec->push_back(std::move(param));
1073
1074 // With this option, IVs will match the sector numbering, instead
1075 // of being hard-coded to being based on 512-byte sectors.
1076 extra_params_vec->emplace_back("iv_large_sectors");
Eric Biggersed45ec32019-01-25 10:47:55 -08001077
1078 // Round the crypto device size down to a crypto sector boundary.
1079 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001080 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001081 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001082}
1083
Paul Crowley5afbc622017-11-27 09:42:17 -08001084static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1085 const char* real_blk_name, char* crypto_blk_name, const char* name,
1086 uint32_t flags) {
1087 char buffer[DM_CRYPT_BUF_SIZE];
1088 struct dm_ioctl* io;
1089 unsigned int minor;
1090 int fd = 0;
1091 int err;
1092 int retval = -1;
1093 int version[3];
1094 int load_count;
1095 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001096
Paul Crowley5afbc622017-11-27 09:42:17 -08001097 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1098 SLOGE("Cannot open device-mapper\n");
1099 goto errout;
1100 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001101
Paul Crowley5afbc622017-11-27 09:42:17 -08001102 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001103
Paul Crowley5afbc622017-11-27 09:42:17 -08001104 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1105 err = ioctl(fd, DM_DEV_CREATE, io);
1106 if (err) {
1107 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1108 goto errout;
1109 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001110
Paul Crowley5afbc622017-11-27 09:42:17 -08001111 /* Get the device status, in particular, the name of it's device file */
1112 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1113 if (ioctl(fd, DM_DEV_STATUS, io)) {
1114 SLOGE("Cannot retrieve dm-crypt device status\n");
1115 goto errout;
1116 }
1117 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1118 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001119
Paul Crowley5afbc622017-11-27 09:42:17 -08001120 if (!get_dm_crypt_version(fd, name, version)) {
1121 /* Support for allow_discards was added in version 1.11.0 */
1122 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1123 extra_params_vec.emplace_back("allow_discards");
1124 }
1125 }
1126 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1127 extra_params_vec.emplace_back("allow_encrypt_override");
1128 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001129 if (add_sector_size_param(&extra_params_vec, crypt_ftr)) {
1130 SLOGE("Error processing dm-crypt sector size param\n");
1131 goto errout;
1132 }
Paul Crowley5afbc622017-11-27 09:42:17 -08001133 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1134 extra_params_as_string(extra_params_vec).c_str());
1135 if (load_count < 0) {
1136 SLOGE("Cannot load dm-crypt mapping table.\n");
1137 goto errout;
1138 } else if (load_count > 1) {
1139 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1140 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001141
Paul Crowley5afbc622017-11-27 09:42:17 -08001142 /* Resume this device to activate it */
1143 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001144
Paul Crowley5afbc622017-11-27 09:42:17 -08001145 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1146 SLOGE("Cannot resume the dm-crypt device\n");
1147 goto errout;
1148 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149
Paul Crowleycfe39722018-10-30 15:59:24 -07001150 /* Ensure the dm device has been created before returning. */
1151 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1152 // WaitForFile generates a suitable log message
1153 goto errout;
1154 }
1155
Paul Crowley5afbc622017-11-27 09:42:17 -08001156 /* We made it here with no errors. Woot! */
1157 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001158
1159errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001160 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 -08001161
Paul Crowley14c8c072018-09-18 13:30:21 -07001162 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001163}
1164
Paul Crowley14c8c072018-09-18 13:30:21 -07001165static int delete_crypto_blk_dev(const char* name) {
1166 int fd;
1167 char buffer[DM_CRYPT_BUF_SIZE];
1168 struct dm_ioctl* io;
1169 int retval = -1;
Yue Hu9d6cc182018-12-17 17:09:55 +08001170 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001171
Paul Crowley14c8c072018-09-18 13:30:21 -07001172 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1173 SLOGE("Cannot open device-mapper\n");
1174 goto errout;
1175 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001176
Paul Crowley14c8c072018-09-18 13:30:21 -07001177 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001178
Paul Crowley14c8c072018-09-18 13:30:21 -07001179 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Yue Hu9d6cc182018-12-17 17:09:55 +08001180 err = ioctl(fd, DM_DEV_REMOVE, io);
1181 if (err) {
1182 SLOGE("Cannot remove dm-crypt device %s: %s\n", name, strerror(errno));
Paul Crowley14c8c072018-09-18 13:30:21 -07001183 goto errout;
1184 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001185
Paul Crowley14c8c072018-09-18 13:30:21 -07001186 /* We made it here with no errors. Woot! */
1187 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001188
1189errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001190 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 -08001191
Paul Crowley14c8c072018-09-18 13:30:21 -07001192 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001193}
1194
Paul Crowley14c8c072018-09-18 13:30:21 -07001195static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1196 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001197 SLOGI("Using pbkdf2 for cryptfs KDF");
1198
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001199 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001200 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1201 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001202}
1203
Paul Crowley14c8c072018-09-18 13:30:21 -07001204static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001205 SLOGI("Using scrypt for cryptfs KDF");
1206
Paul Crowley14c8c072018-09-18 13:30:21 -07001207 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001208
1209 int N = 1 << ftr->N_factor;
1210 int r = 1 << ftr->r_factor;
1211 int p = 1 << ftr->p_factor;
1212
1213 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001214 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001215 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001216
Paul Crowley14c8c072018-09-18 13:30:21 -07001217 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001218}
1219
Paul Crowley14c8c072018-09-18 13:30:21 -07001220static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1221 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001222 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1223
1224 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001225 size_t signature_size;
1226 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001227 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001228
1229 int N = 1 << ftr->N_factor;
1230 int r = 1 << ftr->r_factor;
1231 int p = 1 << ftr->p_factor;
1232
Paul Crowley14c8c072018-09-18 13:30:21 -07001233 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001234 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001235
1236 if (rc) {
1237 SLOGE("scrypt failed");
1238 return -1;
1239 }
1240
Paul Crowley14c8c072018-09-18 13:30:21 -07001241 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001242 SLOGE("Signing failed");
1243 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001244 }
1245
Paul Crowley14c8c072018-09-18 13:30:21 -07001246 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1247 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001248 free(signature);
1249
1250 if (rc) {
1251 SLOGE("scrypt failed");
1252 return -1;
1253 }
1254
1255 return 0;
1256}
1257
Paul Crowley14c8c072018-09-18 13:30:21 -07001258static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1259 const unsigned char* decrypted_master_key,
1260 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1261 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001262 EVP_CIPHER_CTX e_ctx;
1263 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001264 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001265
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001266 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001267 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001268
1269 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001270 case KDF_SCRYPT_KEYMASTER:
1271 if (keymaster_create_key(crypt_ftr)) {
1272 SLOGE("keymaster_create_key failed");
1273 return -1;
1274 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001275
Paul Crowley14c8c072018-09-18 13:30:21 -07001276 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1277 SLOGE("scrypt failed");
1278 return -1;
1279 }
1280 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001281
Paul Crowley14c8c072018-09-18 13:30:21 -07001282 case KDF_SCRYPT:
1283 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1284 SLOGE("scrypt failed");
1285 return -1;
1286 }
1287 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001288
Paul Crowley14c8c072018-09-18 13:30:21 -07001289 default:
1290 SLOGE("Invalid kdf_type");
1291 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001292 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001293
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001295 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001296 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1297 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001298 SLOGE("EVP_EncryptInit failed\n");
1299 return -1;
1300 }
1301 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001302
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001303 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001304 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1305 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001306 SLOGE("EVP_EncryptUpdate failed\n");
1307 return -1;
1308 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001309 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001310 SLOGE("EVP_EncryptFinal failed\n");
1311 return -1;
1312 }
1313
Greg Kaiser59ad0182018-02-16 13:01:36 -08001314 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001315 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1316 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001317 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001318
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001319 /* Store the scrypt of the intermediate key, so we can validate if it's a
1320 password error or mount error when things go wrong.
1321 Note there's no need to check for errors, since if this is incorrect, we
1322 simply won't wipe userdata, which is the correct default behavior
1323 */
1324 int N = 1 << crypt_ftr->N_factor;
1325 int r = 1 << crypt_ftr->r_factor;
1326 int p = 1 << crypt_ftr->p_factor;
1327
Paul Crowley14c8c072018-09-18 13:30:21 -07001328 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1329 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001330 sizeof(crypt_ftr->scrypted_intermediate_key));
1331
1332 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001333 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001334 }
1335
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001336 EVP_CIPHER_CTX_cleanup(&e_ctx);
1337
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001338 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001339}
1340
Paul Crowley14c8c072018-09-18 13:30:21 -07001341static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1342 const unsigned char* encrypted_master_key, size_t keysize,
1343 unsigned char* decrypted_master_key, kdf_func kdf,
1344 void* kdf_params, unsigned char** intermediate_key,
1345 size_t* intermediate_key_size) {
1346 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1347 EVP_CIPHER_CTX d_ctx;
1348 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349
Paul Crowley14c8c072018-09-18 13:30:21 -07001350 /* Turn the password into an intermediate key and IV that can decrypt the
1351 master key */
1352 if (kdf(passwd, salt, ikey, kdf_params)) {
1353 SLOGE("kdf failed");
1354 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001355 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001356
Paul Crowley14c8c072018-09-18 13:30:21 -07001357 /* Initialize the decryption engine */
1358 EVP_CIPHER_CTX_init(&d_ctx);
1359 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1360 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1361 return -1;
1362 }
1363 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1364 /* Decrypt the master key */
1365 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1366 keysize)) {
1367 return -1;
1368 }
1369 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1370 return -1;
1371 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001372
Paul Crowley14c8c072018-09-18 13:30:21 -07001373 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1374 return -1;
1375 }
1376
1377 /* Copy intermediate key if needed by params */
1378 if (intermediate_key && intermediate_key_size) {
1379 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1380 if (*intermediate_key) {
1381 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1382 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1383 }
1384 }
1385
1386 EVP_CIPHER_CTX_cleanup(&d_ctx);
1387
1388 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001389}
1390
Paul Crowley14c8c072018-09-18 13:30:21 -07001391static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001392 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001393 *kdf = scrypt_keymaster;
1394 *kdf_params = ftr;
1395 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001396 *kdf = scrypt;
1397 *kdf_params = ftr;
1398 } else {
1399 *kdf = pbkdf2;
1400 *kdf_params = NULL;
1401 }
1402}
1403
Paul Crowley14c8c072018-09-18 13:30:21 -07001404static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1405 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1406 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001407 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001408 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001409 int ret;
1410
1411 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001412 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1413 decrypted_master_key, kdf, kdf_params, intermediate_key,
1414 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001415 if (ret != 0) {
1416 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001417 }
1418
1419 return ret;
1420}
1421
Paul Crowley14c8c072018-09-18 13:30:21 -07001422static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1423 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001424 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001425
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001426 /* Get some random bits for a key and salt */
1427 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1428 return -1;
1429 }
1430 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1431 return -1;
1432 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001433
1434 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001435 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001436}
1437
Paul Crowley14c8c072018-09-18 13:30:21 -07001438int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001439 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001440#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001441
1442 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001443 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001444 if (umount(mountpoint) == 0) {
1445 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001446 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001447
1448 if (errno == EINVAL) {
1449 /* EINVAL is returned if the directory is not a mountpoint,
1450 * i.e. there is no filesystem mounted there. So just get out.
1451 */
1452 break;
1453 }
1454
1455 err = errno;
1456
1457 /* If allowed, be increasingly aggressive before the last two retries */
1458 if (kill) {
1459 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1460 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001461 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001462 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1463 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001464 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001465 }
1466 }
1467
1468 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001469 }
1470
1471 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001472 SLOGD("unmounting %s succeeded\n", mountpoint);
1473 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001474 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001475 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1476 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1477 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001478 }
1479
1480 return rc;
1481}
1482
Paul Crowley14c8c072018-09-18 13:30:21 -07001483static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001484 // NOTE: post_fs_data results in init calling back around to vold, so all
1485 // callers to this method must be async
1486
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001487 /* Do the prep of the /data filesystem */
1488 property_set("vold.post_fs_data_done", "0");
1489 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001490 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001491
Ken Sumrallc5872692013-05-14 15:26:31 -07001492 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001493 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001494 /* We timed out to prep /data in time. Continue wait. */
1495 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001496 }
Wei Wang42e38102017-06-07 10:46:12 -07001497 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001498}
1499
Paul Crowley14c8c072018-09-18 13:30:21 -07001500static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001501 // Mark the footer as bad
1502 struct crypt_mnt_ftr crypt_ftr;
1503 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1504 SLOGE("Failed to get crypto footer - panic");
1505 return;
1506 }
1507
1508 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1509 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1510 SLOGE("Failed to set crypto footer - panic");
1511 return;
1512 }
1513}
1514
Paul Crowley14c8c072018-09-18 13:30:21 -07001515static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001516 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001517 SLOGE("Failed to mount tmpfs on data - panic");
1518 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001519 }
1520
1521 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1522 SLOGE("Failed to trigger post fs data - panic");
1523 return;
1524 }
1525
1526 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1527 SLOGE("Failed to trigger restart min framework - panic");
1528 return;
1529 }
1530}
1531
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001532/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001533static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001534 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001535 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001536 static int restart_successful = 0;
1537
1538 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001539 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001540 SLOGE("Encrypted filesystem not validated, aborting");
1541 return -1;
1542 }
1543
1544 if (restart_successful) {
1545 SLOGE("System already restarted with encrypted disk, aborting");
1546 return -1;
1547 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001548
Paul Lawrencef4faa572014-01-29 13:31:03 -08001549 if (restart_main) {
1550 /* Here is where we shut down the framework. The init scripts
1551 * start all services in one of three classes: core, main or late_start.
1552 * On boot, we start core and main. Now, we stop main, but not core,
1553 * as core includes vold and a few other really important things that
1554 * we need to keep running. Once main has stopped, we should be able
1555 * to umount the tmpfs /data, then mount the encrypted /data.
1556 * We then restart the class main, and also the class late_start.
1557 * At the moment, I've only put a few things in late_start that I know
1558 * are not needed to bring up the framework, and that also cause problems
1559 * with unmounting the tmpfs /data, but I hope to add add more services
1560 * to the late_start class as we optimize this to decrease the delay
1561 * till the user is asked for the password to the filesystem.
1562 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001563
Paul Lawrencef4faa572014-01-29 13:31:03 -08001564 /* The init files are setup to stop the class main when vold.decrypt is
1565 * set to trigger_reset_main.
1566 */
1567 property_set("vold.decrypt", "trigger_reset_main");
1568 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569
Paul Lawrencef4faa572014-01-29 13:31:03 -08001570 /* Ugh, shutting down the framework is not synchronous, so until it
1571 * can be fixed, this horrible hack will wait a moment for it all to
1572 * shut down before proceeding. Without it, some devices cannot
1573 * restart the graphics services.
1574 */
1575 sleep(2);
1576 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001577
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001578 /* Now that the framework is shutdown, we should be able to umount()
1579 * the tmpfs filesystem, and mount the real one.
1580 */
1581
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001582 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1583 if (strlen(crypto_blkdev) == 0) {
1584 SLOGE("fs_crypto_blkdev not set\n");
1585 return -1;
1586 }
1587
Paul Crowley14c8c072018-09-18 13:30:21 -07001588 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001589 /* If ro.crypto.readonly is set to 1, mount the decrypted
1590 * filesystem readonly. This is used when /data is mounted by
1591 * recovery mode.
1592 */
1593 char ro_prop[PROPERTY_VALUE_MAX];
1594 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001595 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001596 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001597 if (rec) {
1598 rec->flags |= MS_RDONLY;
1599 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001600 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001601
Ken Sumralle5032c42012-04-01 23:58:44 -07001602 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001603 int retries = RETRY_MOUNT_ATTEMPTS;
1604 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001605
1606 /*
1607 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1608 * partitions in the fsck domain.
1609 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001610 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001611 SLOGE("Failed to setexeccon");
1612 return -1;
1613 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001614 bool needs_cp = android::vold::cp_needsCheckpoint();
1615 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1616 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001617 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1618 /* TODO: invoke something similar to
1619 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1620 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001621 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001622 if (--retries) {
1623 sleep(RETRY_MOUNT_DELAY_SECONDS);
1624 } else {
1625 /* Let's hope that a reboot clears away whatever is keeping
1626 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001627 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001628 }
1629 } else {
1630 SLOGE("Failed to mount decrypted data");
1631 cryptfs_set_corrupt();
1632 cryptfs_trigger_restart_min_framework();
1633 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001634 if (setexeccon(NULL)) {
1635 SLOGE("Failed to setexeccon");
1636 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001637 return -1;
1638 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001639 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001640 if (setexeccon(NULL)) {
1641 SLOGE("Failed to setexeccon");
1642 return -1;
1643 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001644
Ken Sumralle5032c42012-04-01 23:58:44 -07001645 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001646 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001647 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001648
1649 /* startup service classes main and late_start */
1650 property_set("vold.decrypt", "trigger_restart_framework");
1651 SLOGD("Just triggered restart_framework\n");
1652
1653 /* Give it a few moments to get started */
1654 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001655 }
1656
Ken Sumrall0cc16632011-01-18 20:32:26 -08001657 if (rc == 0) {
1658 restart_successful = 1;
1659 }
1660
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001661 return rc;
1662}
1663
Paul Crowley14c8c072018-09-18 13:30:21 -07001664int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001665 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001666 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001667 SLOGE("cryptfs_restart not valid for file encryption:");
1668 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001669 }
1670
Paul Lawrencef4faa572014-01-29 13:31:03 -08001671 /* Call internal implementation forcing a restart of main service group */
1672 return cryptfs_restart_internal(1);
1673}
1674
Paul Crowley14c8c072018-09-18 13:30:21 -07001675static int do_crypto_complete(const char* mount_point) {
1676 struct crypt_mnt_ftr crypt_ftr;
1677 char encrypted_state[PROPERTY_VALUE_MAX];
1678 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001679
Paul Crowley14c8c072018-09-18 13:30:21 -07001680 property_get("ro.crypto.state", encrypted_state, "");
1681 if (strcmp(encrypted_state, "encrypted")) {
1682 SLOGE("not running with encryption, aborting");
1683 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001684 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001685
Paul Crowley14c8c072018-09-18 13:30:21 -07001686 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001687 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001688 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1689 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001690
Paul Crowley14c8c072018-09-18 13:30:21 -07001691 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1692 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001693
Paul Crowley14c8c072018-09-18 13:30:21 -07001694 /*
1695 * Only report this error if key_loc is a file and it exists.
1696 * If the device was never encrypted, and /data is not mountable for
1697 * some reason, returning 1 should prevent the UI from presenting the
1698 * a "enter password" screen, or worse, a "press button to wipe the
1699 * device" screen.
1700 */
1701 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1702 SLOGE("master key file does not exist, aborting");
1703 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1704 } else {
1705 SLOGE("Error getting crypt footer and key\n");
1706 return CRYPTO_COMPLETE_BAD_METADATA;
1707 }
1708 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001709
Paul Crowley14c8c072018-09-18 13:30:21 -07001710 // Test for possible error flags
1711 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1712 SLOGE("Encryption process is partway completed\n");
1713 return CRYPTO_COMPLETE_PARTIAL;
1714 }
1715
1716 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1717 SLOGE("Encryption process was interrupted but cannot continue\n");
1718 return CRYPTO_COMPLETE_INCONSISTENT;
1719 }
1720
1721 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1722 SLOGE("Encryption is successful but data is corrupt\n");
1723 return CRYPTO_COMPLETE_CORRUPT;
1724 }
1725
1726 /* We passed the test! We shall diminish, and return to the west */
1727 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001728}
1729
Paul Crowley14c8c072018-09-18 13:30:21 -07001730static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1731 const char* mount_point, const char* label) {
1732 unsigned char decrypted_master_key[MAX_KEY_LEN];
1733 char crypto_blkdev[MAXPATHLEN];
1734 char real_blkdev[MAXPATHLEN];
1735 char tmp_mount_point[64];
1736 unsigned int orig_failed_decrypt_count;
1737 int rc;
1738 int use_keymaster = 0;
1739 int upgrade = 0;
1740 unsigned char* intermediate_key = 0;
1741 size_t intermediate_key_size = 0;
1742 int N = 1 << crypt_ftr->N_factor;
1743 int r = 1 << crypt_ftr->r_factor;
1744 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001745
Paul Crowley14c8c072018-09-18 13:30:21 -07001746 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1747 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001748
Paul Crowley14c8c072018-09-18 13:30:21 -07001749 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1750 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1751 &intermediate_key_size)) {
1752 SLOGE("Failed to decrypt master key\n");
1753 rc = -1;
1754 goto errout;
1755 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001756 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001757
Paul Crowley14c8c072018-09-18 13:30:21 -07001758 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001759
Paul Crowley14c8c072018-09-18 13:30:21 -07001760 // Create crypto block device - all (non fatal) code paths
1761 // need it
1762 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
1763 0)) {
1764 SLOGE("Error creating decrypted block device\n");
1765 rc = -1;
1766 goto errout;
1767 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001768
Paul Crowley14c8c072018-09-18 13:30:21 -07001769 /* Work out if the problem is the password or the data */
1770 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001771
Paul Crowley14c8c072018-09-18 13:30:21 -07001772 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1773 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1774 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001775
Paul Crowley14c8c072018-09-18 13:30:21 -07001776 // Does the key match the crypto footer?
1777 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1778 sizeof(scrypted_intermediate_key)) == 0) {
1779 SLOGI("Password matches");
1780 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001781 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001782 /* Try mounting the file system anyway, just in case the problem's with
1783 * the footer, not the key. */
1784 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1785 mkdir(tmp_mount_point, 0755);
1786 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1787 SLOGE("Error temp mounting decrypted block device\n");
1788 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001789
Paul Crowley14c8c072018-09-18 13:30:21 -07001790 rc = ++crypt_ftr->failed_decrypt_count;
1791 put_crypt_ftr_and_key(crypt_ftr);
1792 } else {
1793 /* Success! */
1794 SLOGI("Password did not match but decrypted drive mounted - continue");
1795 umount(tmp_mount_point);
1796 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001797 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001798 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001799
Paul Crowley14c8c072018-09-18 13:30:21 -07001800 if (rc == 0) {
1801 crypt_ftr->failed_decrypt_count = 0;
1802 if (orig_failed_decrypt_count != 0) {
1803 put_crypt_ftr_and_key(crypt_ftr);
1804 }
1805
1806 /* Save the name of the crypto block device
1807 * so we can mount it when restarting the framework. */
1808 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1809
1810 /* Also save a the master key so we can reencrypted the key
1811 * the key when we want to change the password on it. */
1812 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1813 saved_mount_point = strdup(mount_point);
1814 master_key_saved = 1;
1815 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1816 rc = 0;
1817
1818 // Upgrade if we're not using the latest KDF.
1819 use_keymaster = keymaster_check_compatibility();
1820 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1821 // Don't allow downgrade
1822 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1823 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1824 upgrade = 1;
1825 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1826 crypt_ftr->kdf_type = KDF_SCRYPT;
1827 upgrade = 1;
1828 }
1829
1830 if (upgrade) {
1831 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1832 crypt_ftr->master_key, crypt_ftr);
1833 if (!rc) {
1834 rc = put_crypt_ftr_and_key(crypt_ftr);
1835 }
1836 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1837
1838 // Do not fail even if upgrade failed - machine is bootable
1839 // Note that if this code is ever hit, there is a *serious* problem
1840 // since KDFs should never fail. You *must* fix the kdf before
1841 // proceeding!
1842 if (rc) {
1843 SLOGW(
1844 "Upgrade failed with error %d,"
1845 " but continuing with previous state",
1846 rc);
1847 rc = 0;
1848 }
1849 }
1850 }
1851
1852errout:
1853 if (intermediate_key) {
1854 memset(intermediate_key, 0, intermediate_key_size);
1855 free(intermediate_key);
1856 }
1857 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001858}
1859
Ken Sumrall29d8da82011-05-18 17:20:07 -07001860/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001861 * Called by vold when it's asked to mount an encrypted external
1862 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001863 * as any metadata is been stored in a separate, small partition. We
1864 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001865 *
1866 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001867 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001868int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1869 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001870 uint64_t nr_sec = 0;
1871 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001872 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001873 return -1;
1874 }
1875
Jeff Sharkey9c484982015-03-31 10:35:33 -07001876 struct crypt_mnt_ftr ext_crypt_ftr;
1877 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1878 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001879 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001880 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001881 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001882 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001883 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001884 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1885 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001886
Paul Crowley385cb8c2018-03-29 13:27:23 -07001887 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001888}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001889
Jeff Sharkey9c484982015-03-31 10:35:33 -07001890/*
1891 * Called by vold when it's asked to unmount an encrypted external
1892 * storage volume.
1893 */
1894int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001895 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001896}
1897
Paul Crowley14c8c072018-09-18 13:30:21 -07001898int cryptfs_crypto_complete(void) {
1899 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001900}
1901
Paul Crowley14c8c072018-09-18 13:30:21 -07001902int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001903 char encrypted_state[PROPERTY_VALUE_MAX];
1904 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001905 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1906 SLOGE(
1907 "encrypted fs already validated or not running with encryption,"
1908 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001909 return -1;
1910 }
1911
1912 if (get_crypt_ftr_and_key(crypt_ftr)) {
1913 SLOGE("Error getting crypt footer and key");
1914 return -1;
1915 }
1916
1917 return 0;
1918}
1919
Paul Crowley14c8c072018-09-18 13:30:21 -07001920int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001921 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001922 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001923 SLOGE("cryptfs_check_passwd not valid for file encryption");
1924 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001925 }
1926
Paul Lawrencef4faa572014-01-29 13:31:03 -08001927 struct crypt_mnt_ftr crypt_ftr;
1928 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001929
Paul Lawrencef4faa572014-01-29 13:31:03 -08001930 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001931 if (rc) {
1932 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001933 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001934 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001935
Paul Crowley14c8c072018-09-18 13:30:21 -07001936 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001937 if (rc) {
1938 SLOGE("Password did not match");
1939 return rc;
1940 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001941
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001942 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1943 // Here we have a default actual password but a real password
1944 // we must test against the scrypted value
1945 // First, we must delete the crypto block device that
1946 // test_mount_encrypted_fs leaves behind as a side effect
1947 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001948 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1949 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001950 if (rc) {
1951 SLOGE("Default password did not match on reboot encryption");
1952 return rc;
1953 }
1954
1955 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1956 put_crypt_ftr_and_key(&crypt_ftr);
1957 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1958 if (rc) {
1959 SLOGE("Could not change password on reboot encryption");
1960 return rc;
1961 }
1962 }
1963
1964 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001965 cryptfs_clear_password();
1966 password = strdup(passwd);
1967 struct timespec now;
1968 clock_gettime(CLOCK_BOOTTIME, &now);
1969 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001970 }
1971
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001972 return rc;
1973}
1974
Paul Crowley14c8c072018-09-18 13:30:21 -07001975int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001976 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001977 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001978 char encrypted_state[PROPERTY_VALUE_MAX];
1979 int rc;
1980
1981 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001982 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001983 SLOGE("device not encrypted, aborting");
1984 return -2;
1985 }
1986
1987 if (!master_key_saved) {
1988 SLOGE("encrypted fs not yet mounted, aborting");
1989 return -1;
1990 }
1991
1992 if (!saved_mount_point) {
1993 SLOGE("encrypted fs failed to save mount point, aborting");
1994 return -1;
1995 }
1996
Ken Sumrall160b4d62013-04-22 12:15:39 -07001997 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001998 SLOGE("Error getting crypt footer and key\n");
1999 return -1;
2000 }
2001
2002 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2003 /* If the device has no password, then just say the password is valid */
2004 rc = 0;
2005 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002006 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002007 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2008 /* They match, the password is correct */
2009 rc = 0;
2010 } else {
2011 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2012 sleep(1);
2013 rc = 1;
2014 }
2015 }
2016
2017 return rc;
2018}
2019
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002020/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002021 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002022 * Presumably, at a minimum, the caller will update the
2023 * filesystem size and crypto_type_name after calling this function.
2024 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002025static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002026 off64_t off;
2027
2028 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002029 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002030 ftr->major_version = CURRENT_MAJOR_VERSION;
2031 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002032 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002033 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002034
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002035 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002036 case 1:
2037 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2038 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002039
Paul Crowley14c8c072018-09-18 13:30:21 -07002040 case 0:
2041 ftr->kdf_type = KDF_SCRYPT;
2042 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002043
Paul Crowley14c8c072018-09-18 13:30:21 -07002044 default:
2045 SLOGE("keymaster_check_compatibility failed");
2046 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002047 }
2048
Kenny Rootc4c70f12013-06-14 12:11:38 -07002049 get_device_scrypt_params(ftr);
2050
Ken Sumrall160b4d62013-04-22 12:15:39 -07002051 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2052 if (get_crypt_ftr_info(NULL, &off) == 0) {
2053 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002054 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002055 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002056
2057 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002058}
2059
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002060#define FRAMEWORK_BOOT_WAIT 60
2061
Paul Crowley14c8c072018-09-18 13:30:21 -07002062static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2063 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002064 if (fd == -1) {
2065 SLOGE("Error opening file %s", filename);
2066 return -1;
2067 }
2068
2069 char block[CRYPT_INPLACE_BUFSIZE];
2070 memset(block, 0, sizeof(block));
2071 if (unix_read(fd, block, sizeof(block)) < 0) {
2072 SLOGE("Error reading file %s", filename);
2073 close(fd);
2074 return -1;
2075 }
2076
2077 close(fd);
2078
2079 SHA256_CTX c;
2080 SHA256_Init(&c);
2081 SHA256_Update(&c, block, sizeof(block));
2082 SHA256_Final(buf, &c);
2083
2084 return 0;
2085}
2086
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002087static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2088 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002089 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002090 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002091
Paul Lawrence87999172014-02-20 12:21:31 -08002092 /* The size of the userdata partition, and add in the vold volumes below */
2093 tot_encryption_size = crypt_ftr->fs_size;
2094
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002095 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002096 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002097
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002098 if (rc == ENABLE_INPLACE_ERR_DEV) {
2099 /* Hack for b/17898962 */
2100 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2101 cryptfs_reboot(RebootType::reboot);
2102 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002103
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002104 if (!rc) {
2105 crypt_ftr->encrypted_upto = cur_encryption_done;
2106 }
Paul Lawrence87999172014-02-20 12:21:31 -08002107
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002108 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2109 /* The inplace routine never actually sets the progress to 100% due
2110 * to the round down nature of integer division, so set it here */
2111 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002112 }
2113
2114 return rc;
2115}
2116
Paul Crowleyb64933a2017-10-31 08:25:55 -07002117static int vold_unmountAll(void) {
2118 VolumeManager* vm = VolumeManager::Instance();
2119 return vm->unmountAll();
2120}
2121
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002122int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002123 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002124 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002125 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002126 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002127 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002128 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002129 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002130 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002131 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002132 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002133 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002134 bool onlyCreateHeader = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002135
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002136 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002137 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2138 /* An encryption was underway and was interrupted */
2139 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2140 crypt_ftr.encrypted_upto = 0;
2141 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002142
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002143 /* At this point, we are in an inconsistent state. Until we successfully
2144 complete encryption, a reboot will leave us broken. So mark the
2145 encryption failed in case that happens.
2146 On successfully completing encryption, remove this flag */
2147 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002148
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002149 put_crypt_ftr_and_key(&crypt_ftr);
2150 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2151 if (!check_ftr_sha(&crypt_ftr)) {
2152 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2153 put_crypt_ftr_and_key(&crypt_ftr);
2154 goto error_unencrypted;
2155 }
2156
2157 /* Doing a reboot-encryption*/
2158 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2159 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2160 rebootEncryption = true;
2161 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002162 } else {
2163 // We don't want to accidentally reference invalid data.
2164 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002165 }
2166
2167 property_get("ro.crypto.state", encrypted_state, "");
2168 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2169 SLOGE("Device is already running encrypted, aborting");
2170 goto error_unencrypted;
2171 }
2172
2173 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002174 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2175 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002176
Ken Sumrall3ed82362011-01-28 23:31:16 -08002177 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002178 uint64_t nr_sec;
2179 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002180 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2181 goto error_unencrypted;
2182 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002183
2184 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002185 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002186 uint64_t fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002187 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002188 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002189
Paul Lawrence87999172014-02-20 12:21:31 -08002190 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002191
2192 if (fs_size_sec > max_fs_size_sec) {
2193 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2194 goto error_unencrypted;
2195 }
2196 }
2197
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002198 /* Get a wakelock as this may take a while, and we don't want the
2199 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2200 * wants to keep the screen on, it can grab a full wakelock.
2201 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002202 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002203 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2204
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002205 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002206 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002207 */
2208 property_set("vold.decrypt", "trigger_shutdown_framework");
2209 SLOGD("Just asked init to shut down class main\n");
2210
Jeff Sharkey9c484982015-03-31 10:35:33 -07002211 /* Ask vold to unmount all devices that it manages */
2212 if (vold_unmountAll()) {
2213 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002214 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002215
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002216 /* no_ui means we are being called from init, not settings.
2217 Now we always reboot from settings, so !no_ui means reboot
2218 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002219 if (!no_ui) {
2220 /* Try fallback, which is to reboot and try there */
2221 onlyCreateHeader = true;
2222 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2223 if (breadcrumb == 0) {
2224 SLOGE("Failed to create breadcrumb file");
2225 goto error_shutting_down;
2226 }
2227 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002228 }
2229
2230 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002231 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002232 /* Now that /data is unmounted, we need to mount a tmpfs
2233 * /data, set a property saying we're doing inplace encryption,
2234 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002235 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002236 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002237 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002238 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002239 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002240 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002241
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002242 /* restart the framework. */
2243 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002244 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002245
Ken Sumrall92736ef2012-10-17 20:57:14 -07002246 /* Ugh, shutting down the framework is not synchronous, so until it
2247 * can be fixed, this horrible hack will wait a moment for it all to
2248 * shut down before proceeding. Without it, some devices cannot
2249 * restart the graphics services.
2250 */
2251 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002252 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002253
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002254 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002255 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002256 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002257 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2258 goto error_shutting_down;
2259 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002260
Paul Lawrence87999172014-02-20 12:21:31 -08002261 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002262 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002263 } else {
2264 crypt_ftr.fs_size = nr_sec;
2265 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002266 /* At this point, we are in an inconsistent state. Until we successfully
2267 complete encryption, a reboot will leave us broken. So mark the
2268 encryption failed in case that happens.
2269 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002270 if (onlyCreateHeader) {
2271 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2272 } else {
2273 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2274 }
Paul Lawrence87999172014-02-20 12:21:31 -08002275 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002276 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2277 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002278
Paul Lawrence87999172014-02-20 12:21:31 -08002279 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002280 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2281 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002282 SLOGE("Cannot create encrypted master key\n");
2283 goto error_shutting_down;
2284 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002285
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002286 /* Replace scrypted intermediate key if we are preparing for a reboot */
2287 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002288 unsigned char fake_master_key[MAX_KEY_LEN];
2289 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002290 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002291 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2292 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002293 }
2294
Paul Lawrence87999172014-02-20 12:21:31 -08002295 /* Write the key to the end of the partition */
2296 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002297
Paul Lawrence87999172014-02-20 12:21:31 -08002298 /* If any persistent data has been remembered, save it.
2299 * If none, create a valid empty table and save that.
2300 */
2301 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002302 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2303 if (pdata) {
2304 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2305 persist_data = pdata;
2306 }
Paul Lawrence87999172014-02-20 12:21:31 -08002307 }
2308 if (persist_data) {
2309 save_persistent_data();
2310 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002311 }
2312
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002313 if (onlyCreateHeader) {
2314 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002315 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002316 }
2317
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002318 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002319 /* startup service classes main and late_start */
2320 property_set("vold.decrypt", "trigger_restart_min_framework");
2321 SLOGD("Just triggered restart_min_framework\n");
2322
2323 /* OK, the framework is restarted and will soon be showing a
2324 * progress bar. Time to setup an encrypted mapping, and
2325 * either write a new filesystem, or encrypt in place updating
2326 * the progress bar as we work.
2327 */
2328 }
2329
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002330 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002331 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002332 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002333
Paul Lawrence87999172014-02-20 12:21:31 -08002334 /* If we are continuing, check checksums match */
2335 rc = 0;
2336 if (previously_encrypted_upto) {
2337 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2338 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002339
Paul Crowley14c8c072018-09-18 13:30:21 -07002340 if (!rc &&
2341 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002342 SLOGE("Checksums do not match - trigger wipe");
2343 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002344 }
2345 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002346
Paul Lawrence87999172014-02-20 12:21:31 -08002347 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002348 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002349 previously_encrypted_upto);
2350 }
2351
2352 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002353 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002354 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002355 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002356 SLOGE("Error calculating checksum for continuing encryption");
2357 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002358 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002359 }
2360
2361 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002362 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002363
Paul Crowley14c8c072018-09-18 13:30:21 -07002364 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002365 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002366 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002367
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002368 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002369 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2370 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002371 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002372 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002373
Paul Lawrence6bfed202014-07-28 12:47:22 -07002374 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002375
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002376 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2377 char value[PROPERTY_VALUE_MAX];
2378 property_get("ro.crypto.state", value, "");
2379 if (!strcmp(value, "")) {
2380 /* default encryption - continue first boot sequence */
2381 property_set("ro.crypto.state", "encrypted");
2382 property_set("ro.crypto.type", "block");
2383 release_wake_lock(lockid);
2384 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2385 // Bring up cryptkeeper that will check the password and set it
2386 property_set("vold.decrypt", "trigger_shutdown_framework");
2387 sleep(2);
2388 property_set("vold.encrypt_progress", "");
2389 cryptfs_trigger_restart_min_framework();
2390 } else {
2391 cryptfs_check_passwd(DEFAULT_PASSWORD);
2392 cryptfs_restart_internal(1);
2393 }
2394 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002395 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002396 sleep(2); /* Give the UI a chance to show 100% progress */
2397 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002398 }
Paul Lawrence87999172014-02-20 12:21:31 -08002399 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002400 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002401 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002402 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002403 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002404 char value[PROPERTY_VALUE_MAX];
2405
Ken Sumrall319369a2012-06-27 16:30:18 -07002406 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002407 if (!strcmp(value, "1")) {
2408 /* wipe data if encryption failed */
2409 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002410 std::string err;
2411 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002412 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002413 if (!write_bootloader_message(options, &err)) {
2414 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002415 }
Josh Gaofec44372017-08-28 13:22:55 -07002416 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002417 } else {
2418 /* set property to trigger dialog */
2419 property_set("vold.encrypt_progress", "error_partially_encrypted");
2420 release_wake_lock(lockid);
2421 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002422 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002423 }
2424
Ken Sumrall3ed82362011-01-28 23:31:16 -08002425 /* hrm, the encrypt step claims success, but the reboot failed.
2426 * This should not happen.
2427 * Set the property and return. Hope the framework can deal with it.
2428 */
2429 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002430 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002431 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002432
2433error_unencrypted:
2434 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002435 if (lockid[0]) {
2436 release_wake_lock(lockid);
2437 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002438 return -1;
2439
2440error_shutting_down:
2441 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2442 * but the framework is stopped and not restarted to show the error, so it's up to
2443 * vold to restart the system.
2444 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002445 SLOGE(
2446 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2447 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002448 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002449
2450 /* shouldn't get here */
2451 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002452 if (lockid[0]) {
2453 release_wake_lock(lockid);
2454 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002455 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002456}
2457
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002458int cryptfs_enable(int type, const char* passwd, int no_ui) {
2459 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002460}
2461
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002462int cryptfs_enable_default(int no_ui) {
2463 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002464}
2465
Paul Crowley14c8c072018-09-18 13:30:21 -07002466int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002467 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002468 SLOGE("cryptfs_changepw not valid for file encryption");
2469 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002470 }
2471
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002472 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002473 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002474
2475 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002476 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002477 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002478 return -1;
2479 }
2480
Paul Lawrencef4faa572014-01-29 13:31:03 -08002481 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2482 SLOGE("Invalid crypt_type %d", crypt_type);
2483 return -1;
2484 }
2485
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002486 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002487 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002488 SLOGE("Error getting crypt footer and key");
2489 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002490 }
2491
Paul Lawrencef4faa572014-01-29 13:31:03 -08002492 crypt_ftr.crypt_type = crypt_type;
2493
Paul Crowley14c8c072018-09-18 13:30:21 -07002494 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2495 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002496 if (rc) {
2497 SLOGE("Encrypt master key failed: %d", rc);
2498 return -1;
2499 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002500 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002501 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002502
2503 return 0;
2504}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002505
Rubin Xu85c01f92014-10-13 12:49:54 +01002506static unsigned int persist_get_max_entries(int encrypted) {
2507 struct crypt_mnt_ftr crypt_ftr;
2508 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002509
2510 /* If encrypted, use the values from the crypt_ftr, otherwise
2511 * use the values for the current spec.
2512 */
2513 if (encrypted) {
2514 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002515 /* Something is wrong, assume no space for entries */
2516 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002517 }
2518 dsize = crypt_ftr.persist_data_size;
2519 } else {
2520 dsize = CRYPT_PERSIST_DATA_SIZE;
2521 }
2522
Rubin Xuf83cc612018-10-09 16:13:38 +01002523 if (dsize > sizeof(struct crypt_persist_data)) {
2524 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2525 } else {
2526 return 0;
2527 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002528}
2529
Paul Crowley14c8c072018-09-18 13:30:21 -07002530static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002531 unsigned int i;
2532
2533 if (persist_data == NULL) {
2534 return -1;
2535 }
2536 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2537 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2538 /* We found it! */
2539 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2540 return 0;
2541 }
2542 }
2543
2544 return -1;
2545}
2546
Paul Crowley14c8c072018-09-18 13:30:21 -07002547static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002548 unsigned int i;
2549 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002550 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002551
2552 if (persist_data == NULL) {
2553 return -1;
2554 }
2555
Rubin Xu85c01f92014-10-13 12:49:54 +01002556 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002557
2558 num = persist_data->persist_valid_entries;
2559
2560 for (i = 0; i < num; i++) {
2561 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2562 /* We found an existing entry, update it! */
2563 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2564 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2565 return 0;
2566 }
2567 }
2568
2569 /* We didn't find it, add it to the end, if there is room */
2570 if (persist_data->persist_valid_entries < max_persistent_entries) {
2571 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2572 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2573 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2574 persist_data->persist_valid_entries++;
2575 return 0;
2576 }
2577
2578 return -1;
2579}
2580
Rubin Xu85c01f92014-10-13 12:49:54 +01002581/**
2582 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2583 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2584 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002585int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002586 std::string key_ = key;
2587 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002588
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002589 std::string parsed_field;
2590 unsigned parsed_index;
2591
2592 std::string::size_type split = key_.find_last_of('_');
2593 if (split == std::string::npos) {
2594 parsed_field = key_;
2595 parsed_index = 0;
2596 } else {
2597 parsed_field = key_.substr(0, split);
2598 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002599 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002600
2601 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002602}
2603
2604/*
2605 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2606 * remaining entries starting from index will be deleted.
2607 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2608 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2609 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2610 *
2611 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002612static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002613 unsigned int i;
2614 unsigned int j;
2615 unsigned int num;
2616
2617 if (persist_data == NULL) {
2618 return PERSIST_DEL_KEY_ERROR_OTHER;
2619 }
2620
2621 num = persist_data->persist_valid_entries;
2622
Paul Crowley14c8c072018-09-18 13:30:21 -07002623 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002624 // Filter out to-be-deleted entries in place.
2625 for (i = 0; i < num; i++) {
2626 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2627 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2628 j++;
2629 }
2630 }
2631
2632 if (j < num) {
2633 persist_data->persist_valid_entries = j;
2634 // Zeroise the remaining entries
2635 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2636 return PERSIST_DEL_KEY_OK;
2637 } else {
2638 // Did not find an entry matching the given fieldname
2639 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2640 }
2641}
2642
Paul Crowley14c8c072018-09-18 13:30:21 -07002643static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002644 unsigned int i;
2645 unsigned int count;
2646
2647 if (persist_data == NULL) {
2648 return -1;
2649 }
2650
2651 count = 0;
2652 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2653 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2654 count++;
2655 }
2656 }
2657
2658 return count;
2659}
2660
Ken Sumrall160b4d62013-04-22 12:15:39 -07002661/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002662int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002663 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002664 SLOGE("Cannot get field when file encrypted");
2665 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002666 }
2667
Ken Sumrall160b4d62013-04-22 12:15:39 -07002668 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002669 /* CRYPTO_GETFIELD_OK is success,
2670 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2671 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2672 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002673 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002674 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2675 int i;
2676 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002677
2678 if (persist_data == NULL) {
2679 load_persistent_data();
2680 if (persist_data == NULL) {
2681 SLOGE("Getfield error, cannot load persistent data");
2682 goto out;
2683 }
2684 }
2685
Rubin Xu85c01f92014-10-13 12:49:54 +01002686 // Read value from persistent entries. If the original value is split into multiple entries,
2687 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002688 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002689 // 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 -07002690 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002691 // value too small
2692 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2693 goto out;
2694 }
2695 rc = CRYPTO_GETFIELD_OK;
2696
2697 for (i = 1; /* break explicitly */; i++) {
2698 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002699 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002700 // If the fieldname is very long, we stop as soon as it begins to overflow the
2701 // maximum field length. At this point we have in fact fully read out the original
2702 // value because cryptfs_setfield would not allow fields with longer names to be
2703 // written in the first place.
2704 break;
2705 }
2706 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002707 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2708 // value too small.
2709 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2710 goto out;
2711 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002712 } else {
2713 // Exhaust all entries.
2714 break;
2715 }
2716 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002717 } else {
2718 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002719 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002720 }
2721
2722out:
2723 return rc;
2724}
2725
2726/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002727int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002728 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002729 SLOGE("Cannot set field when file encrypted");
2730 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002731 }
2732
Ken Sumrall160b4d62013-04-22 12:15:39 -07002733 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002734 /* 0 is success, negative values are error */
2735 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002736 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002737 unsigned int field_id;
2738 char temp_field[PROPERTY_KEY_MAX];
2739 unsigned int num_entries;
2740 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002741
2742 if (persist_data == NULL) {
2743 load_persistent_data();
2744 if (persist_data == NULL) {
2745 SLOGE("Setfield error, cannot load persistent data");
2746 goto out;
2747 }
2748 }
2749
2750 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002751 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002752 encrypted = 1;
2753 }
2754
Rubin Xu85c01f92014-10-13 12:49:54 +01002755 // Compute the number of entries required to store value, each entry can store up to
2756 // (PROPERTY_VALUE_MAX - 1) chars
2757 if (strlen(value) == 0) {
2758 // Empty value also needs one entry to store.
2759 num_entries = 1;
2760 } else {
2761 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2762 }
2763
2764 max_keylen = strlen(fieldname);
2765 if (num_entries > 1) {
2766 // Need an extra "_%d" suffix.
2767 max_keylen += 1 + log10(num_entries);
2768 }
2769 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2770 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002771 goto out;
2772 }
2773
Rubin Xu85c01f92014-10-13 12:49:54 +01002774 // Make sure we have enough space to write the new value
2775 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2776 persist_get_max_entries(encrypted)) {
2777 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2778 goto out;
2779 }
2780
2781 // Now that we know persist_data has enough space for value, let's delete the old field first
2782 // to make up space.
2783 persist_del_keys(fieldname, 0);
2784
2785 if (persist_set_key(fieldname, value, encrypted)) {
2786 // fail to set key, should not happen as we have already checked the available space
2787 SLOGE("persist_set_key() error during setfield()");
2788 goto out;
2789 }
2790
2791 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002792 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002793
2794 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2795 // fail to set key, should not happen as we have already checked the available space.
2796 SLOGE("persist_set_key() error during setfield()");
2797 goto out;
2798 }
2799 }
2800
Ken Sumrall160b4d62013-04-22 12:15:39 -07002801 /* If we are running encrypted, save the persistent data now */
2802 if (encrypted) {
2803 if (save_persistent_data()) {
2804 SLOGE("Setfield error, cannot save persistent data");
2805 goto out;
2806 }
2807 }
2808
Rubin Xu85c01f92014-10-13 12:49:54 +01002809 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002810
2811out:
2812 return rc;
2813}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002814
2815/* Checks userdata. Attempt to mount the volume if default-
2816 * encrypted.
2817 * On success trigger next init phase and return 0.
2818 * Currently do not handle failure - see TODO below.
2819 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002820int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002821 int crypt_type = cryptfs_get_password_type();
2822 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2823 SLOGE("Bad crypt type - error");
2824 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002825 SLOGD(
2826 "Password is not default - "
2827 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002828 property_set("vold.decrypt", "trigger_restart_min_framework");
2829 return 0;
2830 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2831 SLOGD("Password is default - restarting filesystem");
2832 cryptfs_restart_internal(0);
2833 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002834 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002835 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002836 }
2837
Paul Lawrence6bfed202014-07-28 12:47:22 -07002838 /** Corrupt. Allow us to boot into framework, which will detect bad
2839 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002840 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002841 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002842 return 0;
2843}
2844
2845/* Returns type of the password, default, pattern, pin or password.
2846 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002847int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002848 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002849 SLOGE("cryptfs_get_password_type not valid for file encryption");
2850 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002851 }
2852
Paul Lawrencef4faa572014-01-29 13:31:03 -08002853 struct crypt_mnt_ftr crypt_ftr;
2854
2855 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2856 SLOGE("Error getting crypt footer and key\n");
2857 return -1;
2858 }
2859
Paul Lawrence6bfed202014-07-28 12:47:22 -07002860 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2861 return -1;
2862 }
2863
Paul Lawrencef4faa572014-01-29 13:31:03 -08002864 return crypt_ftr.crypt_type;
2865}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002866
Paul Crowley14c8c072018-09-18 13:30:21 -07002867const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002868 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002869 SLOGE("cryptfs_get_password not valid for file encryption");
2870 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002871 }
2872
Paul Lawrence399317e2014-03-10 13:20:50 -07002873 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002874 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002875 if (now.tv_sec < password_expiry_time) {
2876 return password;
2877 } else {
2878 cryptfs_clear_password();
2879 return 0;
2880 }
2881}
2882
Paul Crowley14c8c072018-09-18 13:30:21 -07002883void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002884 if (password) {
2885 size_t len = strlen(password);
2886 memset(password, 0, len);
2887 free(password);
2888 password = 0;
2889 password_expiry_time = 0;
2890 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002891}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002892
Paul Crowley14c8c072018-09-18 13:30:21 -07002893int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002894 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07002895 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07002896}