blob: 41931deb3a8c8c9af65d48cf5e0c4edef84ac1d3 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
Logan Chiend557d762018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
Daniel Rosenberg65f99c92018-08-28 01:58:49 -070027#include "Checkpoint.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070029#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080030#include "Keymaster.h"
31#include "Process.h"
32#include "ScryptParameters.h"
Paul Crowleycfe39722018-10-30 15:59:24 -070033#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080034#include "VoldUtil.h"
35#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080036
Eric Biggersed45ec32019-01-25 10:47:55 -080037#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080039#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080040#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070043#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070045#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070046#include <fscrypt/fscrypt.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080047#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080048#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080049#include <logwrap/logwrap.h>
50#include <openssl/evp.h>
51#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080052#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080053
54#include <ctype.h>
55#include <errno.h>
56#include <fcntl.h>
57#include <inttypes.h>
58#include <libgen.h>
59#include <linux/dm-ioctl.h>
60#include <linux/kdev_t.h>
61#include <math.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <sys/ioctl.h>
66#include <sys/mount.h>
67#include <sys/param.h>
68#include <sys/stat.h>
69#include <sys/types.h>
70#include <sys/wait.h>
71#include <time.h>
72#include <unistd.h>
73
Wei Wang4375f1b2017-02-24 17:43:01 -080074extern "C" {
75#include <crypto_scrypt.h>
76}
Mark Salyzyn3e971272014-01-21 13:27:04 -080077
Eric Biggersed45ec32019-01-25 10:47:55 -080078using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080079using android::base::StringPrintf;
Paul Crowleycfe39722018-10-30 15:59:24 -070080using namespace std::chrono_literals;
81
Mark Salyzyn5eecc442014-02-12 14:16:14 -080082#define UNUSED __attribute__((unused))
83
Ken Sumrall8f869aa2010-12-03 03:47:09 -080084#define DM_CRYPT_BUF_SIZE 4096
85
Jason parks70a4b3f2011-01-28 10:10:47 -060086#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080087
88constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
89constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070090constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080091
92// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070093static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060094
Paul Crowley14c8c072018-09-18 13:30:21 -070095#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070096
Paul Lawrence3bd36d52015-06-09 13:37:44 -070097#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080098
Paul Lawrence3d99eba2015-11-20 07:07:19 -080099#define CRYPTO_BLOCK_DEVICE "userdata"
100
101#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
102
Ken Sumrall29d8da82011-05-18 17:20:07 -0700103#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700104#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700105
Ken Sumralle919efe2012-09-29 17:07:41 -0700106#define TABLE_LOAD_RETRIES 10
107
Shawn Willden47ba10d2014-09-03 17:07:06 -0600108#define RSA_KEY_SIZE 2048
109#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
110#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600111#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700112
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700113#define RETRY_MOUNT_ATTEMPTS 10
114#define RETRY_MOUNT_DELAY_SECONDS 1
115
Paul Crowley5afbc622017-11-27 09:42:17 -0800116#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
117
Paul Crowley73473332017-11-21 15:43:51 -0800118static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
119
Greg Kaiser59ad0182018-02-16 13:01:36 -0800120static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700121static char* saved_mount_point;
122static int master_key_saved = 0;
123static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800124
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700125/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700126static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000127 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700128}
129
130/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700131static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800132 if (ftr->keymaster_blob_size) {
133 SLOGI("Already have key");
134 return 0;
135 }
136
Paul Crowley14c8c072018-09-18 13:30:21 -0700137 int rc = keymaster_create_key_for_cryptfs_scrypt(
138 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
139 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000140 if (rc) {
141 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800142 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000143 ftr->keymaster_blob_size = 0;
144 }
145 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700146 return -1;
147 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000148 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700149}
150
Shawn Willdene17a9c42014-09-08 13:04:08 -0600151/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700152static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
153 const size_t object_size, unsigned char** signature,
154 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600155 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600156 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600157 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600158
Shawn Willdene17a9c42014-09-08 13:04:08 -0600159 // To sign a message with RSA, the message must satisfy two
160 // constraints:
161 //
162 // 1. The message, when interpreted as a big-endian numeric value, must
163 // be strictly less than the public modulus of the RSA key. Note
164 // that because the most significant bit of the public modulus is
165 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
166 // key), an n-bit message with most significant bit 0 always
167 // satisfies this requirement.
168 //
169 // 2. The message must have the same length in bits as the public
170 // modulus of the RSA key. This requirement isn't mathematically
171 // necessary, but is necessary to ensure consistency in
172 // implementations.
173 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600174 case KDF_SCRYPT_KEYMASTER:
175 // This ensures the most significant byte of the signed message
176 // is zero. We could have zero-padded to the left instead, but
177 // this approach is slightly more robust against changes in
178 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600179 // so) because we really should be using a proper deterministic
180 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800181 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600182 SLOGI("Signing safely-padded object");
183 break;
184 default:
185 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000186 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600187 }
Paul Crowley73473332017-11-21 15:43:51 -0800188 for (;;) {
189 auto result = keymaster_sign_object_for_cryptfs_scrypt(
190 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
191 to_sign_size, signature, signature_size);
192 switch (result) {
193 case KeymasterSignResult::ok:
194 return 0;
195 case KeymasterSignResult::upgrade:
196 break;
197 default:
198 return -1;
199 }
200 SLOGD("Upgrading key");
201 if (keymaster_upgrade_key_for_cryptfs_scrypt(
202 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
203 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
204 &ftr->keymaster_blob_size) != 0) {
205 SLOGE("Failed to upgrade key");
206 return -1;
207 }
208 if (put_crypt_ftr_and_key(ftr) != 0) {
209 SLOGE("Failed to write upgraded key to disk");
210 }
211 SLOGD("Key upgraded successfully");
212 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600213}
214
Paul Lawrence399317e2014-03-10 13:20:50 -0700215/* Store password when userdata is successfully decrypted and mounted.
216 * Cleared by cryptfs_clear_password
217 *
218 * To avoid a double prompt at boot, we need to store the CryptKeeper
219 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
220 * Since the entire framework is torn down and rebuilt after encryption,
221 * we have to use a daemon or similar to store the password. Since vold
222 * is secured against IPC except from system processes, it seems a reasonable
223 * place to store this.
224 *
225 * password should be cleared once it has been used.
226 *
227 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800228 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700229static char* password = 0;
230static int password_expiry_time = 0;
231static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800232
Paul Crowley14c8c072018-09-18 13:30:21 -0700233enum class RebootType { reboot, recovery, shutdown };
234static void cryptfs_reboot(RebootType rt) {
235 switch (rt) {
236 case RebootType::reboot:
237 property_set(ANDROID_RB_PROPERTY, "reboot");
238 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800239
Paul Crowley14c8c072018-09-18 13:30:21 -0700240 case RebootType::recovery:
241 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
242 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800243
Paul Crowley14c8c072018-09-18 13:30:21 -0700244 case RebootType::shutdown:
245 property_set(ANDROID_RB_PROPERTY, "shutdown");
246 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700247 }
Paul Lawrence87999172014-02-20 12:21:31 -0800248
Ken Sumralladfba362013-06-04 16:37:52 -0700249 sleep(20);
250
251 /* Shouldn't get here, reboot should happen before sleep times out */
252 return;
253}
254
Paul Crowley14c8c072018-09-18 13:30:21 -0700255static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800256 memset(io, 0, dataSize);
257 io->data_size = dataSize;
258 io->data_start = sizeof(struct dm_ioctl);
259 io->version[0] = 4;
260 io->version[1] = 0;
261 io->version[2] = 0;
262 io->flags = flags;
263 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100264 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800265 }
266}
267
Greg Kaiser38723f22018-02-16 13:35:35 -0800268namespace {
269
270struct CryptoType;
271
272// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700273const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800274
275struct CryptoType {
276 // We should only be constructing CryptoTypes as part of
277 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
278 // which isn't pure or fully protected as a concession to being able to
279 // do it all at compile time. Add new CryptoTypes in
280 // supported_crypto_types[] below.
281 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
282 constexpr CryptoType set_keysize(uint32_t size) const {
283 return CryptoType(this->property_name, this->crypto_name, size);
284 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700285 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800286 return CryptoType(property, this->crypto_name, this->keysize);
287 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700288 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800289 return CryptoType(this->property_name, crypto, this->keysize);
290 }
291
Paul Crowley14c8c072018-09-18 13:30:21 -0700292 constexpr const char* get_property_name() const { return property_name; }
293 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800294 constexpr uint32_t get_keysize() const { return keysize; }
295
Paul Crowley14c8c072018-09-18 13:30:21 -0700296 private:
297 const char* property_name;
298 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800299 uint32_t keysize;
300
Paul Crowley14c8c072018-09-18 13:30:21 -0700301 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800302 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700303 friend const CryptoType& get_crypto_type();
304 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800305};
306
307// We only want to parse this read-only property once. But we need to wait
308// until the system is initialized before we can read it. So we use a static
309// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700310const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800311 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
312 return crypto_type;
313}
314
315constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700316 .set_property_name("AES-128-CBC")
317 .set_crypto_name("aes-cbc-essiv:sha256")
318 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800319
320constexpr CryptoType supported_crypto_types[] = {
321 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800322 CryptoType()
323 .set_property_name("adiantum")
324 .set_crypto_name("xchacha12,aes-adiantum-plain64")
325 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800326 // Add new CryptoTypes here. Order is not important.
327};
328
Greg Kaiser38723f22018-02-16 13:35:35 -0800329// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
330// We confirm all supported_crypto_types have a small enough keysize and
331// had both set_property_name() and set_crypto_name() called.
332
333template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700334constexpr size_t array_length(T (&)[N]) {
335 return N;
336}
Greg Kaiser38723f22018-02-16 13:35:35 -0800337
338constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
339 return (index >= array_length(supported_crypto_types));
340}
341
Paul Crowley14c8c072018-09-18 13:30:21 -0700342constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800343 return ((crypto_type.get_property_name() != nullptr) &&
344 (crypto_type.get_crypto_name() != nullptr) &&
345 (crypto_type.get_keysize() <= MAX_KEY_LEN));
346}
347
348// Note in C++11 that constexpr functions can only have a single line.
349// So our code is a bit convoluted (using recursion instead of a loop),
350// but it's asserting at compile time that all of our key lengths are valid.
351constexpr bool validateSupportedCryptoTypes(size_t index) {
352 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700353 (isValidCryptoType(supported_crypto_types[index]) &&
354 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800355}
356
357static_assert(validateSupportedCryptoTypes(0),
358 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
359 "incompletely constructed.");
360// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
361
Greg Kaiser38723f22018-02-16 13:35:35 -0800362// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700363const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800364 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
365 char paramstr[PROPERTY_VALUE_MAX];
366
Paul Crowley14c8c072018-09-18 13:30:21 -0700367 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
368 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800369 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
370 return ctype;
371 }
372 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700373 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
374 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800375 return default_crypto_type;
376}
377
378} // namespace
379
Kenny Rootc4c70f12013-06-14 12:11:38 -0700380/**
381 * Gets the default device scrypt parameters for key derivation time tuning.
382 * The parameters should lead to about one second derivation time for the
383 * given device.
384 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700385static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700386 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000387 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700388
Paul Crowley63c18d32016-02-10 14:02:47 +0000389 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
390 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
391 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
392 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700393 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000394 ftr->N_factor = Nf;
395 ftr->r_factor = rf;
396 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700397}
398
Greg Kaiser57f9af62018-02-16 13:13:58 -0800399uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800400 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800401}
402
Paul Crowley14c8c072018-09-18 13:30:21 -0700403const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800404 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800405}
406
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200407static uint64_t get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800408 int fd, block_size;
409 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200410 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800411
Paul Crowley14c8c072018-09-18 13:30:21 -0700412 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800413 SLOGE("Cannot open device to get filesystem size ");
414 return 0;
415 }
416
417 if (lseek64(fd, 1024, SEEK_SET) < 0) {
418 SLOGE("Cannot seek to superblock");
419 return 0;
420 }
421
422 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
423 SLOGE("Cannot read superblock");
424 return 0;
425 }
426
427 close(fd);
428
Daniel Rosenberge82df162014-08-15 22:19:23 +0000429 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
430 SLOGE("Not a valid ext4 superblock");
431 return 0;
432 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800433 block_size = 1024 << sb.s_log_block_size;
434 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200435 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800436
437 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200438 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800439}
440
Paul Crowley14c8c072018-09-18 13:30:21 -0700441static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
442 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200443 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700444 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700445 char key_loc[PROPERTY_VALUE_MAX];
446 char real_blkdev[PROPERTY_VALUE_MAX];
447 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700448
Paul Crowley14c8c072018-09-18 13:30:21 -0700449 if (!cached_data) {
450 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700451
Paul Crowley14c8c072018-09-18 13:30:21 -0700452 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200453 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700454 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
455 * encryption info footer and key, and plenty of bytes to spare for future
456 * growth.
457 */
458 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200459 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700460 cached_data = 1;
461 } else {
462 SLOGE("Cannot get size of block device %s\n", real_blkdev);
463 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700464 } else {
465 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
466 cached_off = 0;
467 cached_data = 1;
468 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700469 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700470
Paul Crowley14c8c072018-09-18 13:30:21 -0700471 if (cached_data) {
472 if (metadata_fname) {
473 *metadata_fname = cached_metadata_fname;
474 }
475 if (off) {
476 *off = cached_off;
477 }
478 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700479 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700480
Paul Crowley14c8c072018-09-18 13:30:21 -0700481 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700482}
483
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800484/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700485static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800486 SHA256_CTX c;
487 SHA256_Init(&c);
488 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
489 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
490 SHA256_Final(crypt_ftr->sha256, &c);
491}
492
Ken Sumralle8744072011-01-18 22:01:55 -0800493/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800494 * update the failed mount count but not change the key.
495 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700496static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
497 int fd;
498 unsigned int cnt;
499 /* starting_off is set to the SEEK_SET offset
500 * where the crypto structure starts
501 */
502 off64_t starting_off;
503 int rc = -1;
504 char* fname = NULL;
505 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800506
Paul Crowley14c8c072018-09-18 13:30:21 -0700507 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800508
Paul Crowley14c8c072018-09-18 13:30:21 -0700509 if (get_crypt_ftr_info(&fname, &starting_off)) {
510 SLOGE("Unable to get crypt_ftr_info\n");
511 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800512 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700513 if (fname[0] != '/') {
514 SLOGE("Unexpected value for crypto key location\n");
515 return -1;
516 }
517 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
518 SLOGE("Cannot open footer file %s for put\n", fname);
519 return -1;
520 }
Ken Sumralle8744072011-01-18 22:01:55 -0800521
Paul Crowley14c8c072018-09-18 13:30:21 -0700522 /* Seek to the start of the crypt footer */
523 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
524 SLOGE("Cannot seek to real block device footer\n");
525 goto errout;
526 }
527
528 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
529 SLOGE("Cannot write real block device footer\n");
530 goto errout;
531 }
532
533 fstat(fd, &statbuf);
534 /* If the keys are kept on a raw block device, do not try to truncate it. */
535 if (S_ISREG(statbuf.st_mode)) {
536 if (ftruncate(fd, 0x4000)) {
537 SLOGE("Cannot set footer file size\n");
538 goto errout;
539 }
540 }
541
542 /* Success! */
543 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800544
545errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700546 close(fd);
547 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800548}
549
Paul Crowley14c8c072018-09-18 13:30:21 -0700550static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800551 struct crypt_mnt_ftr copy;
552 memcpy(&copy, crypt_ftr, sizeof(copy));
553 set_ftr_sha(&copy);
554 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
555}
556
Paul Crowley14c8c072018-09-18 13:30:21 -0700557static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700558 return TEMP_FAILURE_RETRY(read(fd, buff, len));
559}
560
Paul Crowley14c8c072018-09-18 13:30:21 -0700561static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700562 return TEMP_FAILURE_RETRY(write(fd, buff, len));
563}
564
Paul Crowley14c8c072018-09-18 13:30:21 -0700565static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700566 memset(pdata, 0, len);
567 pdata->persist_magic = PERSIST_DATA_MAGIC;
568 pdata->persist_valid_entries = 0;
569}
570
571/* A routine to update the passed in crypt_ftr to the lastest version.
572 * fd is open read/write on the device that holds the crypto footer and persistent
573 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
574 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
575 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700576static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700577 int orig_major = crypt_ftr->major_version;
578 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700579
Kenny Root7434b312013-06-14 11:29:53 -0700580 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700581 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700582 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700583
Kenny Rootc4c70f12013-06-14 12:11:38 -0700584 SLOGW("upgrading crypto footer to 1.1");
585
Paul Crowley14c8c072018-09-18 13:30:21 -0700586 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700587 if (pdata == NULL) {
588 SLOGE("Cannot allocate persisent data\n");
589 return;
590 }
591 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
592
593 /* Need to initialize the persistent data area */
594 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
595 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100596 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700597 return;
598 }
599 /* Write all zeros to the first copy, making it invalid */
600 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
601
602 /* Write a valid but empty structure to the second copy */
603 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
604 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
605
606 /* Update the footer */
607 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
608 crypt_ftr->persist_data_offset[0] = pdata_offset;
609 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
610 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100611 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700612 }
613
Paul Lawrencef4faa572014-01-29 13:31:03 -0800614 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700615 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800616 /* But keep the old kdf_type.
617 * It will get updated later to KDF_SCRYPT after the password has been verified.
618 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700619 crypt_ftr->kdf_type = KDF_PBKDF2;
620 get_device_scrypt_params(crypt_ftr);
621 crypt_ftr->minor_version = 2;
622 }
623
Paul Lawrencef4faa572014-01-29 13:31:03 -0800624 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
625 SLOGW("upgrading crypto footer to 1.3");
626 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
627 crypt_ftr->minor_version = 3;
628 }
629
Kenny Root7434b312013-06-14 11:29:53 -0700630 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
631 if (lseek64(fd, offset, SEEK_SET) == -1) {
632 SLOGE("Cannot seek to crypt footer\n");
633 return;
634 }
635 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700636 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700637}
638
Paul Crowley14c8c072018-09-18 13:30:21 -0700639static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
640 int fd;
641 unsigned int cnt;
642 off64_t starting_off;
643 int rc = -1;
644 char* fname = NULL;
645 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700646
Paul Crowley14c8c072018-09-18 13:30:21 -0700647 if (get_crypt_ftr_info(&fname, &starting_off)) {
648 SLOGE("Unable to get crypt_ftr_info\n");
649 return -1;
650 }
651 if (fname[0] != '/') {
652 SLOGE("Unexpected value for crypto key location\n");
653 return -1;
654 }
655 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
656 SLOGE("Cannot open footer file %s for get\n", fname);
657 return -1;
658 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800659
Paul Crowley14c8c072018-09-18 13:30:21 -0700660 /* Make sure it's 16 Kbytes in length */
661 fstat(fd, &statbuf);
662 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
663 SLOGE("footer file %s is not the expected size!\n", fname);
664 goto errout;
665 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700666
Paul Crowley14c8c072018-09-18 13:30:21 -0700667 /* Seek to the start of the crypt footer */
668 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
669 SLOGE("Cannot seek to real block device footer\n");
670 goto errout;
671 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700672
Paul Crowley14c8c072018-09-18 13:30:21 -0700673 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
674 SLOGE("Cannot read real block device footer\n");
675 goto errout;
676 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800677
Paul Crowley14c8c072018-09-18 13:30:21 -0700678 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
679 SLOGE("Bad magic for real block device %s\n", fname);
680 goto errout;
681 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800682
Paul Crowley14c8c072018-09-18 13:30:21 -0700683 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
684 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
685 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
686 goto errout;
687 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800688
Paul Crowley14c8c072018-09-18 13:30:21 -0700689 // We risk buffer overflows with oversized keys, so we just reject them.
690 // 0-sized keys are problematic (essentially by-passing encryption), and
691 // AES-CBC key wrapping only works for multiples of 16 bytes.
692 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
693 (crypt_ftr->keysize > MAX_KEY_LEN)) {
694 SLOGE(
695 "Invalid keysize (%u) for block device %s; Must be non-zero, "
696 "divisible by 16, and <= %d\n",
697 crypt_ftr->keysize, fname, MAX_KEY_LEN);
698 goto errout;
699 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800700
Paul Crowley14c8c072018-09-18 13:30:21 -0700701 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
702 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
703 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
704 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800705
Paul Crowley14c8c072018-09-18 13:30:21 -0700706 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
707 * copy on disk before returning.
708 */
709 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
710 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
711 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800712
Paul Crowley14c8c072018-09-18 13:30:21 -0700713 /* Success! */
714 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800715
716errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700717 close(fd);
718 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800719}
720
Paul Crowley14c8c072018-09-18 13:30:21 -0700721static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700722 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
723 crypt_ftr->persist_data_offset[1]) {
724 SLOGE("Crypt_ftr persist data regions overlap");
725 return -1;
726 }
727
728 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
729 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
730 return -1;
731 }
732
733 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700734 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700735 CRYPT_FOOTER_OFFSET) {
736 SLOGE("Persistent data extends past crypto footer");
737 return -1;
738 }
739
740 return 0;
741}
742
Paul Crowley14c8c072018-09-18 13:30:21 -0700743static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700744 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700745 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700746 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700747 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700748 int found = 0;
749 int fd;
750 int ret;
751 int i;
752
753 if (persist_data) {
754 /* Nothing to do, we've already loaded or initialized it */
755 return 0;
756 }
757
Ken Sumrall160b4d62013-04-22 12:15:39 -0700758 /* If not encrypted, just allocate an empty table and initialize it */
759 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700760 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800761 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700762 if (pdata) {
763 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
764 persist_data = pdata;
765 return 0;
766 }
767 return -1;
768 }
769
Paul Crowley14c8c072018-09-18 13:30:21 -0700770 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700771 return -1;
772 }
773
Paul Crowley14c8c072018-09-18 13:30:21 -0700774 if ((crypt_ftr.major_version < 1) ||
775 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700776 SLOGE("Crypt_ftr version doesn't support persistent data");
777 return -1;
778 }
779
780 if (get_crypt_ftr_info(&fname, NULL)) {
781 return -1;
782 }
783
784 ret = validate_persistent_data_storage(&crypt_ftr);
785 if (ret) {
786 return -1;
787 }
788
Paul Crowley14c8c072018-09-18 13:30:21 -0700789 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700790 if (fd < 0) {
791 SLOGE("Cannot open %s metadata file", fname);
792 return -1;
793 }
794
Wei Wang4375f1b2017-02-24 17:43:01 -0800795 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800796 if (pdata == NULL) {
797 SLOGE("Cannot allocate memory for persistent data");
798 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700799 }
800
801 for (i = 0; i < 2; i++) {
802 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
803 SLOGE("Cannot seek to read persistent data on %s", fname);
804 goto err2;
805 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700806 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700807 SLOGE("Error reading persistent data on iteration %d", i);
808 goto err2;
809 }
810 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
811 found = 1;
812 break;
813 }
814 }
815
816 if (!found) {
817 SLOGI("Could not find valid persistent data, creating");
818 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
819 }
820
821 /* Success */
822 persist_data = pdata;
823 close(fd);
824 return 0;
825
826err2:
827 free(pdata);
828
829err:
830 close(fd);
831 return -1;
832}
833
Paul Crowley14c8c072018-09-18 13:30:21 -0700834static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700835 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700836 struct crypt_persist_data* pdata;
837 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700838 off64_t write_offset;
839 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700840 int fd;
841 int ret;
842
843 if (persist_data == NULL) {
844 SLOGE("No persistent data to save");
845 return -1;
846 }
847
Paul Crowley14c8c072018-09-18 13:30:21 -0700848 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700849 return -1;
850 }
851
Paul Crowley14c8c072018-09-18 13:30:21 -0700852 if ((crypt_ftr.major_version < 1) ||
853 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700854 SLOGE("Crypt_ftr version doesn't support persistent data");
855 return -1;
856 }
857
858 ret = validate_persistent_data_storage(&crypt_ftr);
859 if (ret) {
860 return -1;
861 }
862
863 if (get_crypt_ftr_info(&fname, NULL)) {
864 return -1;
865 }
866
Paul Crowley14c8c072018-09-18 13:30:21 -0700867 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700868 if (fd < 0) {
869 SLOGE("Cannot open %s metadata file", fname);
870 return -1;
871 }
872
Wei Wang4375f1b2017-02-24 17:43:01 -0800873 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700874 if (pdata == NULL) {
875 SLOGE("Cannot allocate persistant data");
876 goto err;
877 }
878
879 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
880 SLOGE("Cannot seek to read persistent data on %s", fname);
881 goto err2;
882 }
883
884 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700885 SLOGE("Error reading persistent data before save");
886 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700887 }
888
889 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
890 /* The first copy is the curent valid copy, so write to
891 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700892 write_offset = crypt_ftr.persist_data_offset[1];
893 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700894 } else {
895 /* The second copy must be the valid copy, so write to
896 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700897 write_offset = crypt_ftr.persist_data_offset[0];
898 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700899 }
900
901 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100902 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700903 SLOGE("Cannot seek to write persistent data");
904 goto err2;
905 }
906 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700907 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100908 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700909 SLOGE("Cannot seek to erase previous persistent data");
910 goto err2;
911 }
912 fsync(fd);
913 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -0700914 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700915 SLOGE("Cannot write to erase previous persistent data");
916 goto err2;
917 }
918 fsync(fd);
919 } else {
920 SLOGE("Cannot write to save persistent data");
921 goto err2;
922 }
923
924 /* Success */
925 free(pdata);
926 close(fd);
927 return 0;
928
929err2:
930 free(pdata);
931err:
932 close(fd);
933 return -1;
934}
935
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800936/* Convert a binary key of specified length into an ascii hex string equivalent,
937 * without the leading 0x and with null termination
938 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700939static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
940 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700941 unsigned int i, a;
942 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800943
Paul Crowley14c8c072018-09-18 13:30:21 -0700944 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700945 /* For each byte, write out two ascii hex digits */
946 nibble = (master_key[i] >> 4) & 0xf;
947 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800948
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700949 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -0700950 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700951 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800952
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700953 /* Add the null termination */
954 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800955}
956
Paul Crowley14c8c072018-09-18 13:30:21 -0700957static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
958 const unsigned char* master_key, const char* real_blk_name,
959 const char* name, int fd, const char* extra_params) {
960 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
961 struct dm_ioctl* io;
962 struct dm_target_spec* tgt;
963 char* crypt_params;
964 // We need two ASCII characters to represent each byte, and need space for
965 // the '\0' terminator.
966 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
967 size_t buff_offset;
968 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800969
Paul Crowley14c8c072018-09-18 13:30:21 -0700970 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800971
Paul Crowley14c8c072018-09-18 13:30:21 -0700972 /* Load the mapping table for this device */
973 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800974
Paul Crowley14c8c072018-09-18 13:30:21 -0700975 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
976 io->target_count = 1;
977 tgt->status = 0;
978 tgt->sector_start = 0;
979 tgt->length = crypt_ftr->fs_size;
980 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800981
Paul Crowley14c8c072018-09-18 13:30:21 -0700982 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
983 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800984
Paul Crowley14c8c072018-09-18 13:30:21 -0700985 buff_offset = crypt_params - buffer;
Eric Biggerse1a7e772019-01-25 12:11:25 -0800986 SLOGI(
987 "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
988 name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
989 extra_params);
Paul Crowley14c8c072018-09-18 13:30:21 -0700990 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
991 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
992 crypt_params += strlen(crypt_params) + 1;
993 crypt_params =
994 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
995 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800996
Paul Crowley14c8c072018-09-18 13:30:21 -0700997 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
998 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
999 break;
1000 }
1001 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001002 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001003
Paul Crowley14c8c072018-09-18 13:30:21 -07001004 if (i == TABLE_LOAD_RETRIES) {
1005 /* We failed to load the table, return an error */
1006 return -1;
1007 } else {
1008 return i + 1;
1009 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001010}
1011
Paul Crowley14c8c072018-09-18 13:30:21 -07001012static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001013 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001014 struct dm_ioctl* io;
1015 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001016
Paul Crowley14c8c072018-09-18 13:30:21 -07001017 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001018
1019 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1020
1021 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1022 return -1;
1023 }
1024
1025 /* Iterate over the returned versions, looking for name of "crypt".
1026 * When found, get and return the version.
1027 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001028 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001029 while (v->next) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001030 if (!strcmp(v->name, "crypt")) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001031 /* We found the crypt driver, return the version, and get out */
1032 version[0] = v->version[0];
1033 version[1] = v->version[1];
1034 version[2] = v->version[2];
1035 return 0;
1036 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001037 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001038 }
1039
1040 return -1;
1041}
1042
Paul Crowley5afbc622017-11-27 09:42:17 -08001043static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1044 if (extra_params_vec.empty()) return "";
1045 std::string extra_params = std::to_string(extra_params_vec.size());
1046 for (const auto& p : extra_params_vec) {
1047 extra_params.append(" ");
1048 extra_params.append(p);
1049 }
1050 return extra_params;
1051}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001052
Eric Biggersed45ec32019-01-25 10:47:55 -08001053/*
1054 * If the ro.crypto.fde_sector_size system property is set, append the
1055 * parameters to make dm-crypt use the specified crypto sector size and round
1056 * the crypto device size down to a crypto sector boundary.
1057 */
1058static int add_sector_size_param(std::vector<std::string>* extra_params_vec,
1059 struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001060 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001061 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001062
Eric Biggersed45ec32019-01-25 10:47:55 -08001063 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1064 unsigned int sector_size;
1065
1066 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1067 (sector_size & (sector_size - 1)) != 0) {
1068 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1069 DM_CRYPT_SECTOR_SIZE, value);
1070 return -1;
1071 }
1072
1073 std::string param = StringPrintf("sector_size:%u", sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001074 extra_params_vec->push_back(std::move(param));
1075
1076 // With this option, IVs will match the sector numbering, instead
1077 // of being hard-coded to being based on 512-byte sectors.
1078 extra_params_vec->emplace_back("iv_large_sectors");
Eric Biggersed45ec32019-01-25 10:47:55 -08001079
1080 // Round the crypto device size down to a crypto sector boundary.
1081 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001082 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001083 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001084}
1085
Paul Crowley5afbc622017-11-27 09:42:17 -08001086static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1087 const char* real_blk_name, char* crypto_blk_name, const char* name,
1088 uint32_t flags) {
1089 char buffer[DM_CRYPT_BUF_SIZE];
1090 struct dm_ioctl* io;
1091 unsigned int minor;
1092 int fd = 0;
1093 int err;
1094 int retval = -1;
1095 int version[3];
1096 int load_count;
1097 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001098
Paul Crowley5afbc622017-11-27 09:42:17 -08001099 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1100 SLOGE("Cannot open device-mapper\n");
1101 goto errout;
1102 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001103
Paul Crowley5afbc622017-11-27 09:42:17 -08001104 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001105
Paul Crowley5afbc622017-11-27 09:42:17 -08001106 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1107 err = ioctl(fd, DM_DEV_CREATE, io);
1108 if (err) {
1109 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1110 goto errout;
1111 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001112
Paul Crowley5afbc622017-11-27 09:42:17 -08001113 /* Get the device status, in particular, the name of it's device file */
1114 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1115 if (ioctl(fd, DM_DEV_STATUS, io)) {
1116 SLOGE("Cannot retrieve dm-crypt device status\n");
1117 goto errout;
1118 }
1119 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1120 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001121
Paul Crowley5afbc622017-11-27 09:42:17 -08001122 if (!get_dm_crypt_version(fd, name, version)) {
1123 /* Support for allow_discards was added in version 1.11.0 */
1124 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1125 extra_params_vec.emplace_back("allow_discards");
1126 }
1127 }
1128 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1129 extra_params_vec.emplace_back("allow_encrypt_override");
1130 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001131 if (add_sector_size_param(&extra_params_vec, crypt_ftr)) {
1132 SLOGE("Error processing dm-crypt sector size param\n");
1133 goto errout;
1134 }
Paul Crowley5afbc622017-11-27 09:42:17 -08001135 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1136 extra_params_as_string(extra_params_vec).c_str());
1137 if (load_count < 0) {
1138 SLOGE("Cannot load dm-crypt mapping table.\n");
1139 goto errout;
1140 } else if (load_count > 1) {
1141 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1142 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001143
Paul Crowley5afbc622017-11-27 09:42:17 -08001144 /* Resume this device to activate it */
1145 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001146
Paul Crowley5afbc622017-11-27 09:42:17 -08001147 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1148 SLOGE("Cannot resume the dm-crypt device\n");
1149 goto errout;
1150 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001151
Paul Crowleycfe39722018-10-30 15:59:24 -07001152 /* Ensure the dm device has been created before returning. */
1153 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1154 // WaitForFile generates a suitable log message
1155 goto errout;
1156 }
1157
Paul Crowley5afbc622017-11-27 09:42:17 -08001158 /* We made it here with no errors. Woot! */
1159 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001160
1161errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001162 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 -08001163
Paul Crowley14c8c072018-09-18 13:30:21 -07001164 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165}
1166
Paul Crowley14c8c072018-09-18 13:30:21 -07001167static int delete_crypto_blk_dev(const char* name) {
1168 int fd;
1169 char buffer[DM_CRYPT_BUF_SIZE];
1170 struct dm_ioctl* io;
1171 int retval = -1;
Yue Hu9d6cc182018-12-17 17:09:55 +08001172 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001173
Paul Crowley14c8c072018-09-18 13:30:21 -07001174 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1175 SLOGE("Cannot open device-mapper\n");
1176 goto errout;
1177 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001178
Paul Crowley14c8c072018-09-18 13:30:21 -07001179 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001180
Paul Crowley14c8c072018-09-18 13:30:21 -07001181 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Yue Hu9d6cc182018-12-17 17:09:55 +08001182 err = ioctl(fd, DM_DEV_REMOVE, io);
1183 if (err) {
1184 SLOGE("Cannot remove dm-crypt device %s: %s\n", name, strerror(errno));
Paul Crowley14c8c072018-09-18 13:30:21 -07001185 goto errout;
1186 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001187
Paul Crowley14c8c072018-09-18 13:30:21 -07001188 /* We made it here with no errors. Woot! */
1189 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001190
1191errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001192 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 -08001193
Paul Crowley14c8c072018-09-18 13:30:21 -07001194 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001195}
1196
Paul Crowley14c8c072018-09-18 13:30:21 -07001197static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1198 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001199 SLOGI("Using pbkdf2 for cryptfs KDF");
1200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001201 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001202 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1203 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001204}
1205
Paul Crowley14c8c072018-09-18 13:30:21 -07001206static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001207 SLOGI("Using scrypt for cryptfs KDF");
1208
Paul Crowley14c8c072018-09-18 13:30:21 -07001209 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001210
1211 int N = 1 << ftr->N_factor;
1212 int r = 1 << ftr->r_factor;
1213 int p = 1 << ftr->p_factor;
1214
1215 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001216 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001217 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001218
Paul Crowley14c8c072018-09-18 13:30:21 -07001219 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001220}
1221
Paul Crowley14c8c072018-09-18 13:30:21 -07001222static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1223 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001224 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1225
1226 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001227 size_t signature_size;
1228 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001229 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001230
1231 int N = 1 << ftr->N_factor;
1232 int r = 1 << ftr->r_factor;
1233 int p = 1 << ftr->p_factor;
1234
Paul Crowley14c8c072018-09-18 13:30:21 -07001235 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001236 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001237
1238 if (rc) {
1239 SLOGE("scrypt failed");
1240 return -1;
1241 }
1242
Paul Crowley14c8c072018-09-18 13:30:21 -07001243 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001244 SLOGE("Signing failed");
1245 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001246 }
1247
Paul Crowley14c8c072018-09-18 13:30:21 -07001248 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1249 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001250 free(signature);
1251
1252 if (rc) {
1253 SLOGE("scrypt failed");
1254 return -1;
1255 }
1256
1257 return 0;
1258}
1259
Paul Crowley14c8c072018-09-18 13:30:21 -07001260static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1261 const unsigned char* decrypted_master_key,
1262 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1263 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001264 EVP_CIPHER_CTX e_ctx;
1265 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001266 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001267
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001268 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001269 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001270
1271 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001272 case KDF_SCRYPT_KEYMASTER:
1273 if (keymaster_create_key(crypt_ftr)) {
1274 SLOGE("keymaster_create_key failed");
1275 return -1;
1276 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001277
Paul Crowley14c8c072018-09-18 13:30:21 -07001278 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1279 SLOGE("scrypt failed");
1280 return -1;
1281 }
1282 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001283
Paul Crowley14c8c072018-09-18 13:30:21 -07001284 case KDF_SCRYPT:
1285 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1286 SLOGE("scrypt failed");
1287 return -1;
1288 }
1289 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001290
Paul Crowley14c8c072018-09-18 13:30:21 -07001291 default:
1292 SLOGE("Invalid kdf_type");
1293 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001294 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001295
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001296 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001297 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001298 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1299 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001300 SLOGE("EVP_EncryptInit failed\n");
1301 return -1;
1302 }
1303 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001304
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001305 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001306 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1307 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001308 SLOGE("EVP_EncryptUpdate failed\n");
1309 return -1;
1310 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001311 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001312 SLOGE("EVP_EncryptFinal failed\n");
1313 return -1;
1314 }
1315
Greg Kaiser59ad0182018-02-16 13:01:36 -08001316 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001317 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1318 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001319 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001320
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001321 /* Store the scrypt of the intermediate key, so we can validate if it's a
1322 password error or mount error when things go wrong.
1323 Note there's no need to check for errors, since if this is incorrect, we
1324 simply won't wipe userdata, which is the correct default behavior
1325 */
1326 int N = 1 << crypt_ftr->N_factor;
1327 int r = 1 << crypt_ftr->r_factor;
1328 int p = 1 << crypt_ftr->p_factor;
1329
Paul Crowley14c8c072018-09-18 13:30:21 -07001330 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1331 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001332 sizeof(crypt_ftr->scrypted_intermediate_key));
1333
1334 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001335 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001336 }
1337
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001338 EVP_CIPHER_CTX_cleanup(&e_ctx);
1339
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001340 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001341}
1342
Paul Crowley14c8c072018-09-18 13:30:21 -07001343static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1344 const unsigned char* encrypted_master_key, size_t keysize,
1345 unsigned char* decrypted_master_key, kdf_func kdf,
1346 void* kdf_params, unsigned char** intermediate_key,
1347 size_t* intermediate_key_size) {
1348 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1349 EVP_CIPHER_CTX d_ctx;
1350 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001351
Paul Crowley14c8c072018-09-18 13:30:21 -07001352 /* Turn the password into an intermediate key and IV that can decrypt the
1353 master key */
1354 if (kdf(passwd, salt, ikey, kdf_params)) {
1355 SLOGE("kdf failed");
1356 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001357 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001358
Paul Crowley14c8c072018-09-18 13:30:21 -07001359 /* Initialize the decryption engine */
1360 EVP_CIPHER_CTX_init(&d_ctx);
1361 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1362 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1363 return -1;
1364 }
1365 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1366 /* Decrypt the master key */
1367 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1368 keysize)) {
1369 return -1;
1370 }
1371 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1372 return -1;
1373 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001374
Paul Crowley14c8c072018-09-18 13:30:21 -07001375 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1376 return -1;
1377 }
1378
1379 /* Copy intermediate key if needed by params */
1380 if (intermediate_key && intermediate_key_size) {
1381 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1382 if (*intermediate_key) {
1383 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1384 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1385 }
1386 }
1387
1388 EVP_CIPHER_CTX_cleanup(&d_ctx);
1389
1390 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391}
1392
Paul Crowley14c8c072018-09-18 13:30:21 -07001393static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001394 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001395 *kdf = scrypt_keymaster;
1396 *kdf_params = ftr;
1397 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001398 *kdf = scrypt;
1399 *kdf_params = ftr;
1400 } else {
1401 *kdf = pbkdf2;
1402 *kdf_params = NULL;
1403 }
1404}
1405
Paul Crowley14c8c072018-09-18 13:30:21 -07001406static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1407 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1408 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001409 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001410 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001411 int ret;
1412
1413 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001414 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1415 decrypted_master_key, kdf, kdf_params, intermediate_key,
1416 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001417 if (ret != 0) {
1418 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001419 }
1420
1421 return ret;
1422}
1423
Paul Crowley14c8c072018-09-18 13:30:21 -07001424static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1425 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001426 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001427
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001428 /* Get some random bits for a key and salt */
1429 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1430 return -1;
1431 }
1432 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1433 return -1;
1434 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001435
1436 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001437 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001438}
1439
Paul Crowley14c8c072018-09-18 13:30:21 -07001440int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001441 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001442#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001443
1444 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001445 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001446 if (umount(mountpoint) == 0) {
1447 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001448 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001449
1450 if (errno == EINVAL) {
1451 /* EINVAL is returned if the directory is not a mountpoint,
1452 * i.e. there is no filesystem mounted there. So just get out.
1453 */
1454 break;
1455 }
1456
1457 err = errno;
1458
1459 /* If allowed, be increasingly aggressive before the last two retries */
1460 if (kill) {
1461 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1462 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001463 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001464 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1465 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001466 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001467 }
1468 }
1469
1470 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001471 }
1472
1473 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001474 SLOGD("unmounting %s succeeded\n", mountpoint);
1475 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001476 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001477 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1478 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1479 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001480 }
1481
1482 return rc;
1483}
1484
Paul Crowley14c8c072018-09-18 13:30:21 -07001485static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001486 // NOTE: post_fs_data results in init calling back around to vold, so all
1487 // callers to this method must be async
1488
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001489 /* Do the prep of the /data filesystem */
1490 property_set("vold.post_fs_data_done", "0");
1491 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001492 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001493
Ken Sumrallc5872692013-05-14 15:26:31 -07001494 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001495 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001496 /* We timed out to prep /data in time. Continue wait. */
1497 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001498 }
Wei Wang42e38102017-06-07 10:46:12 -07001499 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001500}
1501
Paul Crowley14c8c072018-09-18 13:30:21 -07001502static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001503 // Mark the footer as bad
1504 struct crypt_mnt_ftr crypt_ftr;
1505 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1506 SLOGE("Failed to get crypto footer - panic");
1507 return;
1508 }
1509
1510 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1511 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1512 SLOGE("Failed to set crypto footer - panic");
1513 return;
1514 }
1515}
1516
Paul Crowley14c8c072018-09-18 13:30:21 -07001517static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001518 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001519 SLOGE("Failed to mount tmpfs on data - panic");
1520 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001521 }
1522
1523 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1524 SLOGE("Failed to trigger post fs data - panic");
1525 return;
1526 }
1527
1528 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1529 SLOGE("Failed to trigger restart min framework - panic");
1530 return;
1531 }
1532}
1533
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001534/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001535static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001536 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001537 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001538 static int restart_successful = 0;
1539
1540 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001541 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001542 SLOGE("Encrypted filesystem not validated, aborting");
1543 return -1;
1544 }
1545
1546 if (restart_successful) {
1547 SLOGE("System already restarted with encrypted disk, aborting");
1548 return -1;
1549 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001550
Paul Lawrencef4faa572014-01-29 13:31:03 -08001551 if (restart_main) {
1552 /* Here is where we shut down the framework. The init scripts
1553 * start all services in one of three classes: core, main or late_start.
1554 * On boot, we start core and main. Now, we stop main, but not core,
1555 * as core includes vold and a few other really important things that
1556 * we need to keep running. Once main has stopped, we should be able
1557 * to umount the tmpfs /data, then mount the encrypted /data.
1558 * We then restart the class main, and also the class late_start.
1559 * At the moment, I've only put a few things in late_start that I know
1560 * are not needed to bring up the framework, and that also cause problems
1561 * with unmounting the tmpfs /data, but I hope to add add more services
1562 * to the late_start class as we optimize this to decrease the delay
1563 * till the user is asked for the password to the filesystem.
1564 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001565
Paul Lawrencef4faa572014-01-29 13:31:03 -08001566 /* The init files are setup to stop the class main when vold.decrypt is
1567 * set to trigger_reset_main.
1568 */
1569 property_set("vold.decrypt", "trigger_reset_main");
1570 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571
Paul Lawrencef4faa572014-01-29 13:31:03 -08001572 /* Ugh, shutting down the framework is not synchronous, so until it
1573 * can be fixed, this horrible hack will wait a moment for it all to
1574 * shut down before proceeding. Without it, some devices cannot
1575 * restart the graphics services.
1576 */
1577 sleep(2);
1578 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001579
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001580 /* Now that the framework is shutdown, we should be able to umount()
1581 * the tmpfs filesystem, and mount the real one.
1582 */
1583
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001584 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1585 if (strlen(crypto_blkdev) == 0) {
1586 SLOGE("fs_crypto_blkdev not set\n");
1587 return -1;
1588 }
1589
Paul Crowley14c8c072018-09-18 13:30:21 -07001590 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001591 /* If ro.crypto.readonly is set to 1, mount the decrypted
1592 * filesystem readonly. This is used when /data is mounted by
1593 * recovery mode.
1594 */
1595 char ro_prop[PROPERTY_VALUE_MAX];
1596 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001597 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001598 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001599 if (rec) {
1600 rec->flags |= MS_RDONLY;
1601 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001602 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001603
Ken Sumralle5032c42012-04-01 23:58:44 -07001604 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001605 int retries = RETRY_MOUNT_ATTEMPTS;
1606 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001607
1608 /*
1609 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1610 * partitions in the fsck domain.
1611 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001612 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001613 SLOGE("Failed to setexeccon");
1614 return -1;
1615 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001616 bool needs_cp = android::vold::cp_needsCheckpoint();
1617 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1618 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001619 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1620 /* TODO: invoke something similar to
1621 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1622 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001623 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001624 if (--retries) {
1625 sleep(RETRY_MOUNT_DELAY_SECONDS);
1626 } else {
1627 /* Let's hope that a reboot clears away whatever is keeping
1628 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001629 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001630 }
1631 } else {
1632 SLOGE("Failed to mount decrypted data");
1633 cryptfs_set_corrupt();
1634 cryptfs_trigger_restart_min_framework();
1635 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001636 if (setexeccon(NULL)) {
1637 SLOGE("Failed to setexeccon");
1638 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001639 return -1;
1640 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001641 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001642 if (setexeccon(NULL)) {
1643 SLOGE("Failed to setexeccon");
1644 return -1;
1645 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001646
Ken Sumralle5032c42012-04-01 23:58:44 -07001647 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001648 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001649 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001650
1651 /* startup service classes main and late_start */
1652 property_set("vold.decrypt", "trigger_restart_framework");
1653 SLOGD("Just triggered restart_framework\n");
1654
1655 /* Give it a few moments to get started */
1656 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001657 }
1658
Ken Sumrall0cc16632011-01-18 20:32:26 -08001659 if (rc == 0) {
1660 restart_successful = 1;
1661 }
1662
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001663 return rc;
1664}
1665
Paul Crowley14c8c072018-09-18 13:30:21 -07001666int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001667 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001668 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001669 SLOGE("cryptfs_restart not valid for file encryption:");
1670 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001671 }
1672
Paul Lawrencef4faa572014-01-29 13:31:03 -08001673 /* Call internal implementation forcing a restart of main service group */
1674 return cryptfs_restart_internal(1);
1675}
1676
Paul Crowley14c8c072018-09-18 13:30:21 -07001677static int do_crypto_complete(const char* mount_point) {
1678 struct crypt_mnt_ftr crypt_ftr;
1679 char encrypted_state[PROPERTY_VALUE_MAX];
1680 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001681
Paul Crowley14c8c072018-09-18 13:30:21 -07001682 property_get("ro.crypto.state", encrypted_state, "");
1683 if (strcmp(encrypted_state, "encrypted")) {
1684 SLOGE("not running with encryption, aborting");
1685 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001686 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001687
Paul Crowley14c8c072018-09-18 13:30:21 -07001688 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001689 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001690 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1691 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001692
Paul Crowley14c8c072018-09-18 13:30:21 -07001693 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1694 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001695
Paul Crowley14c8c072018-09-18 13:30:21 -07001696 /*
1697 * Only report this error if key_loc is a file and it exists.
1698 * If the device was never encrypted, and /data is not mountable for
1699 * some reason, returning 1 should prevent the UI from presenting the
1700 * a "enter password" screen, or worse, a "press button to wipe the
1701 * device" screen.
1702 */
1703 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1704 SLOGE("master key file does not exist, aborting");
1705 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1706 } else {
1707 SLOGE("Error getting crypt footer and key\n");
1708 return CRYPTO_COMPLETE_BAD_METADATA;
1709 }
1710 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001711
Paul Crowley14c8c072018-09-18 13:30:21 -07001712 // Test for possible error flags
1713 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1714 SLOGE("Encryption process is partway completed\n");
1715 return CRYPTO_COMPLETE_PARTIAL;
1716 }
1717
1718 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1719 SLOGE("Encryption process was interrupted but cannot continue\n");
1720 return CRYPTO_COMPLETE_INCONSISTENT;
1721 }
1722
1723 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1724 SLOGE("Encryption is successful but data is corrupt\n");
1725 return CRYPTO_COMPLETE_CORRUPT;
1726 }
1727
1728 /* We passed the test! We shall diminish, and return to the west */
1729 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001730}
1731
Paul Crowley14c8c072018-09-18 13:30:21 -07001732static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1733 const char* mount_point, const char* label) {
1734 unsigned char decrypted_master_key[MAX_KEY_LEN];
1735 char crypto_blkdev[MAXPATHLEN];
1736 char real_blkdev[MAXPATHLEN];
1737 char tmp_mount_point[64];
1738 unsigned int orig_failed_decrypt_count;
1739 int rc;
1740 int use_keymaster = 0;
1741 int upgrade = 0;
1742 unsigned char* intermediate_key = 0;
1743 size_t intermediate_key_size = 0;
1744 int N = 1 << crypt_ftr->N_factor;
1745 int r = 1 << crypt_ftr->r_factor;
1746 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001747
Paul Crowley14c8c072018-09-18 13:30:21 -07001748 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1749 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001750
Paul Crowley14c8c072018-09-18 13:30:21 -07001751 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1752 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1753 &intermediate_key_size)) {
1754 SLOGE("Failed to decrypt master key\n");
1755 rc = -1;
1756 goto errout;
1757 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001758 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001759
Paul Crowley14c8c072018-09-18 13:30:21 -07001760 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001761
Paul Crowley14c8c072018-09-18 13:30:21 -07001762 // Create crypto block device - all (non fatal) code paths
1763 // need it
1764 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
1765 0)) {
1766 SLOGE("Error creating decrypted block device\n");
1767 rc = -1;
1768 goto errout;
1769 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001770
Paul Crowley14c8c072018-09-18 13:30:21 -07001771 /* Work out if the problem is the password or the data */
1772 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001773
Paul Crowley14c8c072018-09-18 13:30:21 -07001774 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1775 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1776 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001777
Paul Crowley14c8c072018-09-18 13:30:21 -07001778 // Does the key match the crypto footer?
1779 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1780 sizeof(scrypted_intermediate_key)) == 0) {
1781 SLOGI("Password matches");
1782 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001783 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001784 /* Try mounting the file system anyway, just in case the problem's with
1785 * the footer, not the key. */
1786 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1787 mkdir(tmp_mount_point, 0755);
1788 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1789 SLOGE("Error temp mounting decrypted block device\n");
1790 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001791
Paul Crowley14c8c072018-09-18 13:30:21 -07001792 rc = ++crypt_ftr->failed_decrypt_count;
1793 put_crypt_ftr_and_key(crypt_ftr);
1794 } else {
1795 /* Success! */
1796 SLOGI("Password did not match but decrypted drive mounted - continue");
1797 umount(tmp_mount_point);
1798 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001799 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001800 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001801
Paul Crowley14c8c072018-09-18 13:30:21 -07001802 if (rc == 0) {
1803 crypt_ftr->failed_decrypt_count = 0;
1804 if (orig_failed_decrypt_count != 0) {
1805 put_crypt_ftr_and_key(crypt_ftr);
1806 }
1807
1808 /* Save the name of the crypto block device
1809 * so we can mount it when restarting the framework. */
1810 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1811
1812 /* Also save a the master key so we can reencrypted the key
1813 * the key when we want to change the password on it. */
1814 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1815 saved_mount_point = strdup(mount_point);
1816 master_key_saved = 1;
1817 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1818 rc = 0;
1819
1820 // Upgrade if we're not using the latest KDF.
1821 use_keymaster = keymaster_check_compatibility();
1822 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1823 // Don't allow downgrade
1824 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1825 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1826 upgrade = 1;
1827 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1828 crypt_ftr->kdf_type = KDF_SCRYPT;
1829 upgrade = 1;
1830 }
1831
1832 if (upgrade) {
1833 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1834 crypt_ftr->master_key, crypt_ftr);
1835 if (!rc) {
1836 rc = put_crypt_ftr_and_key(crypt_ftr);
1837 }
1838 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1839
1840 // Do not fail even if upgrade failed - machine is bootable
1841 // Note that if this code is ever hit, there is a *serious* problem
1842 // since KDFs should never fail. You *must* fix the kdf before
1843 // proceeding!
1844 if (rc) {
1845 SLOGW(
1846 "Upgrade failed with error %d,"
1847 " but continuing with previous state",
1848 rc);
1849 rc = 0;
1850 }
1851 }
1852 }
1853
1854errout:
1855 if (intermediate_key) {
1856 memset(intermediate_key, 0, intermediate_key_size);
1857 free(intermediate_key);
1858 }
1859 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001860}
1861
Ken Sumrall29d8da82011-05-18 17:20:07 -07001862/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001863 * Called by vold when it's asked to mount an encrypted external
1864 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001865 * as any metadata is been stored in a separate, small partition. We
1866 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001867 *
1868 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001869 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001870int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1871 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001872 uint64_t nr_sec = 0;
1873 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001874 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001875 return -1;
1876 }
1877
Jeff Sharkey9c484982015-03-31 10:35:33 -07001878 struct crypt_mnt_ftr ext_crypt_ftr;
1879 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1880 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001881 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001882 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001883 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001884 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001885 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001886 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1887 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001888
Paul Crowley385cb8c2018-03-29 13:27:23 -07001889 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001890}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001891
Jeff Sharkey9c484982015-03-31 10:35:33 -07001892/*
1893 * Called by vold when it's asked to unmount an encrypted external
1894 * storage volume.
1895 */
1896int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001897 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001898}
1899
Paul Crowley14c8c072018-09-18 13:30:21 -07001900int cryptfs_crypto_complete(void) {
1901 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001902}
1903
Paul Crowley14c8c072018-09-18 13:30:21 -07001904int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001905 char encrypted_state[PROPERTY_VALUE_MAX];
1906 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001907 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1908 SLOGE(
1909 "encrypted fs already validated or not running with encryption,"
1910 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001911 return -1;
1912 }
1913
1914 if (get_crypt_ftr_and_key(crypt_ftr)) {
1915 SLOGE("Error getting crypt footer and key");
1916 return -1;
1917 }
1918
1919 return 0;
1920}
1921
Paul Crowley14c8c072018-09-18 13:30:21 -07001922int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001923 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001924 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001925 SLOGE("cryptfs_check_passwd not valid for file encryption");
1926 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001927 }
1928
Paul Lawrencef4faa572014-01-29 13:31:03 -08001929 struct crypt_mnt_ftr crypt_ftr;
1930 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001931
Paul Lawrencef4faa572014-01-29 13:31:03 -08001932 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001933 if (rc) {
1934 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001935 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001936 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001937
Paul Crowley14c8c072018-09-18 13:30:21 -07001938 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001939 if (rc) {
1940 SLOGE("Password did not match");
1941 return rc;
1942 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001943
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001944 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1945 // Here we have a default actual password but a real password
1946 // we must test against the scrypted value
1947 // First, we must delete the crypto block device that
1948 // test_mount_encrypted_fs leaves behind as a side effect
1949 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001950 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1951 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001952 if (rc) {
1953 SLOGE("Default password did not match on reboot encryption");
1954 return rc;
1955 }
1956
1957 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1958 put_crypt_ftr_and_key(&crypt_ftr);
1959 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1960 if (rc) {
1961 SLOGE("Could not change password on reboot encryption");
1962 return rc;
1963 }
1964 }
1965
1966 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001967 cryptfs_clear_password();
1968 password = strdup(passwd);
1969 struct timespec now;
1970 clock_gettime(CLOCK_BOOTTIME, &now);
1971 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001972 }
1973
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001974 return rc;
1975}
1976
Paul Crowley14c8c072018-09-18 13:30:21 -07001977int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001978 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001979 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001980 char encrypted_state[PROPERTY_VALUE_MAX];
1981 int rc;
1982
1983 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001984 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001985 SLOGE("device not encrypted, aborting");
1986 return -2;
1987 }
1988
1989 if (!master_key_saved) {
1990 SLOGE("encrypted fs not yet mounted, aborting");
1991 return -1;
1992 }
1993
1994 if (!saved_mount_point) {
1995 SLOGE("encrypted fs failed to save mount point, aborting");
1996 return -1;
1997 }
1998
Ken Sumrall160b4d62013-04-22 12:15:39 -07001999 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002000 SLOGE("Error getting crypt footer and key\n");
2001 return -1;
2002 }
2003
2004 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2005 /* If the device has no password, then just say the password is valid */
2006 rc = 0;
2007 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002008 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002009 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2010 /* They match, the password is correct */
2011 rc = 0;
2012 } else {
2013 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2014 sleep(1);
2015 rc = 1;
2016 }
2017 }
2018
2019 return rc;
2020}
2021
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002022/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002023 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002024 * Presumably, at a minimum, the caller will update the
2025 * filesystem size and crypto_type_name after calling this function.
2026 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002027static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002028 off64_t off;
2029
2030 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002031 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002032 ftr->major_version = CURRENT_MAJOR_VERSION;
2033 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002034 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002035 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002036
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002037 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002038 case 1:
2039 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2040 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002041
Paul Crowley14c8c072018-09-18 13:30:21 -07002042 case 0:
2043 ftr->kdf_type = KDF_SCRYPT;
2044 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002045
Paul Crowley14c8c072018-09-18 13:30:21 -07002046 default:
2047 SLOGE("keymaster_check_compatibility failed");
2048 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002049 }
2050
Kenny Rootc4c70f12013-06-14 12:11:38 -07002051 get_device_scrypt_params(ftr);
2052
Ken Sumrall160b4d62013-04-22 12:15:39 -07002053 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2054 if (get_crypt_ftr_info(NULL, &off) == 0) {
2055 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002056 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002057 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002058
2059 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002060}
2061
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002062#define FRAMEWORK_BOOT_WAIT 60
2063
Paul Crowley14c8c072018-09-18 13:30:21 -07002064static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2065 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002066 if (fd == -1) {
2067 SLOGE("Error opening file %s", filename);
2068 return -1;
2069 }
2070
2071 char block[CRYPT_INPLACE_BUFSIZE];
2072 memset(block, 0, sizeof(block));
2073 if (unix_read(fd, block, sizeof(block)) < 0) {
2074 SLOGE("Error reading file %s", filename);
2075 close(fd);
2076 return -1;
2077 }
2078
2079 close(fd);
2080
2081 SHA256_CTX c;
2082 SHA256_Init(&c);
2083 SHA256_Update(&c, block, sizeof(block));
2084 SHA256_Final(buf, &c);
2085
2086 return 0;
2087}
2088
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002089static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2090 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002091 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002092 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002093
Paul Lawrence87999172014-02-20 12:21:31 -08002094 /* The size of the userdata partition, and add in the vold volumes below */
2095 tot_encryption_size = crypt_ftr->fs_size;
2096
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002097 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002098 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002099
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002100 if (rc == ENABLE_INPLACE_ERR_DEV) {
2101 /* Hack for b/17898962 */
2102 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2103 cryptfs_reboot(RebootType::reboot);
2104 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002105
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002106 if (!rc) {
2107 crypt_ftr->encrypted_upto = cur_encryption_done;
2108 }
Paul Lawrence87999172014-02-20 12:21:31 -08002109
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002110 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2111 /* The inplace routine never actually sets the progress to 100% due
2112 * to the round down nature of integer division, so set it here */
2113 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002114 }
2115
2116 return rc;
2117}
2118
Paul Crowleyb64933a2017-10-31 08:25:55 -07002119static int vold_unmountAll(void) {
2120 VolumeManager* vm = VolumeManager::Instance();
2121 return vm->unmountAll();
2122}
2123
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002124int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002125 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002126 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002127 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002128 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002129 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002130 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002131 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002132 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002133 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002134 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002135 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002136 bool onlyCreateHeader = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002137
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002138 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002139 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2140 /* An encryption was underway and was interrupted */
2141 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2142 crypt_ftr.encrypted_upto = 0;
2143 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002144
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002145 /* At this point, we are in an inconsistent state. Until we successfully
2146 complete encryption, a reboot will leave us broken. So mark the
2147 encryption failed in case that happens.
2148 On successfully completing encryption, remove this flag */
2149 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002150
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002151 put_crypt_ftr_and_key(&crypt_ftr);
2152 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2153 if (!check_ftr_sha(&crypt_ftr)) {
2154 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2155 put_crypt_ftr_and_key(&crypt_ftr);
2156 goto error_unencrypted;
2157 }
2158
2159 /* Doing a reboot-encryption*/
2160 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2161 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2162 rebootEncryption = true;
2163 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002164 } else {
2165 // We don't want to accidentally reference invalid data.
2166 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002167 }
2168
2169 property_get("ro.crypto.state", encrypted_state, "");
2170 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2171 SLOGE("Device is already running encrypted, aborting");
2172 goto error_unencrypted;
2173 }
2174
2175 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002176 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2177 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002178
Ken Sumrall3ed82362011-01-28 23:31:16 -08002179 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002180 uint64_t nr_sec;
2181 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002182 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2183 goto error_unencrypted;
2184 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002185
2186 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002187 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002188 uint64_t fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002189 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002190 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002191
Paul Lawrence87999172014-02-20 12:21:31 -08002192 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002193
2194 if (fs_size_sec > max_fs_size_sec) {
2195 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2196 goto error_unencrypted;
2197 }
2198 }
2199
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002200 /* Get a wakelock as this may take a while, and we don't want the
2201 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2202 * wants to keep the screen on, it can grab a full wakelock.
2203 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002204 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002205 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2206
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002207 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002208 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002209 */
2210 property_set("vold.decrypt", "trigger_shutdown_framework");
2211 SLOGD("Just asked init to shut down class main\n");
2212
Jeff Sharkey9c484982015-03-31 10:35:33 -07002213 /* Ask vold to unmount all devices that it manages */
2214 if (vold_unmountAll()) {
2215 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002216 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002217
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002218 /* no_ui means we are being called from init, not settings.
2219 Now we always reboot from settings, so !no_ui means reboot
2220 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002221 if (!no_ui) {
2222 /* Try fallback, which is to reboot and try there */
2223 onlyCreateHeader = true;
2224 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2225 if (breadcrumb == 0) {
2226 SLOGE("Failed to create breadcrumb file");
2227 goto error_shutting_down;
2228 }
2229 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002230 }
2231
2232 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002233 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002234 /* Now that /data is unmounted, we need to mount a tmpfs
2235 * /data, set a property saying we're doing inplace encryption,
2236 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002237 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002238 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002239 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002240 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002241 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002242 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002243
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002244 /* restart the framework. */
2245 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002246 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002247
Ken Sumrall92736ef2012-10-17 20:57:14 -07002248 /* Ugh, shutting down the framework is not synchronous, so until it
2249 * can be fixed, this horrible hack will wait a moment for it all to
2250 * shut down before proceeding. Without it, some devices cannot
2251 * restart the graphics services.
2252 */
2253 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002254 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002255
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002256 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002257 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002258 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002259 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2260 goto error_shutting_down;
2261 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002262
Paul Lawrence87999172014-02-20 12:21:31 -08002263 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002264 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002265 } else {
2266 crypt_ftr.fs_size = nr_sec;
2267 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002268 /* At this point, we are in an inconsistent state. Until we successfully
2269 complete encryption, a reboot will leave us broken. So mark the
2270 encryption failed in case that happens.
2271 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002272 if (onlyCreateHeader) {
2273 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2274 } else {
2275 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2276 }
Paul Lawrence87999172014-02-20 12:21:31 -08002277 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002278 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2279 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002280
Paul Lawrence87999172014-02-20 12:21:31 -08002281 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002282 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2283 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002284 SLOGE("Cannot create encrypted master key\n");
2285 goto error_shutting_down;
2286 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002287
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002288 /* Replace scrypted intermediate key if we are preparing for a reboot */
2289 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002290 unsigned char fake_master_key[MAX_KEY_LEN];
2291 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002292 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002293 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2294 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002295 }
2296
Paul Lawrence87999172014-02-20 12:21:31 -08002297 /* Write the key to the end of the partition */
2298 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002299
Paul Lawrence87999172014-02-20 12:21:31 -08002300 /* If any persistent data has been remembered, save it.
2301 * If none, create a valid empty table and save that.
2302 */
2303 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002304 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2305 if (pdata) {
2306 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2307 persist_data = pdata;
2308 }
Paul Lawrence87999172014-02-20 12:21:31 -08002309 }
2310 if (persist_data) {
2311 save_persistent_data();
2312 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002313 }
2314
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002315 if (onlyCreateHeader) {
2316 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002317 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002318 }
2319
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002320 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002321 /* startup service classes main and late_start */
2322 property_set("vold.decrypt", "trigger_restart_min_framework");
2323 SLOGD("Just triggered restart_min_framework\n");
2324
2325 /* OK, the framework is restarted and will soon be showing a
2326 * progress bar. Time to setup an encrypted mapping, and
2327 * either write a new filesystem, or encrypt in place updating
2328 * the progress bar as we work.
2329 */
2330 }
2331
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002332 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002333 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002334 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002335
Paul Lawrence87999172014-02-20 12:21:31 -08002336 /* If we are continuing, check checksums match */
2337 rc = 0;
2338 if (previously_encrypted_upto) {
2339 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2340 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002341
Paul Crowley14c8c072018-09-18 13:30:21 -07002342 if (!rc &&
2343 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002344 SLOGE("Checksums do not match - trigger wipe");
2345 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002346 }
2347 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002348
Paul Lawrence87999172014-02-20 12:21:31 -08002349 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002350 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002351 previously_encrypted_upto);
2352 }
2353
2354 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002355 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002356 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002357 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002358 SLOGE("Error calculating checksum for continuing encryption");
2359 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002360 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002361 }
2362
2363 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002364 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002365
Paul Crowley14c8c072018-09-18 13:30:21 -07002366 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002367 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002368 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002369
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002370 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002371 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2372 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002373 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002374 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002375
Paul Lawrence6bfed202014-07-28 12:47:22 -07002376 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002377
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002378 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2379 char value[PROPERTY_VALUE_MAX];
2380 property_get("ro.crypto.state", value, "");
2381 if (!strcmp(value, "")) {
2382 /* default encryption - continue first boot sequence */
2383 property_set("ro.crypto.state", "encrypted");
2384 property_set("ro.crypto.type", "block");
2385 release_wake_lock(lockid);
2386 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2387 // Bring up cryptkeeper that will check the password and set it
2388 property_set("vold.decrypt", "trigger_shutdown_framework");
2389 sleep(2);
2390 property_set("vold.encrypt_progress", "");
2391 cryptfs_trigger_restart_min_framework();
2392 } else {
2393 cryptfs_check_passwd(DEFAULT_PASSWORD);
2394 cryptfs_restart_internal(1);
2395 }
2396 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002397 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002398 sleep(2); /* Give the UI a chance to show 100% progress */
2399 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002400 }
Paul Lawrence87999172014-02-20 12:21:31 -08002401 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002402 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002403 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002404 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002405 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002406 char value[PROPERTY_VALUE_MAX];
2407
Ken Sumrall319369a2012-06-27 16:30:18 -07002408 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002409 if (!strcmp(value, "1")) {
2410 /* wipe data if encryption failed */
2411 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002412 std::string err;
2413 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002414 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002415 if (!write_bootloader_message(options, &err)) {
2416 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002417 }
Josh Gaofec44372017-08-28 13:22:55 -07002418 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002419 } else {
2420 /* set property to trigger dialog */
2421 property_set("vold.encrypt_progress", "error_partially_encrypted");
2422 release_wake_lock(lockid);
2423 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002424 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002425 }
2426
Ken Sumrall3ed82362011-01-28 23:31:16 -08002427 /* hrm, the encrypt step claims success, but the reboot failed.
2428 * This should not happen.
2429 * Set the property and return. Hope the framework can deal with it.
2430 */
2431 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002432 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002433 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002434
2435error_unencrypted:
2436 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002437 if (lockid[0]) {
2438 release_wake_lock(lockid);
2439 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002440 return -1;
2441
2442error_shutting_down:
2443 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2444 * but the framework is stopped and not restarted to show the error, so it's up to
2445 * vold to restart the system.
2446 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002447 SLOGE(
2448 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2449 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002450 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002451
2452 /* shouldn't get here */
2453 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002454 if (lockid[0]) {
2455 release_wake_lock(lockid);
2456 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002457 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002458}
2459
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002460int cryptfs_enable(int type, const char* passwd, int no_ui) {
2461 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002462}
2463
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002464int cryptfs_enable_default(int no_ui) {
2465 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002466}
2467
Paul Crowley14c8c072018-09-18 13:30:21 -07002468int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002469 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002470 SLOGE("cryptfs_changepw not valid for file encryption");
2471 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002472 }
2473
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002474 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002475 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002476
2477 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002478 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002479 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002480 return -1;
2481 }
2482
Paul Lawrencef4faa572014-01-29 13:31:03 -08002483 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2484 SLOGE("Invalid crypt_type %d", crypt_type);
2485 return -1;
2486 }
2487
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002488 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002489 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002490 SLOGE("Error getting crypt footer and key");
2491 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002492 }
2493
Paul Lawrencef4faa572014-01-29 13:31:03 -08002494 crypt_ftr.crypt_type = crypt_type;
2495
Paul Crowley14c8c072018-09-18 13:30:21 -07002496 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2497 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002498 if (rc) {
2499 SLOGE("Encrypt master key failed: %d", rc);
2500 return -1;
2501 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002502 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002503 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002504
2505 return 0;
2506}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002507
Rubin Xu85c01f92014-10-13 12:49:54 +01002508static unsigned int persist_get_max_entries(int encrypted) {
2509 struct crypt_mnt_ftr crypt_ftr;
2510 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002511
2512 /* If encrypted, use the values from the crypt_ftr, otherwise
2513 * use the values for the current spec.
2514 */
2515 if (encrypted) {
2516 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002517 /* Something is wrong, assume no space for entries */
2518 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002519 }
2520 dsize = crypt_ftr.persist_data_size;
2521 } else {
2522 dsize = CRYPT_PERSIST_DATA_SIZE;
2523 }
2524
Rubin Xuf83cc612018-10-09 16:13:38 +01002525 if (dsize > sizeof(struct crypt_persist_data)) {
2526 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2527 } else {
2528 return 0;
2529 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002530}
2531
Paul Crowley14c8c072018-09-18 13:30:21 -07002532static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002533 unsigned int i;
2534
2535 if (persist_data == NULL) {
2536 return -1;
2537 }
2538 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2539 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2540 /* We found it! */
2541 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2542 return 0;
2543 }
2544 }
2545
2546 return -1;
2547}
2548
Paul Crowley14c8c072018-09-18 13:30:21 -07002549static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002550 unsigned int i;
2551 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002552 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002553
2554 if (persist_data == NULL) {
2555 return -1;
2556 }
2557
Rubin Xu85c01f92014-10-13 12:49:54 +01002558 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002559
2560 num = persist_data->persist_valid_entries;
2561
2562 for (i = 0; i < num; i++) {
2563 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2564 /* We found an existing entry, update it! */
2565 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2566 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2567 return 0;
2568 }
2569 }
2570
2571 /* We didn't find it, add it to the end, if there is room */
2572 if (persist_data->persist_valid_entries < max_persistent_entries) {
2573 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2574 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2575 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2576 persist_data->persist_valid_entries++;
2577 return 0;
2578 }
2579
2580 return -1;
2581}
2582
Rubin Xu85c01f92014-10-13 12:49:54 +01002583/**
2584 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2585 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2586 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002587int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002588 std::string key_ = key;
2589 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002590
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002591 std::string parsed_field;
2592 unsigned parsed_index;
2593
2594 std::string::size_type split = key_.find_last_of('_');
2595 if (split == std::string::npos) {
2596 parsed_field = key_;
2597 parsed_index = 0;
2598 } else {
2599 parsed_field = key_.substr(0, split);
2600 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002601 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002602
2603 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002604}
2605
2606/*
2607 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2608 * remaining entries starting from index will be deleted.
2609 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2610 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2611 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2612 *
2613 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002614static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002615 unsigned int i;
2616 unsigned int j;
2617 unsigned int num;
2618
2619 if (persist_data == NULL) {
2620 return PERSIST_DEL_KEY_ERROR_OTHER;
2621 }
2622
2623 num = persist_data->persist_valid_entries;
2624
Paul Crowley14c8c072018-09-18 13:30:21 -07002625 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002626 // Filter out to-be-deleted entries in place.
2627 for (i = 0; i < num; i++) {
2628 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2629 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2630 j++;
2631 }
2632 }
2633
2634 if (j < num) {
2635 persist_data->persist_valid_entries = j;
2636 // Zeroise the remaining entries
2637 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2638 return PERSIST_DEL_KEY_OK;
2639 } else {
2640 // Did not find an entry matching the given fieldname
2641 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2642 }
2643}
2644
Paul Crowley14c8c072018-09-18 13:30:21 -07002645static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002646 unsigned int i;
2647 unsigned int count;
2648
2649 if (persist_data == NULL) {
2650 return -1;
2651 }
2652
2653 count = 0;
2654 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2655 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2656 count++;
2657 }
2658 }
2659
2660 return count;
2661}
2662
Ken Sumrall160b4d62013-04-22 12:15:39 -07002663/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002664int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002665 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002666 SLOGE("Cannot get field when file encrypted");
2667 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002668 }
2669
Ken Sumrall160b4d62013-04-22 12:15:39 -07002670 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002671 /* CRYPTO_GETFIELD_OK is success,
2672 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2673 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2674 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002675 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002676 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2677 int i;
2678 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002679
2680 if (persist_data == NULL) {
2681 load_persistent_data();
2682 if (persist_data == NULL) {
2683 SLOGE("Getfield error, cannot load persistent data");
2684 goto out;
2685 }
2686 }
2687
Rubin Xu85c01f92014-10-13 12:49:54 +01002688 // Read value from persistent entries. If the original value is split into multiple entries,
2689 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002690 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002691 // 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 -07002692 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002693 // value too small
2694 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2695 goto out;
2696 }
2697 rc = CRYPTO_GETFIELD_OK;
2698
2699 for (i = 1; /* break explicitly */; i++) {
2700 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002701 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002702 // If the fieldname is very long, we stop as soon as it begins to overflow the
2703 // maximum field length. At this point we have in fact fully read out the original
2704 // value because cryptfs_setfield would not allow fields with longer names to be
2705 // written in the first place.
2706 break;
2707 }
2708 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002709 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2710 // value too small.
2711 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2712 goto out;
2713 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002714 } else {
2715 // Exhaust all entries.
2716 break;
2717 }
2718 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002719 } else {
2720 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002721 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002722 }
2723
2724out:
2725 return rc;
2726}
2727
2728/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002729int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002730 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002731 SLOGE("Cannot set field when file encrypted");
2732 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002733 }
2734
Ken Sumrall160b4d62013-04-22 12:15:39 -07002735 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002736 /* 0 is success, negative values are error */
2737 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002738 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002739 unsigned int field_id;
2740 char temp_field[PROPERTY_KEY_MAX];
2741 unsigned int num_entries;
2742 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002743
2744 if (persist_data == NULL) {
2745 load_persistent_data();
2746 if (persist_data == NULL) {
2747 SLOGE("Setfield error, cannot load persistent data");
2748 goto out;
2749 }
2750 }
2751
2752 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002753 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002754 encrypted = 1;
2755 }
2756
Rubin Xu85c01f92014-10-13 12:49:54 +01002757 // Compute the number of entries required to store value, each entry can store up to
2758 // (PROPERTY_VALUE_MAX - 1) chars
2759 if (strlen(value) == 0) {
2760 // Empty value also needs one entry to store.
2761 num_entries = 1;
2762 } else {
2763 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2764 }
2765
2766 max_keylen = strlen(fieldname);
2767 if (num_entries > 1) {
2768 // Need an extra "_%d" suffix.
2769 max_keylen += 1 + log10(num_entries);
2770 }
2771 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2772 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002773 goto out;
2774 }
2775
Rubin Xu85c01f92014-10-13 12:49:54 +01002776 // Make sure we have enough space to write the new value
2777 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2778 persist_get_max_entries(encrypted)) {
2779 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2780 goto out;
2781 }
2782
2783 // Now that we know persist_data has enough space for value, let's delete the old field first
2784 // to make up space.
2785 persist_del_keys(fieldname, 0);
2786
2787 if (persist_set_key(fieldname, value, encrypted)) {
2788 // fail to set key, should not happen as we have already checked the available space
2789 SLOGE("persist_set_key() error during setfield()");
2790 goto out;
2791 }
2792
2793 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002794 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002795
2796 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2797 // fail to set key, should not happen as we have already checked the available space.
2798 SLOGE("persist_set_key() error during setfield()");
2799 goto out;
2800 }
2801 }
2802
Ken Sumrall160b4d62013-04-22 12:15:39 -07002803 /* If we are running encrypted, save the persistent data now */
2804 if (encrypted) {
2805 if (save_persistent_data()) {
2806 SLOGE("Setfield error, cannot save persistent data");
2807 goto out;
2808 }
2809 }
2810
Rubin Xu85c01f92014-10-13 12:49:54 +01002811 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002812
2813out:
2814 return rc;
2815}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002816
2817/* Checks userdata. Attempt to mount the volume if default-
2818 * encrypted.
2819 * On success trigger next init phase and return 0.
2820 * Currently do not handle failure - see TODO below.
2821 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002822int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002823 int crypt_type = cryptfs_get_password_type();
2824 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2825 SLOGE("Bad crypt type - error");
2826 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002827 SLOGD(
2828 "Password is not default - "
2829 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002830 property_set("vold.decrypt", "trigger_restart_min_framework");
2831 return 0;
2832 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2833 SLOGD("Password is default - restarting filesystem");
2834 cryptfs_restart_internal(0);
2835 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002836 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002837 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002838 }
2839
Paul Lawrence6bfed202014-07-28 12:47:22 -07002840 /** Corrupt. Allow us to boot into framework, which will detect bad
2841 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002842 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002843 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002844 return 0;
2845}
2846
2847/* Returns type of the password, default, pattern, pin or password.
2848 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002849int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002850 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002851 SLOGE("cryptfs_get_password_type not valid for file encryption");
2852 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002853 }
2854
Paul Lawrencef4faa572014-01-29 13:31:03 -08002855 struct crypt_mnt_ftr crypt_ftr;
2856
2857 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2858 SLOGE("Error getting crypt footer and key\n");
2859 return -1;
2860 }
2861
Paul Lawrence6bfed202014-07-28 12:47:22 -07002862 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2863 return -1;
2864 }
2865
Paul Lawrencef4faa572014-01-29 13:31:03 -08002866 return crypt_ftr.crypt_type;
2867}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002868
Paul Crowley14c8c072018-09-18 13:30:21 -07002869const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002870 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002871 SLOGE("cryptfs_get_password not valid for file encryption");
2872 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002873 }
2874
Paul Lawrence399317e2014-03-10 13:20:50 -07002875 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002876 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002877 if (now.tv_sec < password_expiry_time) {
2878 return password;
2879 } else {
2880 cryptfs_clear_password();
2881 return 0;
2882 }
2883}
2884
Paul Crowley14c8c072018-09-18 13:30:21 -07002885void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002886 if (password) {
2887 size_t len = strlen(password);
2888 memset(password, 0, len);
2889 free(password);
2890 password = 0;
2891 password_expiry_time = 0;
2892 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002893}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002894
Paul Crowley14c8c072018-09-18 13:30:21 -07002895int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002896 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07002897 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07002898}