blob: ae25e9adbe351f8d646a77fa693790a1b00e4ff2 [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 Rosenberg4f684712018-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 Crowley298fa322018-10-30 15:59:24 -070033#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080034#include "VoldUtil.h"
35#include "VolumeManager.h"
36#include "secontext.h"
37
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <android-base/properties.h>
Logan Chiend557d762018-05-02 11:36:45 +080039#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080040#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070042#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080043#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070045#include <fscrypt/fscrypt.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080046#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080047#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080048#include <logwrap/logwrap.h>
49#include <openssl/evp.h>
50#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080051#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080052
53#include <ctype.h>
54#include <errno.h>
55#include <fcntl.h>
56#include <inttypes.h>
57#include <libgen.h>
58#include <linux/dm-ioctl.h>
59#include <linux/kdev_t.h>
60#include <math.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <string.h>
64#include <sys/ioctl.h>
65#include <sys/mount.h>
66#include <sys/param.h>
67#include <sys/stat.h>
68#include <sys/types.h>
69#include <sys/wait.h>
70#include <time.h>
71#include <unistd.h>
72
Wei Wang4375f1b2017-02-24 17:43:01 -080073extern "C" {
74#include <crypto_scrypt.h>
75}
Mark Salyzyn3e971272014-01-21 13:27:04 -080076
Paul Crowley298fa322018-10-30 15:59:24 -070077using namespace std::chrono_literals;
78
Mark Salyzyn5eecc442014-02-12 14:16:14 -080079#define UNUSED __attribute__((unused))
80
Ken Sumrall8f869aa2010-12-03 03:47:09 -080081#define DM_CRYPT_BUF_SIZE 4096
82
Jason parks70a4b3f2011-01-28 10:10:47 -060083#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080084
85constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
86constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070087constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080088
89// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070090static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060091
Paul Crowley14c8c072018-09-18 13:30:21 -070092#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070093
Paul Lawrence3bd36d52015-06-09 13:37:44 -070094#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080095
Paul Lawrence3d99eba2015-11-20 07:07:19 -080096#define CRYPTO_BLOCK_DEVICE "userdata"
97
98#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
99
Ken Sumrall29d8da82011-05-18 17:20:07 -0700100#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700101#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700102
Ken Sumralle919efe2012-09-29 17:07:41 -0700103#define TABLE_LOAD_RETRIES 10
104
Shawn Willden47ba10d2014-09-03 17:07:06 -0600105#define RSA_KEY_SIZE 2048
106#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
107#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600108#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700109
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700110#define RETRY_MOUNT_ATTEMPTS 10
111#define RETRY_MOUNT_DELAY_SECONDS 1
112
Paul Crowley5afbc622017-11-27 09:42:17 -0800113#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
114
Paul Crowley73473332017-11-21 15:43:51 -0800115static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
116
Greg Kaiser59ad0182018-02-16 13:01:36 -0800117static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700118static char* saved_mount_point;
119static int master_key_saved = 0;
120static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800121
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700122/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700123static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000124 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700125}
126
127/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700128static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800129 if (ftr->keymaster_blob_size) {
130 SLOGI("Already have key");
131 return 0;
132 }
133
Paul Crowley14c8c072018-09-18 13:30:21 -0700134 int rc = keymaster_create_key_for_cryptfs_scrypt(
135 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
136 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000137 if (rc) {
138 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800139 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000140 ftr->keymaster_blob_size = 0;
141 }
142 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700143 return -1;
144 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000145 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700146}
147
Shawn Willdene17a9c42014-09-08 13:04:08 -0600148/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700149static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
150 const size_t object_size, unsigned char** signature,
151 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600152 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600153 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600154 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600155
Shawn Willdene17a9c42014-09-08 13:04:08 -0600156 // To sign a message with RSA, the message must satisfy two
157 // constraints:
158 //
159 // 1. The message, when interpreted as a big-endian numeric value, must
160 // be strictly less than the public modulus of the RSA key. Note
161 // that because the most significant bit of the public modulus is
162 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
163 // key), an n-bit message with most significant bit 0 always
164 // satisfies this requirement.
165 //
166 // 2. The message must have the same length in bits as the public
167 // modulus of the RSA key. This requirement isn't mathematically
168 // necessary, but is necessary to ensure consistency in
169 // implementations.
170 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600171 case KDF_SCRYPT_KEYMASTER:
172 // This ensures the most significant byte of the signed message
173 // is zero. We could have zero-padded to the left instead, but
174 // this approach is slightly more robust against changes in
175 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600176 // so) because we really should be using a proper deterministic
177 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800178 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600179 SLOGI("Signing safely-padded object");
180 break;
181 default:
182 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000183 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600184 }
Paul Crowley73473332017-11-21 15:43:51 -0800185 for (;;) {
186 auto result = keymaster_sign_object_for_cryptfs_scrypt(
187 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
188 to_sign_size, signature, signature_size);
189 switch (result) {
190 case KeymasterSignResult::ok:
191 return 0;
192 case KeymasterSignResult::upgrade:
193 break;
194 default:
195 return -1;
196 }
197 SLOGD("Upgrading key");
198 if (keymaster_upgrade_key_for_cryptfs_scrypt(
199 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
200 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
201 &ftr->keymaster_blob_size) != 0) {
202 SLOGE("Failed to upgrade key");
203 return -1;
204 }
205 if (put_crypt_ftr_and_key(ftr) != 0) {
206 SLOGE("Failed to write upgraded key to disk");
207 }
208 SLOGD("Key upgraded successfully");
209 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600210}
211
Paul Lawrence399317e2014-03-10 13:20:50 -0700212/* Store password when userdata is successfully decrypted and mounted.
213 * Cleared by cryptfs_clear_password
214 *
215 * To avoid a double prompt at boot, we need to store the CryptKeeper
216 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
217 * Since the entire framework is torn down and rebuilt after encryption,
218 * we have to use a daemon or similar to store the password. Since vold
219 * is secured against IPC except from system processes, it seems a reasonable
220 * place to store this.
221 *
222 * password should be cleared once it has been used.
223 *
224 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800225 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700226static char* password = 0;
227static int password_expiry_time = 0;
228static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800229
Paul Crowley14c8c072018-09-18 13:30:21 -0700230enum class RebootType { reboot, recovery, shutdown };
231static void cryptfs_reboot(RebootType rt) {
232 switch (rt) {
233 case RebootType::reboot:
234 property_set(ANDROID_RB_PROPERTY, "reboot");
235 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800236
Paul Crowley14c8c072018-09-18 13:30:21 -0700237 case RebootType::recovery:
238 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
239 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800240
Paul Crowley14c8c072018-09-18 13:30:21 -0700241 case RebootType::shutdown:
242 property_set(ANDROID_RB_PROPERTY, "shutdown");
243 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700244 }
Paul Lawrence87999172014-02-20 12:21:31 -0800245
Ken Sumralladfba362013-06-04 16:37:52 -0700246 sleep(20);
247
248 /* Shouldn't get here, reboot should happen before sleep times out */
249 return;
250}
251
Paul Crowley14c8c072018-09-18 13:30:21 -0700252static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800253 memset(io, 0, dataSize);
254 io->data_size = dataSize;
255 io->data_start = sizeof(struct dm_ioctl);
256 io->version[0] = 4;
257 io->version[1] = 0;
258 io->version[2] = 0;
259 io->flags = flags;
260 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100261 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800262 }
263}
264
Greg Kaiser38723f22018-02-16 13:35:35 -0800265namespace {
266
267struct CryptoType;
268
269// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700270const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800271
272struct CryptoType {
273 // We should only be constructing CryptoTypes as part of
274 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
275 // which isn't pure or fully protected as a concession to being able to
276 // do it all at compile time. Add new CryptoTypes in
277 // supported_crypto_types[] below.
278 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
279 constexpr CryptoType set_keysize(uint32_t size) const {
280 return CryptoType(this->property_name, this->crypto_name, size);
281 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700282 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800283 return CryptoType(property, this->crypto_name, this->keysize);
284 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700285 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800286 return CryptoType(this->property_name, crypto, this->keysize);
287 }
288
Paul Crowley14c8c072018-09-18 13:30:21 -0700289 constexpr const char* get_property_name() const { return property_name; }
290 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800291 constexpr uint32_t get_keysize() const { return keysize; }
292
Paul Crowley14c8c072018-09-18 13:30:21 -0700293 private:
294 const char* property_name;
295 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800296 uint32_t keysize;
297
Paul Crowley14c8c072018-09-18 13:30:21 -0700298 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800299 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700300 friend const CryptoType& get_crypto_type();
301 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800302};
303
304// We only want to parse this read-only property once. But we need to wait
305// until the system is initialized before we can read it. So we use a static
306// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700307const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800308 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
309 return crypto_type;
310}
311
312constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700313 .set_property_name("AES-128-CBC")
314 .set_crypto_name("aes-cbc-essiv:sha256")
315 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800316
317constexpr CryptoType supported_crypto_types[] = {
318 default_crypto_type,
Greg Kaiser38723f22018-02-16 13:35:35 -0800319 // Add new CryptoTypes here. Order is not important.
320};
321
Greg Kaiser38723f22018-02-16 13:35:35 -0800322// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
323// We confirm all supported_crypto_types have a small enough keysize and
324// had both set_property_name() and set_crypto_name() called.
325
326template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700327constexpr size_t array_length(T (&)[N]) {
328 return N;
329}
Greg Kaiser38723f22018-02-16 13:35:35 -0800330
331constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
332 return (index >= array_length(supported_crypto_types));
333}
334
Paul Crowley14c8c072018-09-18 13:30:21 -0700335constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800336 return ((crypto_type.get_property_name() != nullptr) &&
337 (crypto_type.get_crypto_name() != nullptr) &&
338 (crypto_type.get_keysize() <= MAX_KEY_LEN));
339}
340
341// Note in C++11 that constexpr functions can only have a single line.
342// So our code is a bit convoluted (using recursion instead of a loop),
343// but it's asserting at compile time that all of our key lengths are valid.
344constexpr bool validateSupportedCryptoTypes(size_t index) {
345 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700346 (isValidCryptoType(supported_crypto_types[index]) &&
347 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800348}
349
350static_assert(validateSupportedCryptoTypes(0),
351 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
352 "incompletely constructed.");
353// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
354
Greg Kaiser38723f22018-02-16 13:35:35 -0800355// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700356const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800357 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
358 char paramstr[PROPERTY_VALUE_MAX];
359
Paul Crowley14c8c072018-09-18 13:30:21 -0700360 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
361 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800362 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
363 return ctype;
364 }
365 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700366 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
367 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800368 return default_crypto_type;
369}
370
371} // namespace
372
Kenny Rootc4c70f12013-06-14 12:11:38 -0700373/**
374 * Gets the default device scrypt parameters for key derivation time tuning.
375 * The parameters should lead to about one second derivation time for the
376 * given device.
377 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700378static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700379 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000380 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700381
Paul Crowley63c18d32016-02-10 14:02:47 +0000382 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
383 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
384 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
385 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700386 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000387 ftr->N_factor = Nf;
388 ftr->r_factor = rf;
389 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700390}
391
Greg Kaiser57f9af62018-02-16 13:13:58 -0800392uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800393 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800394}
395
Paul Crowley14c8c072018-09-18 13:30:21 -0700396const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800397 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800398}
399
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200400static uint64_t get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800401 int fd, block_size;
402 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200403 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800404
Paul Crowley14c8c072018-09-18 13:30:21 -0700405 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800406 SLOGE("Cannot open device to get filesystem size ");
407 return 0;
408 }
409
410 if (lseek64(fd, 1024, SEEK_SET) < 0) {
411 SLOGE("Cannot seek to superblock");
412 return 0;
413 }
414
415 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
416 SLOGE("Cannot read superblock");
417 return 0;
418 }
419
420 close(fd);
421
Daniel Rosenberge82df162014-08-15 22:19:23 +0000422 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
423 SLOGE("Not a valid ext4 superblock");
424 return 0;
425 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800426 block_size = 1024 << sb.s_log_block_size;
427 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200428 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800429
430 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200431 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800432}
433
Paul Crowley14c8c072018-09-18 13:30:21 -0700434static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
435 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200436 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700437 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700438 char key_loc[PROPERTY_VALUE_MAX];
439 char real_blkdev[PROPERTY_VALUE_MAX];
440 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700441
Paul Crowley14c8c072018-09-18 13:30:21 -0700442 if (!cached_data) {
443 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700444
Paul Crowley14c8c072018-09-18 13:30:21 -0700445 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200446 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700447 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
448 * encryption info footer and key, and plenty of bytes to spare for future
449 * growth.
450 */
451 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200452 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700453 cached_data = 1;
454 } else {
455 SLOGE("Cannot get size of block device %s\n", real_blkdev);
456 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700457 } else {
458 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
459 cached_off = 0;
460 cached_data = 1;
461 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700462 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700463
Paul Crowley14c8c072018-09-18 13:30:21 -0700464 if (cached_data) {
465 if (metadata_fname) {
466 *metadata_fname = cached_metadata_fname;
467 }
468 if (off) {
469 *off = cached_off;
470 }
471 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700472 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700473
Paul Crowley14c8c072018-09-18 13:30:21 -0700474 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700475}
476
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800477/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700478static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800479 SHA256_CTX c;
480 SHA256_Init(&c);
481 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
482 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
483 SHA256_Final(crypt_ftr->sha256, &c);
484}
485
Ken Sumralle8744072011-01-18 22:01:55 -0800486/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800487 * update the failed mount count but not change the key.
488 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700489static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
490 int fd;
491 unsigned int cnt;
492 /* starting_off is set to the SEEK_SET offset
493 * where the crypto structure starts
494 */
495 off64_t starting_off;
496 int rc = -1;
497 char* fname = NULL;
498 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800499
Paul Crowley14c8c072018-09-18 13:30:21 -0700500 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800501
Paul Crowley14c8c072018-09-18 13:30:21 -0700502 if (get_crypt_ftr_info(&fname, &starting_off)) {
503 SLOGE("Unable to get crypt_ftr_info\n");
504 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800505 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700506 if (fname[0] != '/') {
507 SLOGE("Unexpected value for crypto key location\n");
508 return -1;
509 }
510 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
511 SLOGE("Cannot open footer file %s for put\n", fname);
512 return -1;
513 }
Ken Sumralle8744072011-01-18 22:01:55 -0800514
Paul Crowley14c8c072018-09-18 13:30:21 -0700515 /* Seek to the start of the crypt footer */
516 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
517 SLOGE("Cannot seek to real block device footer\n");
518 goto errout;
519 }
520
521 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
522 SLOGE("Cannot write real block device footer\n");
523 goto errout;
524 }
525
526 fstat(fd, &statbuf);
527 /* If the keys are kept on a raw block device, do not try to truncate it. */
528 if (S_ISREG(statbuf.st_mode)) {
529 if (ftruncate(fd, 0x4000)) {
530 SLOGE("Cannot set footer file size\n");
531 goto errout;
532 }
533 }
534
535 /* Success! */
536 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800537
538errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700539 close(fd);
540 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800541}
542
Paul Crowley14c8c072018-09-18 13:30:21 -0700543static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800544 struct crypt_mnt_ftr copy;
545 memcpy(&copy, crypt_ftr, sizeof(copy));
546 set_ftr_sha(&copy);
547 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
548}
549
Paul Crowley14c8c072018-09-18 13:30:21 -0700550static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700551 return TEMP_FAILURE_RETRY(read(fd, buff, len));
552}
553
Paul Crowley14c8c072018-09-18 13:30:21 -0700554static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700555 return TEMP_FAILURE_RETRY(write(fd, buff, len));
556}
557
Paul Crowley14c8c072018-09-18 13:30:21 -0700558static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700559 memset(pdata, 0, len);
560 pdata->persist_magic = PERSIST_DATA_MAGIC;
561 pdata->persist_valid_entries = 0;
562}
563
564/* A routine to update the passed in crypt_ftr to the lastest version.
565 * fd is open read/write on the device that holds the crypto footer and persistent
566 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
567 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
568 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700569static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700570 int orig_major = crypt_ftr->major_version;
571 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700572
Kenny Root7434b312013-06-14 11:29:53 -0700573 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700574 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700575 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700576
Kenny Rootc4c70f12013-06-14 12:11:38 -0700577 SLOGW("upgrading crypto footer to 1.1");
578
Paul Crowley14c8c072018-09-18 13:30:21 -0700579 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700580 if (pdata == NULL) {
581 SLOGE("Cannot allocate persisent data\n");
582 return;
583 }
584 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
585
586 /* Need to initialize the persistent data area */
587 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
588 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100589 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700590 return;
591 }
592 /* Write all zeros to the first copy, making it invalid */
593 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
594
595 /* Write a valid but empty structure to the second copy */
596 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
597 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
598
599 /* Update the footer */
600 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
601 crypt_ftr->persist_data_offset[0] = pdata_offset;
602 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
603 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100604 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700605 }
606
Paul Lawrencef4faa572014-01-29 13:31:03 -0800607 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700608 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800609 /* But keep the old kdf_type.
610 * It will get updated later to KDF_SCRYPT after the password has been verified.
611 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700612 crypt_ftr->kdf_type = KDF_PBKDF2;
613 get_device_scrypt_params(crypt_ftr);
614 crypt_ftr->minor_version = 2;
615 }
616
Paul Lawrencef4faa572014-01-29 13:31:03 -0800617 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
618 SLOGW("upgrading crypto footer to 1.3");
619 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
620 crypt_ftr->minor_version = 3;
621 }
622
Kenny Root7434b312013-06-14 11:29:53 -0700623 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
624 if (lseek64(fd, offset, SEEK_SET) == -1) {
625 SLOGE("Cannot seek to crypt footer\n");
626 return;
627 }
628 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700629 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700630}
631
Paul Crowley14c8c072018-09-18 13:30:21 -0700632static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
633 int fd;
634 unsigned int cnt;
635 off64_t starting_off;
636 int rc = -1;
637 char* fname = NULL;
638 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700639
Paul Crowley14c8c072018-09-18 13:30:21 -0700640 if (get_crypt_ftr_info(&fname, &starting_off)) {
641 SLOGE("Unable to get crypt_ftr_info\n");
642 return -1;
643 }
644 if (fname[0] != '/') {
645 SLOGE("Unexpected value for crypto key location\n");
646 return -1;
647 }
648 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
649 SLOGE("Cannot open footer file %s for get\n", fname);
650 return -1;
651 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800652
Paul Crowley14c8c072018-09-18 13:30:21 -0700653 /* Make sure it's 16 Kbytes in length */
654 fstat(fd, &statbuf);
655 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
656 SLOGE("footer file %s is not the expected size!\n", fname);
657 goto errout;
658 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700659
Paul Crowley14c8c072018-09-18 13:30:21 -0700660 /* Seek to the start of the crypt footer */
661 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
662 SLOGE("Cannot seek to real block device footer\n");
663 goto errout;
664 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700665
Paul Crowley14c8c072018-09-18 13:30:21 -0700666 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
667 SLOGE("Cannot read real block device footer\n");
668 goto errout;
669 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800670
Paul Crowley14c8c072018-09-18 13:30:21 -0700671 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
672 SLOGE("Bad magic for real block device %s\n", fname);
673 goto errout;
674 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800675
Paul Crowley14c8c072018-09-18 13:30:21 -0700676 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
677 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
678 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
679 goto errout;
680 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800681
Paul Crowley14c8c072018-09-18 13:30:21 -0700682 // We risk buffer overflows with oversized keys, so we just reject them.
683 // 0-sized keys are problematic (essentially by-passing encryption), and
684 // AES-CBC key wrapping only works for multiples of 16 bytes.
685 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
686 (crypt_ftr->keysize > MAX_KEY_LEN)) {
687 SLOGE(
688 "Invalid keysize (%u) for block device %s; Must be non-zero, "
689 "divisible by 16, and <= %d\n",
690 crypt_ftr->keysize, fname, MAX_KEY_LEN);
691 goto errout;
692 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800693
Paul Crowley14c8c072018-09-18 13:30:21 -0700694 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
695 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
696 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
697 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800698
Paul Crowley14c8c072018-09-18 13:30:21 -0700699 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
700 * copy on disk before returning.
701 */
702 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
703 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
704 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800705
Paul Crowley14c8c072018-09-18 13:30:21 -0700706 /* Success! */
707 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800708
709errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700710 close(fd);
711 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800712}
713
Paul Crowley14c8c072018-09-18 13:30:21 -0700714static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700715 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
716 crypt_ftr->persist_data_offset[1]) {
717 SLOGE("Crypt_ftr persist data regions overlap");
718 return -1;
719 }
720
721 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
722 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
723 return -1;
724 }
725
726 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700727 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700728 CRYPT_FOOTER_OFFSET) {
729 SLOGE("Persistent data extends past crypto footer");
730 return -1;
731 }
732
733 return 0;
734}
735
Paul Crowley14c8c072018-09-18 13:30:21 -0700736static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700737 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700738 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700739 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700740 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700741 int found = 0;
742 int fd;
743 int ret;
744 int i;
745
746 if (persist_data) {
747 /* Nothing to do, we've already loaded or initialized it */
748 return 0;
749 }
750
Ken Sumrall160b4d62013-04-22 12:15:39 -0700751 /* If not encrypted, just allocate an empty table and initialize it */
752 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700753 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800754 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700755 if (pdata) {
756 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
757 persist_data = pdata;
758 return 0;
759 }
760 return -1;
761 }
762
Paul Crowley14c8c072018-09-18 13:30:21 -0700763 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700764 return -1;
765 }
766
Paul Crowley14c8c072018-09-18 13:30:21 -0700767 if ((crypt_ftr.major_version < 1) ||
768 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700769 SLOGE("Crypt_ftr version doesn't support persistent data");
770 return -1;
771 }
772
773 if (get_crypt_ftr_info(&fname, NULL)) {
774 return -1;
775 }
776
777 ret = validate_persistent_data_storage(&crypt_ftr);
778 if (ret) {
779 return -1;
780 }
781
Paul Crowley14c8c072018-09-18 13:30:21 -0700782 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700783 if (fd < 0) {
784 SLOGE("Cannot open %s metadata file", fname);
785 return -1;
786 }
787
Wei Wang4375f1b2017-02-24 17:43:01 -0800788 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800789 if (pdata == NULL) {
790 SLOGE("Cannot allocate memory for persistent data");
791 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700792 }
793
794 for (i = 0; i < 2; i++) {
795 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
796 SLOGE("Cannot seek to read persistent data on %s", fname);
797 goto err2;
798 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700799 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700800 SLOGE("Error reading persistent data on iteration %d", i);
801 goto err2;
802 }
803 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
804 found = 1;
805 break;
806 }
807 }
808
809 if (!found) {
810 SLOGI("Could not find valid persistent data, creating");
811 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
812 }
813
814 /* Success */
815 persist_data = pdata;
816 close(fd);
817 return 0;
818
819err2:
820 free(pdata);
821
822err:
823 close(fd);
824 return -1;
825}
826
Paul Crowley14c8c072018-09-18 13:30:21 -0700827static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700828 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700829 struct crypt_persist_data* pdata;
830 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700831 off64_t write_offset;
832 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700833 int fd;
834 int ret;
835
836 if (persist_data == NULL) {
837 SLOGE("No persistent data to save");
838 return -1;
839 }
840
Paul Crowley14c8c072018-09-18 13:30:21 -0700841 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700842 return -1;
843 }
844
Paul Crowley14c8c072018-09-18 13:30:21 -0700845 if ((crypt_ftr.major_version < 1) ||
846 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700847 SLOGE("Crypt_ftr version doesn't support persistent data");
848 return -1;
849 }
850
851 ret = validate_persistent_data_storage(&crypt_ftr);
852 if (ret) {
853 return -1;
854 }
855
856 if (get_crypt_ftr_info(&fname, NULL)) {
857 return -1;
858 }
859
Paul Crowley14c8c072018-09-18 13:30:21 -0700860 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700861 if (fd < 0) {
862 SLOGE("Cannot open %s metadata file", fname);
863 return -1;
864 }
865
Wei Wang4375f1b2017-02-24 17:43:01 -0800866 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700867 if (pdata == NULL) {
868 SLOGE("Cannot allocate persistant data");
869 goto err;
870 }
871
872 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
873 SLOGE("Cannot seek to read persistent data on %s", fname);
874 goto err2;
875 }
876
877 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700878 SLOGE("Error reading persistent data before save");
879 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700880 }
881
882 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
883 /* The first copy is the curent valid copy, so write to
884 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700885 write_offset = crypt_ftr.persist_data_offset[1];
886 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700887 } else {
888 /* The second copy must be the valid copy, so write to
889 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700890 write_offset = crypt_ftr.persist_data_offset[0];
891 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700892 }
893
894 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100895 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700896 SLOGE("Cannot seek to write persistent data");
897 goto err2;
898 }
899 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700900 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100901 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700902 SLOGE("Cannot seek to erase previous persistent data");
903 goto err2;
904 }
905 fsync(fd);
906 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -0700907 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700908 SLOGE("Cannot write to erase previous persistent data");
909 goto err2;
910 }
911 fsync(fd);
912 } else {
913 SLOGE("Cannot write to save persistent data");
914 goto err2;
915 }
916
917 /* Success */
918 free(pdata);
919 close(fd);
920 return 0;
921
922err2:
923 free(pdata);
924err:
925 close(fd);
926 return -1;
927}
928
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800929/* Convert a binary key of specified length into an ascii hex string equivalent,
930 * without the leading 0x and with null termination
931 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700932static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
933 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700934 unsigned int i, a;
935 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800936
Paul Crowley14c8c072018-09-18 13:30:21 -0700937 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700938 /* For each byte, write out two ascii hex digits */
939 nibble = (master_key[i] >> 4) & 0xf;
940 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700942 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -0700943 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700944 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800945
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700946 /* Add the null termination */
947 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800948}
949
Paul Crowley14c8c072018-09-18 13:30:21 -0700950static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
951 const unsigned char* master_key, const char* real_blk_name,
952 const char* name, int fd, const char* extra_params) {
953 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
954 struct dm_ioctl* io;
955 struct dm_target_spec* tgt;
956 char* crypt_params;
957 // We need two ASCII characters to represent each byte, and need space for
958 // the '\0' terminator.
959 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
960 size_t buff_offset;
961 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800962
Paul Crowley14c8c072018-09-18 13:30:21 -0700963 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800964
Paul Crowley14c8c072018-09-18 13:30:21 -0700965 /* Load the mapping table for this device */
966 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800967
Paul Crowley14c8c072018-09-18 13:30:21 -0700968 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
969 io->target_count = 1;
970 tgt->status = 0;
971 tgt->sector_start = 0;
972 tgt->length = crypt_ftr->fs_size;
973 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800974
Paul Crowley14c8c072018-09-18 13:30:21 -0700975 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
976 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800977
Paul Crowley14c8c072018-09-18 13:30:21 -0700978 buff_offset = crypt_params - buffer;
979 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
980 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
981 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
982 crypt_params += strlen(crypt_params) + 1;
983 crypt_params =
984 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
985 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800986
Paul Crowley14c8c072018-09-18 13:30:21 -0700987 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
988 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
989 break;
990 }
991 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800992 }
Ken Sumralldb5e0262013-02-05 17:39:48 -0800993
Paul Crowley14c8c072018-09-18 13:30:21 -0700994 if (i == TABLE_LOAD_RETRIES) {
995 /* We failed to load the table, return an error */
996 return -1;
997 } else {
998 return i + 1;
999 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001000}
1001
Paul Crowley14c8c072018-09-18 13:30:21 -07001002static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001003 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001004 struct dm_ioctl* io;
1005 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001006
Paul Crowley14c8c072018-09-18 13:30:21 -07001007 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001008
1009 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1010
1011 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1012 return -1;
1013 }
1014
1015 /* Iterate over the returned versions, looking for name of "crypt".
1016 * When found, get and return the version.
1017 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001018 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001019 while (v->next) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001020 if (!strcmp(v->name, "crypt")) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001021 /* We found the crypt driver, return the version, and get out */
1022 version[0] = v->version[0];
1023 version[1] = v->version[1];
1024 version[2] = v->version[2];
1025 return 0;
1026 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001027 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001028 }
1029
1030 return -1;
1031}
1032
Paul Crowley5afbc622017-11-27 09:42:17 -08001033static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1034 if (extra_params_vec.empty()) return "";
1035 std::string extra_params = std::to_string(extra_params_vec.size());
1036 for (const auto& p : extra_params_vec) {
1037 extra_params.append(" ");
1038 extra_params.append(p);
1039 }
1040 return extra_params;
1041}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001042
Paul Crowley5afbc622017-11-27 09:42:17 -08001043static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1044 const char* real_blk_name, char* crypto_blk_name, const char* name,
1045 uint32_t flags) {
1046 char buffer[DM_CRYPT_BUF_SIZE];
1047 struct dm_ioctl* io;
1048 unsigned int minor;
1049 int fd = 0;
1050 int err;
1051 int retval = -1;
1052 int version[3];
1053 int load_count;
1054 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001055
Paul Crowley5afbc622017-11-27 09:42:17 -08001056 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1057 SLOGE("Cannot open device-mapper\n");
1058 goto errout;
1059 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001060
Paul Crowley5afbc622017-11-27 09:42:17 -08001061 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001062
Paul Crowley5afbc622017-11-27 09:42:17 -08001063 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1064 err = ioctl(fd, DM_DEV_CREATE, io);
1065 if (err) {
1066 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1067 goto errout;
1068 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001069
Paul Crowley5afbc622017-11-27 09:42:17 -08001070 /* Get the device status, in particular, the name of it's device file */
1071 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1072 if (ioctl(fd, DM_DEV_STATUS, io)) {
1073 SLOGE("Cannot retrieve dm-crypt device status\n");
1074 goto errout;
1075 }
1076 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1077 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001078
Paul Crowley5afbc622017-11-27 09:42:17 -08001079 if (!get_dm_crypt_version(fd, name, version)) {
1080 /* Support for allow_discards was added in version 1.11.0 */
1081 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1082 extra_params_vec.emplace_back("allow_discards");
1083 }
1084 }
1085 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1086 extra_params_vec.emplace_back("allow_encrypt_override");
1087 }
1088 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1089 extra_params_as_string(extra_params_vec).c_str());
1090 if (load_count < 0) {
1091 SLOGE("Cannot load dm-crypt mapping table.\n");
1092 goto errout;
1093 } else if (load_count > 1) {
1094 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1095 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001096
Paul Crowley5afbc622017-11-27 09:42:17 -08001097 /* Resume this device to activate it */
1098 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001099
Paul Crowley5afbc622017-11-27 09:42:17 -08001100 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1101 SLOGE("Cannot resume the dm-crypt device\n");
1102 goto errout;
1103 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001104
Paul Crowley298fa322018-10-30 15:59:24 -07001105 /* Ensure the dm device has been created before returning. */
1106 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1107 // WaitForFile generates a suitable log message
1108 goto errout;
1109 }
1110
Paul Crowley5afbc622017-11-27 09:42:17 -08001111 /* We made it here with no errors. Woot! */
1112 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001113
1114errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001115 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 -08001116
Paul Crowley14c8c072018-09-18 13:30:21 -07001117 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001118}
1119
Paul Crowley14c8c072018-09-18 13:30:21 -07001120static int delete_crypto_blk_dev(const char* name) {
1121 int fd;
1122 char buffer[DM_CRYPT_BUF_SIZE];
1123 struct dm_ioctl* io;
1124 int retval = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125
Paul Crowley14c8c072018-09-18 13:30:21 -07001126 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1127 SLOGE("Cannot open device-mapper\n");
1128 goto errout;
1129 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001130
Paul Crowley14c8c072018-09-18 13:30:21 -07001131 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001132
Paul Crowley14c8c072018-09-18 13:30:21 -07001133 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1134 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1135 SLOGE("Cannot remove dm-crypt device\n");
1136 goto errout;
1137 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001138
Paul Crowley14c8c072018-09-18 13:30:21 -07001139 /* We made it here with no errors. Woot! */
1140 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001141
1142errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001143 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 -08001144
Paul Crowley14c8c072018-09-18 13:30:21 -07001145 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001146}
1147
Paul Crowley14c8c072018-09-18 13:30:21 -07001148static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1149 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001150 SLOGI("Using pbkdf2 for cryptfs KDF");
1151
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001152 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001153 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1154 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001155}
1156
Paul Crowley14c8c072018-09-18 13:30:21 -07001157static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001158 SLOGI("Using scrypt for cryptfs KDF");
1159
Paul Crowley14c8c072018-09-18 13:30:21 -07001160 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001161
1162 int N = 1 << ftr->N_factor;
1163 int r = 1 << ftr->r_factor;
1164 int p = 1 << ftr->p_factor;
1165
1166 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001167 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001168 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001169
Paul Crowley14c8c072018-09-18 13:30:21 -07001170 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001171}
1172
Paul Crowley14c8c072018-09-18 13:30:21 -07001173static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1174 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001175 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1176
1177 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001178 size_t signature_size;
1179 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001180 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001181
1182 int N = 1 << ftr->N_factor;
1183 int r = 1 << ftr->r_factor;
1184 int p = 1 << ftr->p_factor;
1185
Paul Crowley14c8c072018-09-18 13:30:21 -07001186 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001187 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001188
1189 if (rc) {
1190 SLOGE("scrypt failed");
1191 return -1;
1192 }
1193
Paul Crowley14c8c072018-09-18 13:30:21 -07001194 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001195 SLOGE("Signing failed");
1196 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001197 }
1198
Paul Crowley14c8c072018-09-18 13:30:21 -07001199 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1200 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001201 free(signature);
1202
1203 if (rc) {
1204 SLOGE("scrypt failed");
1205 return -1;
1206 }
1207
1208 return 0;
1209}
1210
Paul Crowley14c8c072018-09-18 13:30:21 -07001211static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1212 const unsigned char* decrypted_master_key,
1213 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1214 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001215 EVP_CIPHER_CTX e_ctx;
1216 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001217 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001218
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001219 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001220 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001221
1222 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001223 case KDF_SCRYPT_KEYMASTER:
1224 if (keymaster_create_key(crypt_ftr)) {
1225 SLOGE("keymaster_create_key failed");
1226 return -1;
1227 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001228
Paul Crowley14c8c072018-09-18 13:30:21 -07001229 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1230 SLOGE("scrypt failed");
1231 return -1;
1232 }
1233 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001234
Paul Crowley14c8c072018-09-18 13:30:21 -07001235 case KDF_SCRYPT:
1236 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1237 SLOGE("scrypt failed");
1238 return -1;
1239 }
1240 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001241
Paul Crowley14c8c072018-09-18 13:30:21 -07001242 default:
1243 SLOGE("Invalid kdf_type");
1244 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001245 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001246
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001247 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001248 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001249 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1250 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251 SLOGE("EVP_EncryptInit failed\n");
1252 return -1;
1253 }
1254 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001255
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001256 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001257 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1258 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259 SLOGE("EVP_EncryptUpdate failed\n");
1260 return -1;
1261 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001262 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001263 SLOGE("EVP_EncryptFinal failed\n");
1264 return -1;
1265 }
1266
Greg Kaiser59ad0182018-02-16 13:01:36 -08001267 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001268 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1269 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001270 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001271
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001272 /* Store the scrypt of the intermediate key, so we can validate if it's a
1273 password error or mount error when things go wrong.
1274 Note there's no need to check for errors, since if this is incorrect, we
1275 simply won't wipe userdata, which is the correct default behavior
1276 */
1277 int N = 1 << crypt_ftr->N_factor;
1278 int r = 1 << crypt_ftr->r_factor;
1279 int p = 1 << crypt_ftr->p_factor;
1280
Paul Crowley14c8c072018-09-18 13:30:21 -07001281 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1282 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001283 sizeof(crypt_ftr->scrypted_intermediate_key));
1284
1285 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001286 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001287 }
1288
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001289 EVP_CIPHER_CTX_cleanup(&e_ctx);
1290
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001291 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001292}
1293
Paul Crowley14c8c072018-09-18 13:30:21 -07001294static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1295 const unsigned char* encrypted_master_key, size_t keysize,
1296 unsigned char* decrypted_master_key, kdf_func kdf,
1297 void* kdf_params, unsigned char** intermediate_key,
1298 size_t* intermediate_key_size) {
1299 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1300 EVP_CIPHER_CTX d_ctx;
1301 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302
Paul Crowley14c8c072018-09-18 13:30:21 -07001303 /* Turn the password into an intermediate key and IV that can decrypt the
1304 master key */
1305 if (kdf(passwd, salt, ikey, kdf_params)) {
1306 SLOGE("kdf failed");
1307 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001308 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001309
Paul Crowley14c8c072018-09-18 13:30:21 -07001310 /* Initialize the decryption engine */
1311 EVP_CIPHER_CTX_init(&d_ctx);
1312 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1313 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1314 return -1;
1315 }
1316 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1317 /* Decrypt the master key */
1318 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1319 keysize)) {
1320 return -1;
1321 }
1322 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1323 return -1;
1324 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001325
Paul Crowley14c8c072018-09-18 13:30:21 -07001326 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1327 return -1;
1328 }
1329
1330 /* Copy intermediate key if needed by params */
1331 if (intermediate_key && intermediate_key_size) {
1332 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1333 if (*intermediate_key) {
1334 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1335 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1336 }
1337 }
1338
1339 EVP_CIPHER_CTX_cleanup(&d_ctx);
1340
1341 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001342}
1343
Paul Crowley14c8c072018-09-18 13:30:21 -07001344static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001345 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001346 *kdf = scrypt_keymaster;
1347 *kdf_params = ftr;
1348 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001349 *kdf = scrypt;
1350 *kdf_params = ftr;
1351 } else {
1352 *kdf = pbkdf2;
1353 *kdf_params = NULL;
1354 }
1355}
1356
Paul Crowley14c8c072018-09-18 13:30:21 -07001357static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1358 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1359 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001360 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001361 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001362 int ret;
1363
1364 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001365 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1366 decrypted_master_key, kdf, kdf_params, intermediate_key,
1367 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001368 if (ret != 0) {
1369 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001370 }
1371
1372 return ret;
1373}
1374
Paul Crowley14c8c072018-09-18 13:30:21 -07001375static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1376 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001377 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001378 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001379
1380 /* Get some random bits for a key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001381 fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001382 read(fd, key_buf, sizeof(key_buf));
1383 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001384 close(fd);
1385
1386 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001387 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001388}
1389
Paul Crowley14c8c072018-09-18 13:30:21 -07001390int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001391 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001392#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001393
1394 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001395 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001396 if (umount(mountpoint) == 0) {
1397 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001398 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001399
1400 if (errno == EINVAL) {
1401 /* EINVAL is returned if the directory is not a mountpoint,
1402 * i.e. there is no filesystem mounted there. So just get out.
1403 */
1404 break;
1405 }
1406
1407 err = errno;
1408
1409 /* If allowed, be increasingly aggressive before the last two retries */
1410 if (kill) {
1411 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1412 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001413 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001414 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1415 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001416 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001417 }
1418 }
1419
1420 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001421 }
1422
1423 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001424 SLOGD("unmounting %s succeeded\n", mountpoint);
1425 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001427 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1428 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1429 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430 }
1431
1432 return rc;
1433}
1434
Paul Crowley14c8c072018-09-18 13:30:21 -07001435static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001436 // NOTE: post_fs_data results in init calling back around to vold, so all
1437 // callers to this method must be async
1438
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001439 /* Do the prep of the /data filesystem */
1440 property_set("vold.post_fs_data_done", "0");
1441 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001442 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001443
Ken Sumrallc5872692013-05-14 15:26:31 -07001444 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001445 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001446 /* We timed out to prep /data in time. Continue wait. */
1447 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001448 }
Wei Wang42e38102017-06-07 10:46:12 -07001449 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001450}
1451
Paul Crowley14c8c072018-09-18 13:30:21 -07001452static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001453 // Mark the footer as bad
1454 struct crypt_mnt_ftr crypt_ftr;
1455 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1456 SLOGE("Failed to get crypto footer - panic");
1457 return;
1458 }
1459
1460 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1461 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1462 SLOGE("Failed to set crypto footer - panic");
1463 return;
1464 }
1465}
1466
Paul Crowley14c8c072018-09-18 13:30:21 -07001467static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001468 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001469 SLOGE("Failed to mount tmpfs on data - panic");
1470 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001471 }
1472
1473 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1474 SLOGE("Failed to trigger post fs data - panic");
1475 return;
1476 }
1477
1478 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1479 SLOGE("Failed to trigger restart min framework - panic");
1480 return;
1481 }
1482}
1483
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001484/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001485static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001486 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001487 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001488 static int restart_successful = 0;
1489
1490 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001491 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001492 SLOGE("Encrypted filesystem not validated, aborting");
1493 return -1;
1494 }
1495
1496 if (restart_successful) {
1497 SLOGE("System already restarted with encrypted disk, aborting");
1498 return -1;
1499 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001500
Paul Lawrencef4faa572014-01-29 13:31:03 -08001501 if (restart_main) {
1502 /* Here is where we shut down the framework. The init scripts
1503 * start all services in one of three classes: core, main or late_start.
1504 * On boot, we start core and main. Now, we stop main, but not core,
1505 * as core includes vold and a few other really important things that
1506 * we need to keep running. Once main has stopped, we should be able
1507 * to umount the tmpfs /data, then mount the encrypted /data.
1508 * We then restart the class main, and also the class late_start.
1509 * At the moment, I've only put a few things in late_start that I know
1510 * are not needed to bring up the framework, and that also cause problems
1511 * with unmounting the tmpfs /data, but I hope to add add more services
1512 * to the late_start class as we optimize this to decrease the delay
1513 * till the user is asked for the password to the filesystem.
1514 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001515
Paul Lawrencef4faa572014-01-29 13:31:03 -08001516 /* The init files are setup to stop the class main when vold.decrypt is
1517 * set to trigger_reset_main.
1518 */
1519 property_set("vold.decrypt", "trigger_reset_main");
1520 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521
Paul Lawrencef4faa572014-01-29 13:31:03 -08001522 /* Ugh, shutting down the framework is not synchronous, so until it
1523 * can be fixed, this horrible hack will wait a moment for it all to
1524 * shut down before proceeding. Without it, some devices cannot
1525 * restart the graphics services.
1526 */
1527 sleep(2);
1528 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001529
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001530 /* Now that the framework is shutdown, we should be able to umount()
1531 * the tmpfs filesystem, and mount the real one.
1532 */
1533
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001534 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1535 if (strlen(crypto_blkdev) == 0) {
1536 SLOGE("fs_crypto_blkdev not set\n");
1537 return -1;
1538 }
1539
Paul Crowley14c8c072018-09-18 13:30:21 -07001540 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001541 /* If ro.crypto.readonly is set to 1, mount the decrypted
1542 * filesystem readonly. This is used when /data is mounted by
1543 * recovery mode.
1544 */
1545 char ro_prop[PROPERTY_VALUE_MAX];
1546 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001547 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001548 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001549 if (rec) {
1550 rec->flags |= MS_RDONLY;
1551 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001552 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001553
Ken Sumralle5032c42012-04-01 23:58:44 -07001554 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001555 int retries = RETRY_MOUNT_ATTEMPTS;
1556 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001557
1558 /*
1559 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1560 * partitions in the fsck domain.
1561 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001562 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001563 SLOGE("Failed to setexeccon");
1564 return -1;
1565 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001566 bool needs_cp = android::vold::cp_needsCheckpoint();
1567 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1568 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001569 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1570 /* TODO: invoke something similar to
1571 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1572 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001573 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001574 if (--retries) {
1575 sleep(RETRY_MOUNT_DELAY_SECONDS);
1576 } else {
1577 /* Let's hope that a reboot clears away whatever is keeping
1578 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001579 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001580 }
1581 } else {
1582 SLOGE("Failed to mount decrypted data");
1583 cryptfs_set_corrupt();
1584 cryptfs_trigger_restart_min_framework();
1585 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001586 if (setexeccon(NULL)) {
1587 SLOGE("Failed to setexeccon");
1588 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001589 return -1;
1590 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001591 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001592 if (setexeccon(NULL)) {
1593 SLOGE("Failed to setexeccon");
1594 return -1;
1595 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596
Ken Sumralle5032c42012-04-01 23:58:44 -07001597 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001598 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001599 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001600
1601 /* startup service classes main and late_start */
1602 property_set("vold.decrypt", "trigger_restart_framework");
1603 SLOGD("Just triggered restart_framework\n");
1604
1605 /* Give it a few moments to get started */
1606 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001607 }
1608
Ken Sumrall0cc16632011-01-18 20:32:26 -08001609 if (rc == 0) {
1610 restart_successful = 1;
1611 }
1612
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001613 return rc;
1614}
1615
Paul Crowley14c8c072018-09-18 13:30:21 -07001616int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001617 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001618 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001619 SLOGE("cryptfs_restart not valid for file encryption:");
1620 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001621 }
1622
Paul Lawrencef4faa572014-01-29 13:31:03 -08001623 /* Call internal implementation forcing a restart of main service group */
1624 return cryptfs_restart_internal(1);
1625}
1626
Paul Crowley14c8c072018-09-18 13:30:21 -07001627static int do_crypto_complete(const char* mount_point) {
1628 struct crypt_mnt_ftr crypt_ftr;
1629 char encrypted_state[PROPERTY_VALUE_MAX];
1630 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001631
Paul Crowley14c8c072018-09-18 13:30:21 -07001632 property_get("ro.crypto.state", encrypted_state, "");
1633 if (strcmp(encrypted_state, "encrypted")) {
1634 SLOGE("not running with encryption, aborting");
1635 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001636 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001637
Paul Crowley14c8c072018-09-18 13:30:21 -07001638 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001639 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001640 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1641 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001642
Paul Crowley14c8c072018-09-18 13:30:21 -07001643 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1644 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001645
Paul Crowley14c8c072018-09-18 13:30:21 -07001646 /*
1647 * Only report this error if key_loc is a file and it exists.
1648 * If the device was never encrypted, and /data is not mountable for
1649 * some reason, returning 1 should prevent the UI from presenting the
1650 * a "enter password" screen, or worse, a "press button to wipe the
1651 * device" screen.
1652 */
1653 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1654 SLOGE("master key file does not exist, aborting");
1655 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1656 } else {
1657 SLOGE("Error getting crypt footer and key\n");
1658 return CRYPTO_COMPLETE_BAD_METADATA;
1659 }
1660 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001661
Paul Crowley14c8c072018-09-18 13:30:21 -07001662 // Test for possible error flags
1663 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1664 SLOGE("Encryption process is partway completed\n");
1665 return CRYPTO_COMPLETE_PARTIAL;
1666 }
1667
1668 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1669 SLOGE("Encryption process was interrupted but cannot continue\n");
1670 return CRYPTO_COMPLETE_INCONSISTENT;
1671 }
1672
1673 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1674 SLOGE("Encryption is successful but data is corrupt\n");
1675 return CRYPTO_COMPLETE_CORRUPT;
1676 }
1677
1678 /* We passed the test! We shall diminish, and return to the west */
1679 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001680}
1681
Paul Crowley14c8c072018-09-18 13:30:21 -07001682static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1683 const char* mount_point, const char* label) {
1684 unsigned char decrypted_master_key[MAX_KEY_LEN];
1685 char crypto_blkdev[MAXPATHLEN];
1686 char real_blkdev[MAXPATHLEN];
1687 char tmp_mount_point[64];
1688 unsigned int orig_failed_decrypt_count;
1689 int rc;
1690 int use_keymaster = 0;
1691 int upgrade = 0;
1692 unsigned char* intermediate_key = 0;
1693 size_t intermediate_key_size = 0;
1694 int N = 1 << crypt_ftr->N_factor;
1695 int r = 1 << crypt_ftr->r_factor;
1696 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001697
Paul Crowley14c8c072018-09-18 13:30:21 -07001698 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1699 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001700
Paul Crowley14c8c072018-09-18 13:30:21 -07001701 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1702 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1703 &intermediate_key_size)) {
1704 SLOGE("Failed to decrypt master key\n");
1705 rc = -1;
1706 goto errout;
1707 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001708 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001709
Paul Crowley14c8c072018-09-18 13:30:21 -07001710 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001711
Paul Crowley14c8c072018-09-18 13:30:21 -07001712 // Create crypto block device - all (non fatal) code paths
1713 // need it
1714 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
1715 0)) {
1716 SLOGE("Error creating decrypted block device\n");
1717 rc = -1;
1718 goto errout;
1719 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001720
Paul Crowley14c8c072018-09-18 13:30:21 -07001721 /* Work out if the problem is the password or the data */
1722 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001723
Paul Crowley14c8c072018-09-18 13:30:21 -07001724 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1725 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1726 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001727
Paul Crowley14c8c072018-09-18 13:30:21 -07001728 // Does the key match the crypto footer?
1729 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1730 sizeof(scrypted_intermediate_key)) == 0) {
1731 SLOGI("Password matches");
1732 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001733 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001734 /* Try mounting the file system anyway, just in case the problem's with
1735 * the footer, not the key. */
1736 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1737 mkdir(tmp_mount_point, 0755);
1738 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1739 SLOGE("Error temp mounting decrypted block device\n");
1740 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001741
Paul Crowley14c8c072018-09-18 13:30:21 -07001742 rc = ++crypt_ftr->failed_decrypt_count;
1743 put_crypt_ftr_and_key(crypt_ftr);
1744 } else {
1745 /* Success! */
1746 SLOGI("Password did not match but decrypted drive mounted - continue");
1747 umount(tmp_mount_point);
1748 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001749 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001750 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001751
Paul Crowley14c8c072018-09-18 13:30:21 -07001752 if (rc == 0) {
1753 crypt_ftr->failed_decrypt_count = 0;
1754 if (orig_failed_decrypt_count != 0) {
1755 put_crypt_ftr_and_key(crypt_ftr);
1756 }
1757
1758 /* Save the name of the crypto block device
1759 * so we can mount it when restarting the framework. */
1760 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1761
1762 /* Also save a the master key so we can reencrypted the key
1763 * the key when we want to change the password on it. */
1764 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1765 saved_mount_point = strdup(mount_point);
1766 master_key_saved = 1;
1767 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1768 rc = 0;
1769
1770 // Upgrade if we're not using the latest KDF.
1771 use_keymaster = keymaster_check_compatibility();
1772 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1773 // Don't allow downgrade
1774 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1775 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1776 upgrade = 1;
1777 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1778 crypt_ftr->kdf_type = KDF_SCRYPT;
1779 upgrade = 1;
1780 }
1781
1782 if (upgrade) {
1783 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1784 crypt_ftr->master_key, crypt_ftr);
1785 if (!rc) {
1786 rc = put_crypt_ftr_and_key(crypt_ftr);
1787 }
1788 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1789
1790 // Do not fail even if upgrade failed - machine is bootable
1791 // Note that if this code is ever hit, there is a *serious* problem
1792 // since KDFs should never fail. You *must* fix the kdf before
1793 // proceeding!
1794 if (rc) {
1795 SLOGW(
1796 "Upgrade failed with error %d,"
1797 " but continuing with previous state",
1798 rc);
1799 rc = 0;
1800 }
1801 }
1802 }
1803
1804errout:
1805 if (intermediate_key) {
1806 memset(intermediate_key, 0, intermediate_key_size);
1807 free(intermediate_key);
1808 }
1809 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001810}
1811
Ken Sumrall29d8da82011-05-18 17:20:07 -07001812/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001813 * Called by vold when it's asked to mount an encrypted external
1814 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001815 * as any metadata is been stored in a separate, small partition. We
1816 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001817 *
1818 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001819 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001820int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1821 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001822 uint64_t nr_sec = 0;
1823 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001824 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001825 return -1;
1826 }
1827
Jeff Sharkey9c484982015-03-31 10:35:33 -07001828 struct crypt_mnt_ftr ext_crypt_ftr;
1829 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1830 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001831 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001832 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001833 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001834 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001835 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001836 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1837 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001838
Paul Crowley385cb8c2018-03-29 13:27:23 -07001839 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001840}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001841
Jeff Sharkey9c484982015-03-31 10:35:33 -07001842/*
1843 * Called by vold when it's asked to unmount an encrypted external
1844 * storage volume.
1845 */
1846int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001847 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001848}
1849
Paul Crowley14c8c072018-09-18 13:30:21 -07001850int cryptfs_crypto_complete(void) {
1851 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001852}
1853
Paul Crowley14c8c072018-09-18 13:30:21 -07001854int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001855 char encrypted_state[PROPERTY_VALUE_MAX];
1856 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001857 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1858 SLOGE(
1859 "encrypted fs already validated or not running with encryption,"
1860 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001861 return -1;
1862 }
1863
1864 if (get_crypt_ftr_and_key(crypt_ftr)) {
1865 SLOGE("Error getting crypt footer and key");
1866 return -1;
1867 }
1868
1869 return 0;
1870}
1871
Paul Crowley14c8c072018-09-18 13:30:21 -07001872int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001873 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001874 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001875 SLOGE("cryptfs_check_passwd not valid for file encryption");
1876 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001877 }
1878
Paul Lawrencef4faa572014-01-29 13:31:03 -08001879 struct crypt_mnt_ftr crypt_ftr;
1880 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001881
Paul Lawrencef4faa572014-01-29 13:31:03 -08001882 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001883 if (rc) {
1884 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001885 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001886 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001887
Paul Crowley14c8c072018-09-18 13:30:21 -07001888 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001889 if (rc) {
1890 SLOGE("Password did not match");
1891 return rc;
1892 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001893
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001894 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1895 // Here we have a default actual password but a real password
1896 // we must test against the scrypted value
1897 // First, we must delete the crypto block device that
1898 // test_mount_encrypted_fs leaves behind as a side effect
1899 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001900 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1901 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001902 if (rc) {
1903 SLOGE("Default password did not match on reboot encryption");
1904 return rc;
1905 }
1906
1907 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1908 put_crypt_ftr_and_key(&crypt_ftr);
1909 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1910 if (rc) {
1911 SLOGE("Could not change password on reboot encryption");
1912 return rc;
1913 }
1914 }
1915
1916 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001917 cryptfs_clear_password();
1918 password = strdup(passwd);
1919 struct timespec now;
1920 clock_gettime(CLOCK_BOOTTIME, &now);
1921 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001922 }
1923
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001924 return rc;
1925}
1926
Paul Crowley14c8c072018-09-18 13:30:21 -07001927int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001928 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001929 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001930 char encrypted_state[PROPERTY_VALUE_MAX];
1931 int rc;
1932
1933 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001934 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001935 SLOGE("device not encrypted, aborting");
1936 return -2;
1937 }
1938
1939 if (!master_key_saved) {
1940 SLOGE("encrypted fs not yet mounted, aborting");
1941 return -1;
1942 }
1943
1944 if (!saved_mount_point) {
1945 SLOGE("encrypted fs failed to save mount point, aborting");
1946 return -1;
1947 }
1948
Ken Sumrall160b4d62013-04-22 12:15:39 -07001949 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001950 SLOGE("Error getting crypt footer and key\n");
1951 return -1;
1952 }
1953
1954 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1955 /* If the device has no password, then just say the password is valid */
1956 rc = 0;
1957 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001958 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001959 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1960 /* They match, the password is correct */
1961 rc = 0;
1962 } else {
1963 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1964 sleep(1);
1965 rc = 1;
1966 }
1967 }
1968
1969 return rc;
1970}
1971
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001972/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08001973 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001974 * Presumably, at a minimum, the caller will update the
1975 * filesystem size and crypto_type_name after calling this function.
1976 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001977static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001978 off64_t off;
1979
1980 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001981 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001982 ftr->major_version = CURRENT_MAJOR_VERSION;
1983 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001984 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08001985 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07001986
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001987 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001988 case 1:
1989 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1990 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001991
Paul Crowley14c8c072018-09-18 13:30:21 -07001992 case 0:
1993 ftr->kdf_type = KDF_SCRYPT;
1994 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001995
Paul Crowley14c8c072018-09-18 13:30:21 -07001996 default:
1997 SLOGE("keymaster_check_compatibility failed");
1998 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001999 }
2000
Kenny Rootc4c70f12013-06-14 12:11:38 -07002001 get_device_scrypt_params(ftr);
2002
Ken Sumrall160b4d62013-04-22 12:15:39 -07002003 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2004 if (get_crypt_ftr_info(NULL, &off) == 0) {
2005 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002006 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002007 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002008
2009 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002010}
2011
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002012#define FRAMEWORK_BOOT_WAIT 60
2013
Paul Crowley14c8c072018-09-18 13:30:21 -07002014static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2015 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002016 if (fd == -1) {
2017 SLOGE("Error opening file %s", filename);
2018 return -1;
2019 }
2020
2021 char block[CRYPT_INPLACE_BUFSIZE];
2022 memset(block, 0, sizeof(block));
2023 if (unix_read(fd, block, sizeof(block)) < 0) {
2024 SLOGE("Error reading file %s", filename);
2025 close(fd);
2026 return -1;
2027 }
2028
2029 close(fd);
2030
2031 SHA256_CTX c;
2032 SHA256_Init(&c);
2033 SHA256_Update(&c, block, sizeof(block));
2034 SHA256_Final(buf, &c);
2035
2036 return 0;
2037}
2038
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002039static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2040 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002041 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002042 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002043
Paul Lawrence87999172014-02-20 12:21:31 -08002044 /* The size of the userdata partition, and add in the vold volumes below */
2045 tot_encryption_size = crypt_ftr->fs_size;
2046
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002047 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002048 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002049
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002050 if (rc == ENABLE_INPLACE_ERR_DEV) {
2051 /* Hack for b/17898962 */
2052 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2053 cryptfs_reboot(RebootType::reboot);
2054 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002055
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002056 if (!rc) {
2057 crypt_ftr->encrypted_upto = cur_encryption_done;
2058 }
Paul Lawrence87999172014-02-20 12:21:31 -08002059
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002060 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2061 /* The inplace routine never actually sets the progress to 100% due
2062 * to the round down nature of integer division, so set it here */
2063 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002064 }
2065
2066 return rc;
2067}
2068
Paul Crowleyb64933a2017-10-31 08:25:55 -07002069static int vold_unmountAll(void) {
2070 VolumeManager* vm = VolumeManager::Instance();
2071 return vm->unmountAll();
2072}
2073
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002074int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002075 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002076 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002077 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002078 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002079 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002080 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002081 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002082 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002083 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002084 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002085 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002086 bool onlyCreateHeader = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002087
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002088 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002089 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2090 /* An encryption was underway and was interrupted */
2091 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2092 crypt_ftr.encrypted_upto = 0;
2093 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002094
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002095 /* At this point, we are in an inconsistent state. Until we successfully
2096 complete encryption, a reboot will leave us broken. So mark the
2097 encryption failed in case that happens.
2098 On successfully completing encryption, remove this flag */
2099 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002100
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002101 put_crypt_ftr_and_key(&crypt_ftr);
2102 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2103 if (!check_ftr_sha(&crypt_ftr)) {
2104 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2105 put_crypt_ftr_and_key(&crypt_ftr);
2106 goto error_unencrypted;
2107 }
2108
2109 /* Doing a reboot-encryption*/
2110 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2111 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2112 rebootEncryption = true;
2113 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002114 } else {
2115 // We don't want to accidentally reference invalid data.
2116 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002117 }
2118
2119 property_get("ro.crypto.state", encrypted_state, "");
2120 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2121 SLOGE("Device is already running encrypted, aborting");
2122 goto error_unencrypted;
2123 }
2124
2125 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002126 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2127 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002128
Ken Sumrall3ed82362011-01-28 23:31:16 -08002129 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002130 uint64_t nr_sec;
2131 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002132 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2133 goto error_unencrypted;
2134 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002135
2136 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002137 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002138 uint64_t fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002139 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002140 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002141
Paul Lawrence87999172014-02-20 12:21:31 -08002142 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002143
2144 if (fs_size_sec > max_fs_size_sec) {
2145 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2146 goto error_unencrypted;
2147 }
2148 }
2149
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002150 /* Get a wakelock as this may take a while, and we don't want the
2151 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2152 * wants to keep the screen on, it can grab a full wakelock.
2153 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002154 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002155 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2156
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002157 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002158 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002159 */
2160 property_set("vold.decrypt", "trigger_shutdown_framework");
2161 SLOGD("Just asked init to shut down class main\n");
2162
Jeff Sharkey9c484982015-03-31 10:35:33 -07002163 /* Ask vold to unmount all devices that it manages */
2164 if (vold_unmountAll()) {
2165 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002166 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002167
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002168 /* no_ui means we are being called from init, not settings.
2169 Now we always reboot from settings, so !no_ui means reboot
2170 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002171 if (!no_ui) {
2172 /* Try fallback, which is to reboot and try there */
2173 onlyCreateHeader = true;
2174 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2175 if (breadcrumb == 0) {
2176 SLOGE("Failed to create breadcrumb file");
2177 goto error_shutting_down;
2178 }
2179 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002180 }
2181
2182 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002183 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002184 /* Now that /data is unmounted, we need to mount a tmpfs
2185 * /data, set a property saying we're doing inplace encryption,
2186 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002187 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002188 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002189 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002190 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002191 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002192 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002193
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002194 /* restart the framework. */
2195 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002196 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002197
Ken Sumrall92736ef2012-10-17 20:57:14 -07002198 /* Ugh, shutting down the framework is not synchronous, so until it
2199 * can be fixed, this horrible hack will wait a moment for it all to
2200 * shut down before proceeding. Without it, some devices cannot
2201 * restart the graphics services.
2202 */
2203 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002204 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002205
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002206 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002207 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002208 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002209 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2210 goto error_shutting_down;
2211 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002212
Paul Lawrence87999172014-02-20 12:21:31 -08002213 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002214 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002215 } else {
2216 crypt_ftr.fs_size = nr_sec;
2217 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002218 /* At this point, we are in an inconsistent state. Until we successfully
2219 complete encryption, a reboot will leave us broken. So mark the
2220 encryption failed in case that happens.
2221 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002222 if (onlyCreateHeader) {
2223 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2224 } else {
2225 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2226 }
Paul Lawrence87999172014-02-20 12:21:31 -08002227 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002228 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2229 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002230
Paul Lawrence87999172014-02-20 12:21:31 -08002231 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002232 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2233 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002234 SLOGE("Cannot create encrypted master key\n");
2235 goto error_shutting_down;
2236 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002237
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002238 /* Replace scrypted intermediate key if we are preparing for a reboot */
2239 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002240 unsigned char fake_master_key[MAX_KEY_LEN];
2241 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002242 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002243 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2244 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002245 }
2246
Paul Lawrence87999172014-02-20 12:21:31 -08002247 /* Write the key to the end of the partition */
2248 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002249
Paul Lawrence87999172014-02-20 12:21:31 -08002250 /* If any persistent data has been remembered, save it.
2251 * If none, create a valid empty table and save that.
2252 */
2253 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002254 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2255 if (pdata) {
2256 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2257 persist_data = pdata;
2258 }
Paul Lawrence87999172014-02-20 12:21:31 -08002259 }
2260 if (persist_data) {
2261 save_persistent_data();
2262 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002263 }
2264
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002265 if (onlyCreateHeader) {
2266 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002267 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002268 }
2269
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002270 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002271 /* startup service classes main and late_start */
2272 property_set("vold.decrypt", "trigger_restart_min_framework");
2273 SLOGD("Just triggered restart_min_framework\n");
2274
2275 /* OK, the framework is restarted and will soon be showing a
2276 * progress bar. Time to setup an encrypted mapping, and
2277 * either write a new filesystem, or encrypt in place updating
2278 * the progress bar as we work.
2279 */
2280 }
2281
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002282 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002283 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002284 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002285
Paul Lawrence87999172014-02-20 12:21:31 -08002286 /* If we are continuing, check checksums match */
2287 rc = 0;
2288 if (previously_encrypted_upto) {
2289 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2290 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002291
Paul Crowley14c8c072018-09-18 13:30:21 -07002292 if (!rc &&
2293 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002294 SLOGE("Checksums do not match - trigger wipe");
2295 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002296 }
2297 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002298
Paul Lawrence87999172014-02-20 12:21:31 -08002299 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002300 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002301 previously_encrypted_upto);
2302 }
2303
2304 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002305 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002306 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002307 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002308 SLOGE("Error calculating checksum for continuing encryption");
2309 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002310 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002311 }
2312
2313 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002314 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002315
Paul Crowley14c8c072018-09-18 13:30:21 -07002316 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002317 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002318 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002319
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002320 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002321 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2322 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002323 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002324 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002325
Paul Lawrence6bfed202014-07-28 12:47:22 -07002326 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002327
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002328 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2329 char value[PROPERTY_VALUE_MAX];
2330 property_get("ro.crypto.state", value, "");
2331 if (!strcmp(value, "")) {
2332 /* default encryption - continue first boot sequence */
2333 property_set("ro.crypto.state", "encrypted");
2334 property_set("ro.crypto.type", "block");
2335 release_wake_lock(lockid);
2336 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2337 // Bring up cryptkeeper that will check the password and set it
2338 property_set("vold.decrypt", "trigger_shutdown_framework");
2339 sleep(2);
2340 property_set("vold.encrypt_progress", "");
2341 cryptfs_trigger_restart_min_framework();
2342 } else {
2343 cryptfs_check_passwd(DEFAULT_PASSWORD);
2344 cryptfs_restart_internal(1);
2345 }
2346 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002347 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002348 sleep(2); /* Give the UI a chance to show 100% progress */
2349 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002350 }
Paul Lawrence87999172014-02-20 12:21:31 -08002351 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002352 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002353 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002354 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002355 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002356 char value[PROPERTY_VALUE_MAX];
2357
Ken Sumrall319369a2012-06-27 16:30:18 -07002358 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002359 if (!strcmp(value, "1")) {
2360 /* wipe data if encryption failed */
2361 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002362 std::string err;
2363 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002364 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002365 if (!write_bootloader_message(options, &err)) {
2366 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002367 }
Josh Gaofec44372017-08-28 13:22:55 -07002368 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002369 } else {
2370 /* set property to trigger dialog */
2371 property_set("vold.encrypt_progress", "error_partially_encrypted");
2372 release_wake_lock(lockid);
2373 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002374 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002375 }
2376
Ken Sumrall3ed82362011-01-28 23:31:16 -08002377 /* hrm, the encrypt step claims success, but the reboot failed.
2378 * This should not happen.
2379 * Set the property and return. Hope the framework can deal with it.
2380 */
2381 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002382 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002383 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002384
2385error_unencrypted:
2386 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002387 if (lockid[0]) {
2388 release_wake_lock(lockid);
2389 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002390 return -1;
2391
2392error_shutting_down:
2393 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2394 * but the framework is stopped and not restarted to show the error, so it's up to
2395 * vold to restart the system.
2396 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002397 SLOGE(
2398 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2399 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002400 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002401
2402 /* shouldn't get here */
2403 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002404 if (lockid[0]) {
2405 release_wake_lock(lockid);
2406 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002407 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002408}
2409
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002410int cryptfs_enable(int type, const char* passwd, int no_ui) {
2411 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002412}
2413
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002414int cryptfs_enable_default(int no_ui) {
2415 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002416}
2417
Paul Crowley14c8c072018-09-18 13:30:21 -07002418int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002419 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002420 SLOGE("cryptfs_changepw not valid for file encryption");
2421 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002422 }
2423
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002424 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002425 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002426
2427 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002428 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002429 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002430 return -1;
2431 }
2432
Paul Lawrencef4faa572014-01-29 13:31:03 -08002433 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2434 SLOGE("Invalid crypt_type %d", crypt_type);
2435 return -1;
2436 }
2437
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002438 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002439 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002440 SLOGE("Error getting crypt footer and key");
2441 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002442 }
2443
Paul Lawrencef4faa572014-01-29 13:31:03 -08002444 crypt_ftr.crypt_type = crypt_type;
2445
Paul Crowley14c8c072018-09-18 13:30:21 -07002446 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2447 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002448 if (rc) {
2449 SLOGE("Encrypt master key failed: %d", rc);
2450 return -1;
2451 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002452 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002453 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002454
2455 return 0;
2456}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002457
Rubin Xu85c01f92014-10-13 12:49:54 +01002458static unsigned int persist_get_max_entries(int encrypted) {
2459 struct crypt_mnt_ftr crypt_ftr;
2460 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002461
2462 /* If encrypted, use the values from the crypt_ftr, otherwise
2463 * use the values for the current spec.
2464 */
2465 if (encrypted) {
2466 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01002467 /* Something is wrong, assume no space for entries */
2468 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002469 }
2470 dsize = crypt_ftr.persist_data_size;
2471 } else {
2472 dsize = CRYPT_PERSIST_DATA_SIZE;
2473 }
2474
Rubin Xud78181b2018-10-09 16:13:38 +01002475 if (dsize > sizeof(struct crypt_persist_data)) {
2476 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2477 } else {
2478 return 0;
2479 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002480}
2481
Paul Crowley14c8c072018-09-18 13:30:21 -07002482static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002483 unsigned int i;
2484
2485 if (persist_data == NULL) {
2486 return -1;
2487 }
2488 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2489 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2490 /* We found it! */
2491 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2492 return 0;
2493 }
2494 }
2495
2496 return -1;
2497}
2498
Paul Crowley14c8c072018-09-18 13:30:21 -07002499static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002500 unsigned int i;
2501 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002502 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002503
2504 if (persist_data == NULL) {
2505 return -1;
2506 }
2507
Rubin Xu85c01f92014-10-13 12:49:54 +01002508 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002509
2510 num = persist_data->persist_valid_entries;
2511
2512 for (i = 0; i < num; i++) {
2513 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2514 /* We found an existing entry, update it! */
2515 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2516 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2517 return 0;
2518 }
2519 }
2520
2521 /* We didn't find it, add it to the end, if there is room */
2522 if (persist_data->persist_valid_entries < max_persistent_entries) {
2523 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2524 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2525 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2526 persist_data->persist_valid_entries++;
2527 return 0;
2528 }
2529
2530 return -1;
2531}
2532
Rubin Xu85c01f92014-10-13 12:49:54 +01002533/**
2534 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2535 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2536 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002537int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002538 std::string key_ = key;
2539 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002540
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002541 std::string parsed_field;
2542 unsigned parsed_index;
2543
2544 std::string::size_type split = key_.find_last_of('_');
2545 if (split == std::string::npos) {
2546 parsed_field = key_;
2547 parsed_index = 0;
2548 } else {
2549 parsed_field = key_.substr(0, split);
2550 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002551 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002552
2553 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002554}
2555
2556/*
2557 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2558 * remaining entries starting from index will be deleted.
2559 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2560 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2561 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2562 *
2563 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002564static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002565 unsigned int i;
2566 unsigned int j;
2567 unsigned int num;
2568
2569 if (persist_data == NULL) {
2570 return PERSIST_DEL_KEY_ERROR_OTHER;
2571 }
2572
2573 num = persist_data->persist_valid_entries;
2574
Paul Crowley14c8c072018-09-18 13:30:21 -07002575 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002576 // Filter out to-be-deleted entries in place.
2577 for (i = 0; i < num; i++) {
2578 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2579 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2580 j++;
2581 }
2582 }
2583
2584 if (j < num) {
2585 persist_data->persist_valid_entries = j;
2586 // Zeroise the remaining entries
2587 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2588 return PERSIST_DEL_KEY_OK;
2589 } else {
2590 // Did not find an entry matching the given fieldname
2591 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2592 }
2593}
2594
Paul Crowley14c8c072018-09-18 13:30:21 -07002595static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002596 unsigned int i;
2597 unsigned int count;
2598
2599 if (persist_data == NULL) {
2600 return -1;
2601 }
2602
2603 count = 0;
2604 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2605 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2606 count++;
2607 }
2608 }
2609
2610 return count;
2611}
2612
Ken Sumrall160b4d62013-04-22 12:15:39 -07002613/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002614int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002615 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002616 SLOGE("Cannot get field when file encrypted");
2617 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002618 }
2619
Ken Sumrall160b4d62013-04-22 12:15:39 -07002620 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002621 /* CRYPTO_GETFIELD_OK is success,
2622 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2623 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2624 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002625 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002626 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2627 int i;
2628 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002629
2630 if (persist_data == NULL) {
2631 load_persistent_data();
2632 if (persist_data == NULL) {
2633 SLOGE("Getfield error, cannot load persistent data");
2634 goto out;
2635 }
2636 }
2637
Rubin Xu85c01f92014-10-13 12:49:54 +01002638 // Read value from persistent entries. If the original value is split into multiple entries,
2639 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002640 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002641 // 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 -07002642 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002643 // value too small
2644 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2645 goto out;
2646 }
2647 rc = CRYPTO_GETFIELD_OK;
2648
2649 for (i = 1; /* break explicitly */; i++) {
2650 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002651 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002652 // If the fieldname is very long, we stop as soon as it begins to overflow the
2653 // maximum field length. At this point we have in fact fully read out the original
2654 // value because cryptfs_setfield would not allow fields with longer names to be
2655 // written in the first place.
2656 break;
2657 }
2658 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002659 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2660 // value too small.
2661 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2662 goto out;
2663 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002664 } else {
2665 // Exhaust all entries.
2666 break;
2667 }
2668 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002669 } else {
2670 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002671 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002672 }
2673
2674out:
2675 return rc;
2676}
2677
2678/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002679int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002680 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002681 SLOGE("Cannot set field when file encrypted");
2682 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002683 }
2684
Ken Sumrall160b4d62013-04-22 12:15:39 -07002685 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002686 /* 0 is success, negative values are error */
2687 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002688 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002689 unsigned int field_id;
2690 char temp_field[PROPERTY_KEY_MAX];
2691 unsigned int num_entries;
2692 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002693
2694 if (persist_data == NULL) {
2695 load_persistent_data();
2696 if (persist_data == NULL) {
2697 SLOGE("Setfield error, cannot load persistent data");
2698 goto out;
2699 }
2700 }
2701
2702 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002703 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002704 encrypted = 1;
2705 }
2706
Rubin Xu85c01f92014-10-13 12:49:54 +01002707 // Compute the number of entries required to store value, each entry can store up to
2708 // (PROPERTY_VALUE_MAX - 1) chars
2709 if (strlen(value) == 0) {
2710 // Empty value also needs one entry to store.
2711 num_entries = 1;
2712 } else {
2713 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2714 }
2715
2716 max_keylen = strlen(fieldname);
2717 if (num_entries > 1) {
2718 // Need an extra "_%d" suffix.
2719 max_keylen += 1 + log10(num_entries);
2720 }
2721 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2722 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002723 goto out;
2724 }
2725
Rubin Xu85c01f92014-10-13 12:49:54 +01002726 // Make sure we have enough space to write the new value
2727 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2728 persist_get_max_entries(encrypted)) {
2729 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2730 goto out;
2731 }
2732
2733 // Now that we know persist_data has enough space for value, let's delete the old field first
2734 // to make up space.
2735 persist_del_keys(fieldname, 0);
2736
2737 if (persist_set_key(fieldname, value, encrypted)) {
2738 // fail to set key, should not happen as we have already checked the available space
2739 SLOGE("persist_set_key() error during setfield()");
2740 goto out;
2741 }
2742
2743 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002744 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002745
2746 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2747 // fail to set key, should not happen as we have already checked the available space.
2748 SLOGE("persist_set_key() error during setfield()");
2749 goto out;
2750 }
2751 }
2752
Ken Sumrall160b4d62013-04-22 12:15:39 -07002753 /* If we are running encrypted, save the persistent data now */
2754 if (encrypted) {
2755 if (save_persistent_data()) {
2756 SLOGE("Setfield error, cannot save persistent data");
2757 goto out;
2758 }
2759 }
2760
Rubin Xu85c01f92014-10-13 12:49:54 +01002761 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002762
2763out:
2764 return rc;
2765}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002766
2767/* Checks userdata. Attempt to mount the volume if default-
2768 * encrypted.
2769 * On success trigger next init phase and return 0.
2770 * Currently do not handle failure - see TODO below.
2771 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002772int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002773 int crypt_type = cryptfs_get_password_type();
2774 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2775 SLOGE("Bad crypt type - error");
2776 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002777 SLOGD(
2778 "Password is not default - "
2779 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002780 property_set("vold.decrypt", "trigger_restart_min_framework");
2781 return 0;
2782 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2783 SLOGD("Password is default - restarting filesystem");
2784 cryptfs_restart_internal(0);
2785 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002786 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002787 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002788 }
2789
Paul Lawrence6bfed202014-07-28 12:47:22 -07002790 /** Corrupt. Allow us to boot into framework, which will detect bad
2791 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002792 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002793 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002794 return 0;
2795}
2796
2797/* Returns type of the password, default, pattern, pin or password.
2798 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002799int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002800 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002801 SLOGE("cryptfs_get_password_type not valid for file encryption");
2802 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002803 }
2804
Paul Lawrencef4faa572014-01-29 13:31:03 -08002805 struct crypt_mnt_ftr crypt_ftr;
2806
2807 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2808 SLOGE("Error getting crypt footer and key\n");
2809 return -1;
2810 }
2811
Paul Lawrence6bfed202014-07-28 12:47:22 -07002812 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2813 return -1;
2814 }
2815
Paul Lawrencef4faa572014-01-29 13:31:03 -08002816 return crypt_ftr.crypt_type;
2817}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002818
Paul Crowley14c8c072018-09-18 13:30:21 -07002819const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002820 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002821 SLOGE("cryptfs_get_password not valid for file encryption");
2822 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002823 }
2824
Paul Lawrence399317e2014-03-10 13:20:50 -07002825 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002826 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002827 if (now.tv_sec < password_expiry_time) {
2828 return password;
2829 } else {
2830 cryptfs_clear_password();
2831 return 0;
2832 }
2833}
2834
Paul Crowley14c8c072018-09-18 13:30:21 -07002835void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002836 if (password) {
2837 size_t len = strlen(password);
2838 memset(password, 0, len);
2839 free(password);
2840 password = 0;
2841 password_expiry_time = 0;
2842 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002843}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002844
Paul Crowley14c8c072018-09-18 13:30:21 -07002845int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002846 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07002847 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07002848}