blob: 6e449ac965c47c9894e407fe0a36a28d9c2fa339 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
Logan Chiend557d762018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
Daniel Rosenberg65f99c92018-08-28 01:58:49 -070027#include "Checkpoint.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070029#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080030#include "Keymaster.h"
31#include "Process.h"
32#include "ScryptParameters.h"
33#include "VoldUtil.h"
34#include "VolumeManager.h"
35#include "secontext.h"
36
Logan Chien3f2b1222018-05-02 11:39:03 +080037#include <android-base/properties.h>
Logan Chiend557d762018-05-02 11:36:45 +080038#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080039#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080040#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070041#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070044#include <fscrypt/fscrypt.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080045#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080046#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080047#include <logwrap/logwrap.h>
48#include <openssl/evp.h>
49#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080050#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080051
52#include <ctype.h>
53#include <errno.h>
54#include <fcntl.h>
55#include <inttypes.h>
56#include <libgen.h>
57#include <linux/dm-ioctl.h>
58#include <linux/kdev_t.h>
59#include <math.h>
60#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
63#include <sys/ioctl.h>
64#include <sys/mount.h>
65#include <sys/param.h>
66#include <sys/stat.h>
67#include <sys/types.h>
68#include <sys/wait.h>
69#include <time.h>
70#include <unistd.h>
71
Wei Wang4375f1b2017-02-24 17:43:01 -080072extern "C" {
73#include <crypto_scrypt.h>
74}
Mark Salyzyn3e971272014-01-21 13:27:04 -080075
Mark Salyzyn5eecc442014-02-12 14:16:14 -080076#define UNUSED __attribute__((unused))
77
Ken Sumrall8f869aa2010-12-03 03:47:09 -080078#define DM_CRYPT_BUF_SIZE 4096
79
Jason parks70a4b3f2011-01-28 10:10:47 -060080#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080081
82constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
83constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070084constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080085
86// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070087static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060088
Paul Crowley14c8c072018-09-18 13:30:21 -070089#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070090
Paul Lawrence3bd36d52015-06-09 13:37:44 -070091#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080092
Paul Lawrence3d99eba2015-11-20 07:07:19 -080093#define CRYPTO_BLOCK_DEVICE "userdata"
94
95#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
96
Ken Sumrall29d8da82011-05-18 17:20:07 -070097#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070098#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070099
Ken Sumralle919efe2012-09-29 17:07:41 -0700100#define TABLE_LOAD_RETRIES 10
101
Shawn Willden47ba10d2014-09-03 17:07:06 -0600102#define RSA_KEY_SIZE 2048
103#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
104#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600105#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700106
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700107#define RETRY_MOUNT_ATTEMPTS 10
108#define RETRY_MOUNT_DELAY_SECONDS 1
109
Paul Crowley5afbc622017-11-27 09:42:17 -0800110#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
111
Paul Crowley73473332017-11-21 15:43:51 -0800112static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
113
Greg Kaiser59ad0182018-02-16 13:01:36 -0800114static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700115static char* saved_mount_point;
116static int master_key_saved = 0;
117static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800118
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700119/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700120static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000121 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700122}
123
124/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700125static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800126 if (ftr->keymaster_blob_size) {
127 SLOGI("Already have key");
128 return 0;
129 }
130
Paul Crowley14c8c072018-09-18 13:30:21 -0700131 int rc = keymaster_create_key_for_cryptfs_scrypt(
132 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
133 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000134 if (rc) {
135 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800136 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000137 ftr->keymaster_blob_size = 0;
138 }
139 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700140 return -1;
141 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000142 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700143}
144
Shawn Willdene17a9c42014-09-08 13:04:08 -0600145/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700146static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
147 const size_t object_size, unsigned char** signature,
148 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600149 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600150 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600151 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600152
Shawn Willdene17a9c42014-09-08 13:04:08 -0600153 // To sign a message with RSA, the message must satisfy two
154 // constraints:
155 //
156 // 1. The message, when interpreted as a big-endian numeric value, must
157 // be strictly less than the public modulus of the RSA key. Note
158 // that because the most significant bit of the public modulus is
159 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
160 // key), an n-bit message with most significant bit 0 always
161 // satisfies this requirement.
162 //
163 // 2. The message must have the same length in bits as the public
164 // modulus of the RSA key. This requirement isn't mathematically
165 // necessary, but is necessary to ensure consistency in
166 // implementations.
167 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600168 case KDF_SCRYPT_KEYMASTER:
169 // This ensures the most significant byte of the signed message
170 // is zero. We could have zero-padded to the left instead, but
171 // this approach is slightly more robust against changes in
172 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600173 // so) because we really should be using a proper deterministic
174 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800175 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600176 SLOGI("Signing safely-padded object");
177 break;
178 default:
179 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000180 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600181 }
Paul Crowley73473332017-11-21 15:43:51 -0800182 for (;;) {
183 auto result = keymaster_sign_object_for_cryptfs_scrypt(
184 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
185 to_sign_size, signature, signature_size);
186 switch (result) {
187 case KeymasterSignResult::ok:
188 return 0;
189 case KeymasterSignResult::upgrade:
190 break;
191 default:
192 return -1;
193 }
194 SLOGD("Upgrading key");
195 if (keymaster_upgrade_key_for_cryptfs_scrypt(
196 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
197 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
198 &ftr->keymaster_blob_size) != 0) {
199 SLOGE("Failed to upgrade key");
200 return -1;
201 }
202 if (put_crypt_ftr_and_key(ftr) != 0) {
203 SLOGE("Failed to write upgraded key to disk");
204 }
205 SLOGD("Key upgraded successfully");
206 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600207}
208
Paul Lawrence399317e2014-03-10 13:20:50 -0700209/* Store password when userdata is successfully decrypted and mounted.
210 * Cleared by cryptfs_clear_password
211 *
212 * To avoid a double prompt at boot, we need to store the CryptKeeper
213 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
214 * Since the entire framework is torn down and rebuilt after encryption,
215 * we have to use a daemon or similar to store the password. Since vold
216 * is secured against IPC except from system processes, it seems a reasonable
217 * place to store this.
218 *
219 * password should be cleared once it has been used.
220 *
221 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800222 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700223static char* password = 0;
224static int password_expiry_time = 0;
225static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800226
Paul Crowley14c8c072018-09-18 13:30:21 -0700227enum class RebootType { reboot, recovery, shutdown };
228static void cryptfs_reboot(RebootType rt) {
229 switch (rt) {
230 case RebootType::reboot:
231 property_set(ANDROID_RB_PROPERTY, "reboot");
232 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800233
Paul Crowley14c8c072018-09-18 13:30:21 -0700234 case RebootType::recovery:
235 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
236 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800237
Paul Crowley14c8c072018-09-18 13:30:21 -0700238 case RebootType::shutdown:
239 property_set(ANDROID_RB_PROPERTY, "shutdown");
240 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700241 }
Paul Lawrence87999172014-02-20 12:21:31 -0800242
Ken Sumralladfba362013-06-04 16:37:52 -0700243 sleep(20);
244
245 /* Shouldn't get here, reboot should happen before sleep times out */
246 return;
247}
248
Paul Crowley14c8c072018-09-18 13:30:21 -0700249static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800250 memset(io, 0, dataSize);
251 io->data_size = dataSize;
252 io->data_start = sizeof(struct dm_ioctl);
253 io->version[0] = 4;
254 io->version[1] = 0;
255 io->version[2] = 0;
256 io->flags = flags;
257 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100258 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800259 }
260}
261
Greg Kaiser38723f22018-02-16 13:35:35 -0800262namespace {
263
264struct CryptoType;
265
266// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700267const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800268
269struct CryptoType {
270 // We should only be constructing CryptoTypes as part of
271 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
272 // which isn't pure or fully protected as a concession to being able to
273 // do it all at compile time. Add new CryptoTypes in
274 // supported_crypto_types[] below.
275 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
276 constexpr CryptoType set_keysize(uint32_t size) const {
277 return CryptoType(this->property_name, this->crypto_name, size);
278 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700279 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800280 return CryptoType(property, this->crypto_name, this->keysize);
281 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700282 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800283 return CryptoType(this->property_name, crypto, this->keysize);
284 }
285
Paul Crowley14c8c072018-09-18 13:30:21 -0700286 constexpr const char* get_property_name() const { return property_name; }
287 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800288 constexpr uint32_t get_keysize() const { return keysize; }
289
Paul Crowley14c8c072018-09-18 13:30:21 -0700290 private:
291 const char* property_name;
292 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800293 uint32_t keysize;
294
Paul Crowley14c8c072018-09-18 13:30:21 -0700295 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800296 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700297 friend const CryptoType& get_crypto_type();
298 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800299};
300
301// We only want to parse this read-only property once. But we need to wait
302// until the system is initialized before we can read it. So we use a static
303// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700304const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800305 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
306 return crypto_type;
307}
308
309constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700310 .set_property_name("AES-128-CBC")
311 .set_crypto_name("aes-cbc-essiv:sha256")
312 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800313
314constexpr CryptoType supported_crypto_types[] = {
315 default_crypto_type,
Greg Kaiser38723f22018-02-16 13:35:35 -0800316 // Add new CryptoTypes here. Order is not important.
317};
318
Greg Kaiser38723f22018-02-16 13:35:35 -0800319// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
320// We confirm all supported_crypto_types have a small enough keysize and
321// had both set_property_name() and set_crypto_name() called.
322
323template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700324constexpr size_t array_length(T (&)[N]) {
325 return N;
326}
Greg Kaiser38723f22018-02-16 13:35:35 -0800327
328constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
329 return (index >= array_length(supported_crypto_types));
330}
331
Paul Crowley14c8c072018-09-18 13:30:21 -0700332constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800333 return ((crypto_type.get_property_name() != nullptr) &&
334 (crypto_type.get_crypto_name() != nullptr) &&
335 (crypto_type.get_keysize() <= MAX_KEY_LEN));
336}
337
338// Note in C++11 that constexpr functions can only have a single line.
339// So our code is a bit convoluted (using recursion instead of a loop),
340// but it's asserting at compile time that all of our key lengths are valid.
341constexpr bool validateSupportedCryptoTypes(size_t index) {
342 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700343 (isValidCryptoType(supported_crypto_types[index]) &&
344 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800345}
346
347static_assert(validateSupportedCryptoTypes(0),
348 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
349 "incompletely constructed.");
350// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
351
Greg Kaiser38723f22018-02-16 13:35:35 -0800352// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700353const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800354 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
355 char paramstr[PROPERTY_VALUE_MAX];
356
Paul Crowley14c8c072018-09-18 13:30:21 -0700357 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
358 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800359 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
360 return ctype;
361 }
362 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700363 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
364 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800365 return default_crypto_type;
366}
367
368} // namespace
369
Kenny Rootc4c70f12013-06-14 12:11:38 -0700370/**
371 * Gets the default device scrypt parameters for key derivation time tuning.
372 * The parameters should lead to about one second derivation time for the
373 * given device.
374 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700375static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700376 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000377 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700378
Paul Crowley63c18d32016-02-10 14:02:47 +0000379 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
380 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
381 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
382 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700383 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000384 ftr->N_factor = Nf;
385 ftr->r_factor = rf;
386 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700387}
388
Greg Kaiser57f9af62018-02-16 13:13:58 -0800389uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800390 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800391}
392
Paul Crowley14c8c072018-09-18 13:30:21 -0700393const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800394 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800395}
396
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200397static uint64_t get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800398 int fd, block_size;
399 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200400 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800401
Paul Crowley14c8c072018-09-18 13:30:21 -0700402 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800403 SLOGE("Cannot open device to get filesystem size ");
404 return 0;
405 }
406
407 if (lseek64(fd, 1024, SEEK_SET) < 0) {
408 SLOGE("Cannot seek to superblock");
409 return 0;
410 }
411
412 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
413 SLOGE("Cannot read superblock");
414 return 0;
415 }
416
417 close(fd);
418
Daniel Rosenberge82df162014-08-15 22:19:23 +0000419 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
420 SLOGE("Not a valid ext4 superblock");
421 return 0;
422 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800423 block_size = 1024 << sb.s_log_block_size;
424 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200425 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800426
427 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200428 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800429}
430
Paul Crowley14c8c072018-09-18 13:30:21 -0700431static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
432 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200433 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700434 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700435 char key_loc[PROPERTY_VALUE_MAX];
436 char real_blkdev[PROPERTY_VALUE_MAX];
437 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700438
Paul Crowley14c8c072018-09-18 13:30:21 -0700439 if (!cached_data) {
440 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700441
Paul Crowley14c8c072018-09-18 13:30:21 -0700442 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200443 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700444 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
445 * encryption info footer and key, and plenty of bytes to spare for future
446 * growth.
447 */
448 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200449 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700450 cached_data = 1;
451 } else {
452 SLOGE("Cannot get size of block device %s\n", real_blkdev);
453 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700454 } else {
455 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
456 cached_off = 0;
457 cached_data = 1;
458 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700459 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700460
Paul Crowley14c8c072018-09-18 13:30:21 -0700461 if (cached_data) {
462 if (metadata_fname) {
463 *metadata_fname = cached_metadata_fname;
464 }
465 if (off) {
466 *off = cached_off;
467 }
468 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700469 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700470
Paul Crowley14c8c072018-09-18 13:30:21 -0700471 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700472}
473
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800474/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700475static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800476 SHA256_CTX c;
477 SHA256_Init(&c);
478 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
479 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
480 SHA256_Final(crypt_ftr->sha256, &c);
481}
482
Ken Sumralle8744072011-01-18 22:01:55 -0800483/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800484 * update the failed mount count but not change the key.
485 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700486static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
487 int fd;
488 unsigned int cnt;
489 /* starting_off is set to the SEEK_SET offset
490 * where the crypto structure starts
491 */
492 off64_t starting_off;
493 int rc = -1;
494 char* fname = NULL;
495 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800496
Paul Crowley14c8c072018-09-18 13:30:21 -0700497 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800498
Paul Crowley14c8c072018-09-18 13:30:21 -0700499 if (get_crypt_ftr_info(&fname, &starting_off)) {
500 SLOGE("Unable to get crypt_ftr_info\n");
501 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800502 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700503 if (fname[0] != '/') {
504 SLOGE("Unexpected value for crypto key location\n");
505 return -1;
506 }
507 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
508 SLOGE("Cannot open footer file %s for put\n", fname);
509 return -1;
510 }
Ken Sumralle8744072011-01-18 22:01:55 -0800511
Paul Crowley14c8c072018-09-18 13:30:21 -0700512 /* Seek to the start of the crypt footer */
513 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
514 SLOGE("Cannot seek to real block device footer\n");
515 goto errout;
516 }
517
518 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
519 SLOGE("Cannot write real block device footer\n");
520 goto errout;
521 }
522
523 fstat(fd, &statbuf);
524 /* If the keys are kept on a raw block device, do not try to truncate it. */
525 if (S_ISREG(statbuf.st_mode)) {
526 if (ftruncate(fd, 0x4000)) {
527 SLOGE("Cannot set footer file size\n");
528 goto errout;
529 }
530 }
531
532 /* Success! */
533 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800534
535errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700536 close(fd);
537 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800538}
539
Paul Crowley14c8c072018-09-18 13:30:21 -0700540static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800541 struct crypt_mnt_ftr copy;
542 memcpy(&copy, crypt_ftr, sizeof(copy));
543 set_ftr_sha(&copy);
544 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
545}
546
Paul Crowley14c8c072018-09-18 13:30:21 -0700547static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700548 return TEMP_FAILURE_RETRY(read(fd, buff, len));
549}
550
Paul Crowley14c8c072018-09-18 13:30:21 -0700551static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700552 return TEMP_FAILURE_RETRY(write(fd, buff, len));
553}
554
Paul Crowley14c8c072018-09-18 13:30:21 -0700555static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700556 memset(pdata, 0, len);
557 pdata->persist_magic = PERSIST_DATA_MAGIC;
558 pdata->persist_valid_entries = 0;
559}
560
561/* A routine to update the passed in crypt_ftr to the lastest version.
562 * fd is open read/write on the device that holds the crypto footer and persistent
563 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
564 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
565 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700566static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700567 int orig_major = crypt_ftr->major_version;
568 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700569
Kenny Root7434b312013-06-14 11:29:53 -0700570 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700571 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700572 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700573
Kenny Rootc4c70f12013-06-14 12:11:38 -0700574 SLOGW("upgrading crypto footer to 1.1");
575
Paul Crowley14c8c072018-09-18 13:30:21 -0700576 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700577 if (pdata == NULL) {
578 SLOGE("Cannot allocate persisent data\n");
579 return;
580 }
581 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
582
583 /* Need to initialize the persistent data area */
584 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
585 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100586 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700587 return;
588 }
589 /* Write all zeros to the first copy, making it invalid */
590 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
591
592 /* Write a valid but empty structure to the second copy */
593 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
594 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
595
596 /* Update the footer */
597 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
598 crypt_ftr->persist_data_offset[0] = pdata_offset;
599 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
600 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100601 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700602 }
603
Paul Lawrencef4faa572014-01-29 13:31:03 -0800604 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700605 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800606 /* But keep the old kdf_type.
607 * It will get updated later to KDF_SCRYPT after the password has been verified.
608 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700609 crypt_ftr->kdf_type = KDF_PBKDF2;
610 get_device_scrypt_params(crypt_ftr);
611 crypt_ftr->minor_version = 2;
612 }
613
Paul Lawrencef4faa572014-01-29 13:31:03 -0800614 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
615 SLOGW("upgrading crypto footer to 1.3");
616 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
617 crypt_ftr->minor_version = 3;
618 }
619
Kenny Root7434b312013-06-14 11:29:53 -0700620 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
621 if (lseek64(fd, offset, SEEK_SET) == -1) {
622 SLOGE("Cannot seek to crypt footer\n");
623 return;
624 }
625 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700626 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700627}
628
Paul Crowley14c8c072018-09-18 13:30:21 -0700629static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
630 int fd;
631 unsigned int cnt;
632 off64_t starting_off;
633 int rc = -1;
634 char* fname = NULL;
635 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700636
Paul Crowley14c8c072018-09-18 13:30:21 -0700637 if (get_crypt_ftr_info(&fname, &starting_off)) {
638 SLOGE("Unable to get crypt_ftr_info\n");
639 return -1;
640 }
641 if (fname[0] != '/') {
642 SLOGE("Unexpected value for crypto key location\n");
643 return -1;
644 }
645 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
646 SLOGE("Cannot open footer file %s for get\n", fname);
647 return -1;
648 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800649
Paul Crowley14c8c072018-09-18 13:30:21 -0700650 /* Make sure it's 16 Kbytes in length */
651 fstat(fd, &statbuf);
652 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
653 SLOGE("footer file %s is not the expected size!\n", fname);
654 goto errout;
655 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700656
Paul Crowley14c8c072018-09-18 13:30:21 -0700657 /* Seek to the start of the crypt footer */
658 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
659 SLOGE("Cannot seek to real block device footer\n");
660 goto errout;
661 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700662
Paul Crowley14c8c072018-09-18 13:30:21 -0700663 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
664 SLOGE("Cannot read real block device footer\n");
665 goto errout;
666 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800667
Paul Crowley14c8c072018-09-18 13:30:21 -0700668 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
669 SLOGE("Bad magic for real block device %s\n", fname);
670 goto errout;
671 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800672
Paul Crowley14c8c072018-09-18 13:30:21 -0700673 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
674 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
675 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
676 goto errout;
677 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800678
Paul Crowley14c8c072018-09-18 13:30:21 -0700679 // We risk buffer overflows with oversized keys, so we just reject them.
680 // 0-sized keys are problematic (essentially by-passing encryption), and
681 // AES-CBC key wrapping only works for multiples of 16 bytes.
682 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
683 (crypt_ftr->keysize > MAX_KEY_LEN)) {
684 SLOGE(
685 "Invalid keysize (%u) for block device %s; Must be non-zero, "
686 "divisible by 16, and <= %d\n",
687 crypt_ftr->keysize, fname, MAX_KEY_LEN);
688 goto errout;
689 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800690
Paul Crowley14c8c072018-09-18 13:30:21 -0700691 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
692 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
693 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
694 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800695
Paul Crowley14c8c072018-09-18 13:30:21 -0700696 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
697 * copy on disk before returning.
698 */
699 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
700 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
701 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800702
Paul Crowley14c8c072018-09-18 13:30:21 -0700703 /* Success! */
704 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800705
706errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700707 close(fd);
708 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800709}
710
Paul Crowley14c8c072018-09-18 13:30:21 -0700711static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700712 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
713 crypt_ftr->persist_data_offset[1]) {
714 SLOGE("Crypt_ftr persist data regions overlap");
715 return -1;
716 }
717
718 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
719 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
720 return -1;
721 }
722
723 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700724 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700725 CRYPT_FOOTER_OFFSET) {
726 SLOGE("Persistent data extends past crypto footer");
727 return -1;
728 }
729
730 return 0;
731}
732
Paul Crowley14c8c072018-09-18 13:30:21 -0700733static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700734 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700735 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700736 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700737 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700738 int found = 0;
739 int fd;
740 int ret;
741 int i;
742
743 if (persist_data) {
744 /* Nothing to do, we've already loaded or initialized it */
745 return 0;
746 }
747
Ken Sumrall160b4d62013-04-22 12:15:39 -0700748 /* If not encrypted, just allocate an empty table and initialize it */
749 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700750 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800751 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700752 if (pdata) {
753 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
754 persist_data = pdata;
755 return 0;
756 }
757 return -1;
758 }
759
Paul Crowley14c8c072018-09-18 13:30:21 -0700760 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700761 return -1;
762 }
763
Paul Crowley14c8c072018-09-18 13:30:21 -0700764 if ((crypt_ftr.major_version < 1) ||
765 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700766 SLOGE("Crypt_ftr version doesn't support persistent data");
767 return -1;
768 }
769
770 if (get_crypt_ftr_info(&fname, NULL)) {
771 return -1;
772 }
773
774 ret = validate_persistent_data_storage(&crypt_ftr);
775 if (ret) {
776 return -1;
777 }
778
Paul Crowley14c8c072018-09-18 13:30:21 -0700779 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700780 if (fd < 0) {
781 SLOGE("Cannot open %s metadata file", fname);
782 return -1;
783 }
784
Wei Wang4375f1b2017-02-24 17:43:01 -0800785 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800786 if (pdata == NULL) {
787 SLOGE("Cannot allocate memory for persistent data");
788 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700789 }
790
791 for (i = 0; i < 2; i++) {
792 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
793 SLOGE("Cannot seek to read persistent data on %s", fname);
794 goto err2;
795 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700796 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700797 SLOGE("Error reading persistent data on iteration %d", i);
798 goto err2;
799 }
800 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
801 found = 1;
802 break;
803 }
804 }
805
806 if (!found) {
807 SLOGI("Could not find valid persistent data, creating");
808 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
809 }
810
811 /* Success */
812 persist_data = pdata;
813 close(fd);
814 return 0;
815
816err2:
817 free(pdata);
818
819err:
820 close(fd);
821 return -1;
822}
823
Paul Crowley14c8c072018-09-18 13:30:21 -0700824static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700825 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700826 struct crypt_persist_data* pdata;
827 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700828 off64_t write_offset;
829 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700830 int fd;
831 int ret;
832
833 if (persist_data == NULL) {
834 SLOGE("No persistent data to save");
835 return -1;
836 }
837
Paul Crowley14c8c072018-09-18 13:30:21 -0700838 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700839 return -1;
840 }
841
Paul Crowley14c8c072018-09-18 13:30:21 -0700842 if ((crypt_ftr.major_version < 1) ||
843 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700844 SLOGE("Crypt_ftr version doesn't support persistent data");
845 return -1;
846 }
847
848 ret = validate_persistent_data_storage(&crypt_ftr);
849 if (ret) {
850 return -1;
851 }
852
853 if (get_crypt_ftr_info(&fname, NULL)) {
854 return -1;
855 }
856
Paul Crowley14c8c072018-09-18 13:30:21 -0700857 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700858 if (fd < 0) {
859 SLOGE("Cannot open %s metadata file", fname);
860 return -1;
861 }
862
Wei Wang4375f1b2017-02-24 17:43:01 -0800863 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700864 if (pdata == NULL) {
865 SLOGE("Cannot allocate persistant data");
866 goto err;
867 }
868
869 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
870 SLOGE("Cannot seek to read persistent data on %s", fname);
871 goto err2;
872 }
873
874 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700875 SLOGE("Error reading persistent data before save");
876 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700877 }
878
879 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
880 /* The first copy is the curent valid copy, so write to
881 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700882 write_offset = crypt_ftr.persist_data_offset[1];
883 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700884 } else {
885 /* The second copy must be the valid copy, so write to
886 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700887 write_offset = crypt_ftr.persist_data_offset[0];
888 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700889 }
890
891 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100892 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700893 SLOGE("Cannot seek to write persistent data");
894 goto err2;
895 }
896 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700897 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100898 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700899 SLOGE("Cannot seek to erase previous persistent data");
900 goto err2;
901 }
902 fsync(fd);
903 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -0700904 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700905 SLOGE("Cannot write to erase previous persistent data");
906 goto err2;
907 }
908 fsync(fd);
909 } else {
910 SLOGE("Cannot write to save persistent data");
911 goto err2;
912 }
913
914 /* Success */
915 free(pdata);
916 close(fd);
917 return 0;
918
919err2:
920 free(pdata);
921err:
922 close(fd);
923 return -1;
924}
925
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800926/* Convert a binary key of specified length into an ascii hex string equivalent,
927 * without the leading 0x and with null termination
928 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700929static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
930 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700931 unsigned int i, a;
932 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800933
Paul Crowley14c8c072018-09-18 13:30:21 -0700934 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700935 /* For each byte, write out two ascii hex digits */
936 nibble = (master_key[i] >> 4) & 0xf;
937 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800938
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700939 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -0700940 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700941 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800942
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700943 /* Add the null termination */
944 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800945}
946
Paul Crowley14c8c072018-09-18 13:30:21 -0700947static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
948 const unsigned char* master_key, const char* real_blk_name,
949 const char* name, int fd, const char* extra_params) {
950 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
951 struct dm_ioctl* io;
952 struct dm_target_spec* tgt;
953 char* crypt_params;
954 // We need two ASCII characters to represent each byte, and need space for
955 // the '\0' terminator.
956 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
957 size_t buff_offset;
958 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800959
Paul Crowley14c8c072018-09-18 13:30:21 -0700960 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800961
Paul Crowley14c8c072018-09-18 13:30:21 -0700962 /* Load the mapping table for this device */
963 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800964
Paul Crowley14c8c072018-09-18 13:30:21 -0700965 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
966 io->target_count = 1;
967 tgt->status = 0;
968 tgt->sector_start = 0;
969 tgt->length = crypt_ftr->fs_size;
970 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800971
Paul Crowley14c8c072018-09-18 13:30:21 -0700972 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
973 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800974
Paul Crowley14c8c072018-09-18 13:30:21 -0700975 buff_offset = crypt_params - buffer;
976 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
977 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
978 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
979 crypt_params += strlen(crypt_params) + 1;
980 crypt_params =
981 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
982 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800983
Paul Crowley14c8c072018-09-18 13:30:21 -0700984 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
985 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
986 break;
987 }
988 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800989 }
Ken Sumralldb5e0262013-02-05 17:39:48 -0800990
Paul Crowley14c8c072018-09-18 13:30:21 -0700991 if (i == TABLE_LOAD_RETRIES) {
992 /* We failed to load the table, return an error */
993 return -1;
994 } else {
995 return i + 1;
996 }
Ken Sumralldb5e0262013-02-05 17:39:48 -0800997}
998
Paul Crowley14c8c072018-09-18 13:30:21 -0700999static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001000 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001001 struct dm_ioctl* io;
1002 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001003
Paul Crowley14c8c072018-09-18 13:30:21 -07001004 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001005
1006 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1007
1008 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1009 return -1;
1010 }
1011
1012 /* Iterate over the returned versions, looking for name of "crypt".
1013 * When found, get and return the version.
1014 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001015 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001016 while (v->next) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001017 if (!strcmp(v->name, "crypt")) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001018 /* We found the crypt driver, return the version, and get out */
1019 version[0] = v->version[0];
1020 version[1] = v->version[1];
1021 version[2] = v->version[2];
1022 return 0;
1023 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001024 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001025 }
1026
1027 return -1;
1028}
1029
Paul Crowley5afbc622017-11-27 09:42:17 -08001030static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1031 if (extra_params_vec.empty()) return "";
1032 std::string extra_params = std::to_string(extra_params_vec.size());
1033 for (const auto& p : extra_params_vec) {
1034 extra_params.append(" ");
1035 extra_params.append(p);
1036 }
1037 return extra_params;
1038}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001039
Paul Crowley5afbc622017-11-27 09:42:17 -08001040static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1041 const char* real_blk_name, char* crypto_blk_name, const char* name,
1042 uint32_t flags) {
1043 char buffer[DM_CRYPT_BUF_SIZE];
1044 struct dm_ioctl* io;
1045 unsigned int minor;
1046 int fd = 0;
1047 int err;
1048 int retval = -1;
1049 int version[3];
1050 int load_count;
1051 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001052
Paul Crowley5afbc622017-11-27 09:42:17 -08001053 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1054 SLOGE("Cannot open device-mapper\n");
1055 goto errout;
1056 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001057
Paul Crowley5afbc622017-11-27 09:42:17 -08001058 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001059
Paul Crowley5afbc622017-11-27 09:42:17 -08001060 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1061 err = ioctl(fd, DM_DEV_CREATE, io);
1062 if (err) {
1063 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1064 goto errout;
1065 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001066
Paul Crowley5afbc622017-11-27 09:42:17 -08001067 /* Get the device status, in particular, the name of it's device file */
1068 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1069 if (ioctl(fd, DM_DEV_STATUS, io)) {
1070 SLOGE("Cannot retrieve dm-crypt device status\n");
1071 goto errout;
1072 }
1073 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1074 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001075
Paul Crowley5afbc622017-11-27 09:42:17 -08001076 if (!get_dm_crypt_version(fd, name, version)) {
1077 /* Support for allow_discards was added in version 1.11.0 */
1078 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1079 extra_params_vec.emplace_back("allow_discards");
1080 }
1081 }
1082 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1083 extra_params_vec.emplace_back("allow_encrypt_override");
1084 }
1085 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1086 extra_params_as_string(extra_params_vec).c_str());
1087 if (load_count < 0) {
1088 SLOGE("Cannot load dm-crypt mapping table.\n");
1089 goto errout;
1090 } else if (load_count > 1) {
1091 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1092 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001093
Paul Crowley5afbc622017-11-27 09:42:17 -08001094 /* Resume this device to activate it */
1095 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001096
Paul Crowley5afbc622017-11-27 09:42:17 -08001097 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1098 SLOGE("Cannot resume the dm-crypt device\n");
1099 goto errout;
1100 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001101
Paul Crowley5afbc622017-11-27 09:42:17 -08001102 /* We made it here with no errors. Woot! */
1103 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001104
1105errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001106 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 -08001107
Paul Crowley14c8c072018-09-18 13:30:21 -07001108 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001109}
1110
Paul Crowley14c8c072018-09-18 13:30:21 -07001111static int delete_crypto_blk_dev(const char* name) {
1112 int fd;
1113 char buffer[DM_CRYPT_BUF_SIZE];
1114 struct dm_ioctl* io;
1115 int retval = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001116
Paul Crowley14c8c072018-09-18 13:30:21 -07001117 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1118 SLOGE("Cannot open device-mapper\n");
1119 goto errout;
1120 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121
Paul Crowley14c8c072018-09-18 13:30:21 -07001122 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001123
Paul Crowley14c8c072018-09-18 13:30:21 -07001124 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1125 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1126 SLOGE("Cannot remove dm-crypt device\n");
1127 goto errout;
1128 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001129
Paul Crowley14c8c072018-09-18 13:30:21 -07001130 /* We made it here with no errors. Woot! */
1131 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001132
1133errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001134 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 -08001135
Paul Crowley14c8c072018-09-18 13:30:21 -07001136 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001137}
1138
Paul Crowley14c8c072018-09-18 13:30:21 -07001139static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1140 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001141 SLOGI("Using pbkdf2 for cryptfs KDF");
1142
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001143 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001144 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1145 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001146}
1147
Paul Crowley14c8c072018-09-18 13:30:21 -07001148static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001149 SLOGI("Using scrypt for cryptfs KDF");
1150
Paul Crowley14c8c072018-09-18 13:30:21 -07001151 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001152
1153 int N = 1 << ftr->N_factor;
1154 int r = 1 << ftr->r_factor;
1155 int p = 1 << ftr->p_factor;
1156
1157 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001158 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001159 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001160
Paul Crowley14c8c072018-09-18 13:30:21 -07001161 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001162}
1163
Paul Crowley14c8c072018-09-18 13:30:21 -07001164static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1165 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001166 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1167
1168 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001169 size_t signature_size;
1170 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001171 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001172
1173 int N = 1 << ftr->N_factor;
1174 int r = 1 << ftr->r_factor;
1175 int p = 1 << ftr->p_factor;
1176
Paul Crowley14c8c072018-09-18 13:30:21 -07001177 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001178 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001179
1180 if (rc) {
1181 SLOGE("scrypt failed");
1182 return -1;
1183 }
1184
Paul Crowley14c8c072018-09-18 13:30:21 -07001185 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001186 SLOGE("Signing failed");
1187 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001188 }
1189
Paul Crowley14c8c072018-09-18 13:30:21 -07001190 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1191 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001192 free(signature);
1193
1194 if (rc) {
1195 SLOGE("scrypt failed");
1196 return -1;
1197 }
1198
1199 return 0;
1200}
1201
Paul Crowley14c8c072018-09-18 13:30:21 -07001202static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1203 const unsigned char* decrypted_master_key,
1204 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1205 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001206 EVP_CIPHER_CTX e_ctx;
1207 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001208 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001209
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001210 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001211 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001212
1213 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001214 case KDF_SCRYPT_KEYMASTER:
1215 if (keymaster_create_key(crypt_ftr)) {
1216 SLOGE("keymaster_create_key failed");
1217 return -1;
1218 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001219
Paul Crowley14c8c072018-09-18 13:30:21 -07001220 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1221 SLOGE("scrypt failed");
1222 return -1;
1223 }
1224 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001225
Paul Crowley14c8c072018-09-18 13:30:21 -07001226 case KDF_SCRYPT:
1227 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1228 SLOGE("scrypt failed");
1229 return -1;
1230 }
1231 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001232
Paul Crowley14c8c072018-09-18 13:30:21 -07001233 default:
1234 SLOGE("Invalid kdf_type");
1235 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001236 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001237
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001238 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001239 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001240 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1241 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001242 SLOGE("EVP_EncryptInit failed\n");
1243 return -1;
1244 }
1245 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001246
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001247 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001248 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1249 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001250 SLOGE("EVP_EncryptUpdate failed\n");
1251 return -1;
1252 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001253 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001254 SLOGE("EVP_EncryptFinal failed\n");
1255 return -1;
1256 }
1257
Greg Kaiser59ad0182018-02-16 13:01:36 -08001258 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1260 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001261 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001262
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001263 /* Store the scrypt of the intermediate key, so we can validate if it's a
1264 password error or mount error when things go wrong.
1265 Note there's no need to check for errors, since if this is incorrect, we
1266 simply won't wipe userdata, which is the correct default behavior
1267 */
1268 int N = 1 << crypt_ftr->N_factor;
1269 int r = 1 << crypt_ftr->r_factor;
1270 int p = 1 << crypt_ftr->p_factor;
1271
Paul Crowley14c8c072018-09-18 13:30:21 -07001272 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1273 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001274 sizeof(crypt_ftr->scrypted_intermediate_key));
1275
1276 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001277 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001278 }
1279
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001280 EVP_CIPHER_CTX_cleanup(&e_ctx);
1281
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001282 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001283}
1284
Paul Crowley14c8c072018-09-18 13:30:21 -07001285static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1286 const unsigned char* encrypted_master_key, size_t keysize,
1287 unsigned char* decrypted_master_key, kdf_func kdf,
1288 void* kdf_params, unsigned char** intermediate_key,
1289 size_t* intermediate_key_size) {
1290 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1291 EVP_CIPHER_CTX d_ctx;
1292 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001293
Paul Crowley14c8c072018-09-18 13:30:21 -07001294 /* Turn the password into an intermediate key and IV that can decrypt the
1295 master key */
1296 if (kdf(passwd, salt, ikey, kdf_params)) {
1297 SLOGE("kdf failed");
1298 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001299 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001300
Paul Crowley14c8c072018-09-18 13:30:21 -07001301 /* Initialize the decryption engine */
1302 EVP_CIPHER_CTX_init(&d_ctx);
1303 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1304 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1305 return -1;
1306 }
1307 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1308 /* Decrypt the master key */
1309 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1310 keysize)) {
1311 return -1;
1312 }
1313 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1314 return -1;
1315 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001316
Paul Crowley14c8c072018-09-18 13:30:21 -07001317 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1318 return -1;
1319 }
1320
1321 /* Copy intermediate key if needed by params */
1322 if (intermediate_key && intermediate_key_size) {
1323 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1324 if (*intermediate_key) {
1325 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1326 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1327 }
1328 }
1329
1330 EVP_CIPHER_CTX_cleanup(&d_ctx);
1331
1332 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001333}
1334
Paul Crowley14c8c072018-09-18 13:30:21 -07001335static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001336 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001337 *kdf = scrypt_keymaster;
1338 *kdf_params = ftr;
1339 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001340 *kdf = scrypt;
1341 *kdf_params = ftr;
1342 } else {
1343 *kdf = pbkdf2;
1344 *kdf_params = NULL;
1345 }
1346}
1347
Paul Crowley14c8c072018-09-18 13:30:21 -07001348static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1349 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1350 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001351 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001352 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001353 int ret;
1354
1355 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001356 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1357 decrypted_master_key, kdf, kdf_params, intermediate_key,
1358 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001359 if (ret != 0) {
1360 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001361 }
1362
1363 return ret;
1364}
1365
Paul Crowley14c8c072018-09-18 13:30:21 -07001366static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1367 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001368 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001369 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001370
1371 /* Get some random bits for a key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001372 fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001373 read(fd, key_buf, sizeof(key_buf));
1374 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001375 close(fd);
1376
1377 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001378 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001379}
1380
Paul Crowley14c8c072018-09-18 13:30:21 -07001381int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001382 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001383#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001384
1385 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001386 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001387 if (umount(mountpoint) == 0) {
1388 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001389 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001390
1391 if (errno == EINVAL) {
1392 /* EINVAL is returned if the directory is not a mountpoint,
1393 * i.e. there is no filesystem mounted there. So just get out.
1394 */
1395 break;
1396 }
1397
1398 err = errno;
1399
1400 /* If allowed, be increasingly aggressive before the last two retries */
1401 if (kill) {
1402 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1403 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001404 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001405 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1406 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001407 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001408 }
1409 }
1410
1411 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001412 }
1413
1414 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001415 SLOGD("unmounting %s succeeded\n", mountpoint);
1416 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001417 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001418 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1419 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1420 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001421 }
1422
1423 return rc;
1424}
1425
Paul Crowley14c8c072018-09-18 13:30:21 -07001426static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001427 // NOTE: post_fs_data results in init calling back around to vold, so all
1428 // callers to this method must be async
1429
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001430 /* Do the prep of the /data filesystem */
1431 property_set("vold.post_fs_data_done", "0");
1432 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001433 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001434
Ken Sumrallc5872692013-05-14 15:26:31 -07001435 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001436 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001437 /* We timed out to prep /data in time. Continue wait. */
1438 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001439 }
Wei Wang42e38102017-06-07 10:46:12 -07001440 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001441}
1442
Paul Crowley14c8c072018-09-18 13:30:21 -07001443static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001444 // Mark the footer as bad
1445 struct crypt_mnt_ftr crypt_ftr;
1446 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1447 SLOGE("Failed to get crypto footer - panic");
1448 return;
1449 }
1450
1451 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1452 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1453 SLOGE("Failed to set crypto footer - panic");
1454 return;
1455 }
1456}
1457
Paul Crowley14c8c072018-09-18 13:30:21 -07001458static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001459 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001460 SLOGE("Failed to mount tmpfs on data - panic");
1461 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001462 }
1463
1464 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1465 SLOGE("Failed to trigger post fs data - panic");
1466 return;
1467 }
1468
1469 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1470 SLOGE("Failed to trigger restart min framework - panic");
1471 return;
1472 }
1473}
1474
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001475/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001476static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001477 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001478 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001479 static int restart_successful = 0;
1480
1481 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001482 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001483 SLOGE("Encrypted filesystem not validated, aborting");
1484 return -1;
1485 }
1486
1487 if (restart_successful) {
1488 SLOGE("System already restarted with encrypted disk, aborting");
1489 return -1;
1490 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001491
Paul Lawrencef4faa572014-01-29 13:31:03 -08001492 if (restart_main) {
1493 /* Here is where we shut down the framework. The init scripts
1494 * start all services in one of three classes: core, main or late_start.
1495 * On boot, we start core and main. Now, we stop main, but not core,
1496 * as core includes vold and a few other really important things that
1497 * we need to keep running. Once main has stopped, we should be able
1498 * to umount the tmpfs /data, then mount the encrypted /data.
1499 * We then restart the class main, and also the class late_start.
1500 * At the moment, I've only put a few things in late_start that I know
1501 * are not needed to bring up the framework, and that also cause problems
1502 * with unmounting the tmpfs /data, but I hope to add add more services
1503 * to the late_start class as we optimize this to decrease the delay
1504 * till the user is asked for the password to the filesystem.
1505 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001506
Paul Lawrencef4faa572014-01-29 13:31:03 -08001507 /* The init files are setup to stop the class main when vold.decrypt is
1508 * set to trigger_reset_main.
1509 */
1510 property_set("vold.decrypt", "trigger_reset_main");
1511 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001512
Paul Lawrencef4faa572014-01-29 13:31:03 -08001513 /* Ugh, shutting down the framework is not synchronous, so until it
1514 * can be fixed, this horrible hack will wait a moment for it all to
1515 * shut down before proceeding. Without it, some devices cannot
1516 * restart the graphics services.
1517 */
1518 sleep(2);
1519 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001520
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521 /* Now that the framework is shutdown, we should be able to umount()
1522 * the tmpfs filesystem, and mount the real one.
1523 */
1524
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001525 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1526 if (strlen(crypto_blkdev) == 0) {
1527 SLOGE("fs_crypto_blkdev not set\n");
1528 return -1;
1529 }
1530
Paul Crowley14c8c072018-09-18 13:30:21 -07001531 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001532 /* If ro.crypto.readonly is set to 1, mount the decrypted
1533 * filesystem readonly. This is used when /data is mounted by
1534 * recovery mode.
1535 */
1536 char ro_prop[PROPERTY_VALUE_MAX];
1537 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001538 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001539 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001540 if (rec) {
1541 rec->flags |= MS_RDONLY;
1542 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001543 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001544
Ken Sumralle5032c42012-04-01 23:58:44 -07001545 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001546 int retries = RETRY_MOUNT_ATTEMPTS;
1547 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001548
1549 /*
1550 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1551 * partitions in the fsck domain.
1552 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001553 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001554 SLOGE("Failed to setexeccon");
1555 return -1;
1556 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001557 bool needs_cp = android::vold::cp_needsCheckpoint();
1558 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1559 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001560 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1561 /* TODO: invoke something similar to
1562 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1563 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001564 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001565 if (--retries) {
1566 sleep(RETRY_MOUNT_DELAY_SECONDS);
1567 } else {
1568 /* Let's hope that a reboot clears away whatever is keeping
1569 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001570 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001571 }
1572 } else {
1573 SLOGE("Failed to mount decrypted data");
1574 cryptfs_set_corrupt();
1575 cryptfs_trigger_restart_min_framework();
1576 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001577 if (setexeccon(NULL)) {
1578 SLOGE("Failed to setexeccon");
1579 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001580 return -1;
1581 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001582 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001583 if (setexeccon(NULL)) {
1584 SLOGE("Failed to setexeccon");
1585 return -1;
1586 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001587
Ken Sumralle5032c42012-04-01 23:58:44 -07001588 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001589 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001590 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001591
1592 /* startup service classes main and late_start */
1593 property_set("vold.decrypt", "trigger_restart_framework");
1594 SLOGD("Just triggered restart_framework\n");
1595
1596 /* Give it a few moments to get started */
1597 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598 }
1599
Ken Sumrall0cc16632011-01-18 20:32:26 -08001600 if (rc == 0) {
1601 restart_successful = 1;
1602 }
1603
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001604 return rc;
1605}
1606
Paul Crowley14c8c072018-09-18 13:30:21 -07001607int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001608 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001609 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001610 SLOGE("cryptfs_restart not valid for file encryption:");
1611 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001612 }
1613
Paul Lawrencef4faa572014-01-29 13:31:03 -08001614 /* Call internal implementation forcing a restart of main service group */
1615 return cryptfs_restart_internal(1);
1616}
1617
Paul Crowley14c8c072018-09-18 13:30:21 -07001618static int do_crypto_complete(const char* mount_point) {
1619 struct crypt_mnt_ftr crypt_ftr;
1620 char encrypted_state[PROPERTY_VALUE_MAX];
1621 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001622
Paul Crowley14c8c072018-09-18 13:30:21 -07001623 property_get("ro.crypto.state", encrypted_state, "");
1624 if (strcmp(encrypted_state, "encrypted")) {
1625 SLOGE("not running with encryption, aborting");
1626 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001627 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001628
Paul Crowley14c8c072018-09-18 13:30:21 -07001629 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001630 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001631 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1632 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001633
Paul Crowley14c8c072018-09-18 13:30:21 -07001634 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1635 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001636
Paul Crowley14c8c072018-09-18 13:30:21 -07001637 /*
1638 * Only report this error if key_loc is a file and it exists.
1639 * If the device was never encrypted, and /data is not mountable for
1640 * some reason, returning 1 should prevent the UI from presenting the
1641 * a "enter password" screen, or worse, a "press button to wipe the
1642 * device" screen.
1643 */
1644 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1645 SLOGE("master key file does not exist, aborting");
1646 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1647 } else {
1648 SLOGE("Error getting crypt footer and key\n");
1649 return CRYPTO_COMPLETE_BAD_METADATA;
1650 }
1651 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001652
Paul Crowley14c8c072018-09-18 13:30:21 -07001653 // Test for possible error flags
1654 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1655 SLOGE("Encryption process is partway completed\n");
1656 return CRYPTO_COMPLETE_PARTIAL;
1657 }
1658
1659 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1660 SLOGE("Encryption process was interrupted but cannot continue\n");
1661 return CRYPTO_COMPLETE_INCONSISTENT;
1662 }
1663
1664 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1665 SLOGE("Encryption is successful but data is corrupt\n");
1666 return CRYPTO_COMPLETE_CORRUPT;
1667 }
1668
1669 /* We passed the test! We shall diminish, and return to the west */
1670 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001671}
1672
Paul Crowley14c8c072018-09-18 13:30:21 -07001673static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1674 const char* mount_point, const char* label) {
1675 unsigned char decrypted_master_key[MAX_KEY_LEN];
1676 char crypto_blkdev[MAXPATHLEN];
1677 char real_blkdev[MAXPATHLEN];
1678 char tmp_mount_point[64];
1679 unsigned int orig_failed_decrypt_count;
1680 int rc;
1681 int use_keymaster = 0;
1682 int upgrade = 0;
1683 unsigned char* intermediate_key = 0;
1684 size_t intermediate_key_size = 0;
1685 int N = 1 << crypt_ftr->N_factor;
1686 int r = 1 << crypt_ftr->r_factor;
1687 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001688
Paul Crowley14c8c072018-09-18 13:30:21 -07001689 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1690 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001691
Paul Crowley14c8c072018-09-18 13:30:21 -07001692 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1693 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1694 &intermediate_key_size)) {
1695 SLOGE("Failed to decrypt master key\n");
1696 rc = -1;
1697 goto errout;
1698 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001699 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001700
Paul Crowley14c8c072018-09-18 13:30:21 -07001701 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001702
Paul Crowley14c8c072018-09-18 13:30:21 -07001703 // Create crypto block device - all (non fatal) code paths
1704 // need it
1705 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
1706 0)) {
1707 SLOGE("Error creating decrypted block device\n");
1708 rc = -1;
1709 goto errout;
1710 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001711
Paul Crowley14c8c072018-09-18 13:30:21 -07001712 /* Work out if the problem is the password or the data */
1713 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001714
Paul Crowley14c8c072018-09-18 13:30:21 -07001715 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1716 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1717 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001718
Paul Crowley14c8c072018-09-18 13:30:21 -07001719 // Does the key match the crypto footer?
1720 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1721 sizeof(scrypted_intermediate_key)) == 0) {
1722 SLOGI("Password matches");
1723 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001724 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001725 /* Try mounting the file system anyway, just in case the problem's with
1726 * the footer, not the key. */
1727 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1728 mkdir(tmp_mount_point, 0755);
1729 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1730 SLOGE("Error temp mounting decrypted block device\n");
1731 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001732
Paul Crowley14c8c072018-09-18 13:30:21 -07001733 rc = ++crypt_ftr->failed_decrypt_count;
1734 put_crypt_ftr_and_key(crypt_ftr);
1735 } else {
1736 /* Success! */
1737 SLOGI("Password did not match but decrypted drive mounted - continue");
1738 umount(tmp_mount_point);
1739 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001740 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001741 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001742
Paul Crowley14c8c072018-09-18 13:30:21 -07001743 if (rc == 0) {
1744 crypt_ftr->failed_decrypt_count = 0;
1745 if (orig_failed_decrypt_count != 0) {
1746 put_crypt_ftr_and_key(crypt_ftr);
1747 }
1748
1749 /* Save the name of the crypto block device
1750 * so we can mount it when restarting the framework. */
1751 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1752
1753 /* Also save a the master key so we can reencrypted the key
1754 * the key when we want to change the password on it. */
1755 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1756 saved_mount_point = strdup(mount_point);
1757 master_key_saved = 1;
1758 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1759 rc = 0;
1760
1761 // Upgrade if we're not using the latest KDF.
1762 use_keymaster = keymaster_check_compatibility();
1763 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1764 // Don't allow downgrade
1765 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1766 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1767 upgrade = 1;
1768 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1769 crypt_ftr->kdf_type = KDF_SCRYPT;
1770 upgrade = 1;
1771 }
1772
1773 if (upgrade) {
1774 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1775 crypt_ftr->master_key, crypt_ftr);
1776 if (!rc) {
1777 rc = put_crypt_ftr_and_key(crypt_ftr);
1778 }
1779 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1780
1781 // Do not fail even if upgrade failed - machine is bootable
1782 // Note that if this code is ever hit, there is a *serious* problem
1783 // since KDFs should never fail. You *must* fix the kdf before
1784 // proceeding!
1785 if (rc) {
1786 SLOGW(
1787 "Upgrade failed with error %d,"
1788 " but continuing with previous state",
1789 rc);
1790 rc = 0;
1791 }
1792 }
1793 }
1794
1795errout:
1796 if (intermediate_key) {
1797 memset(intermediate_key, 0, intermediate_key_size);
1798 free(intermediate_key);
1799 }
1800 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001801}
1802
Ken Sumrall29d8da82011-05-18 17:20:07 -07001803/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001804 * Called by vold when it's asked to mount an encrypted external
1805 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001806 * as any metadata is been stored in a separate, small partition. We
1807 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001808 *
1809 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001810 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001811int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1812 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001813 uint64_t nr_sec = 0;
1814 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001815 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001816 return -1;
1817 }
1818
Jeff Sharkey9c484982015-03-31 10:35:33 -07001819 struct crypt_mnt_ftr ext_crypt_ftr;
1820 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1821 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001822 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001823 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001824 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001825 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001826 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001827 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1828 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001829
Paul Crowley385cb8c2018-03-29 13:27:23 -07001830 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001831}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001832
Jeff Sharkey9c484982015-03-31 10:35:33 -07001833/*
1834 * Called by vold when it's asked to unmount an encrypted external
1835 * storage volume.
1836 */
1837int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001838 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001839}
1840
Paul Crowley14c8c072018-09-18 13:30:21 -07001841int cryptfs_crypto_complete(void) {
1842 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001843}
1844
Paul Crowley14c8c072018-09-18 13:30:21 -07001845int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001846 char encrypted_state[PROPERTY_VALUE_MAX];
1847 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001848 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1849 SLOGE(
1850 "encrypted fs already validated or not running with encryption,"
1851 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001852 return -1;
1853 }
1854
1855 if (get_crypt_ftr_and_key(crypt_ftr)) {
1856 SLOGE("Error getting crypt footer and key");
1857 return -1;
1858 }
1859
1860 return 0;
1861}
1862
Paul Crowley14c8c072018-09-18 13:30:21 -07001863int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001864 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001865 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001866 SLOGE("cryptfs_check_passwd not valid for file encryption");
1867 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001868 }
1869
Paul Lawrencef4faa572014-01-29 13:31:03 -08001870 struct crypt_mnt_ftr crypt_ftr;
1871 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001872
Paul Lawrencef4faa572014-01-29 13:31:03 -08001873 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001874 if (rc) {
1875 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001876 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001877 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001878
Paul Crowley14c8c072018-09-18 13:30:21 -07001879 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001880 if (rc) {
1881 SLOGE("Password did not match");
1882 return rc;
1883 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001884
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001885 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1886 // Here we have a default actual password but a real password
1887 // we must test against the scrypted value
1888 // First, we must delete the crypto block device that
1889 // test_mount_encrypted_fs leaves behind as a side effect
1890 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001891 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1892 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001893 if (rc) {
1894 SLOGE("Default password did not match on reboot encryption");
1895 return rc;
1896 }
1897
1898 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1899 put_crypt_ftr_and_key(&crypt_ftr);
1900 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1901 if (rc) {
1902 SLOGE("Could not change password on reboot encryption");
1903 return rc;
1904 }
1905 }
1906
1907 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001908 cryptfs_clear_password();
1909 password = strdup(passwd);
1910 struct timespec now;
1911 clock_gettime(CLOCK_BOOTTIME, &now);
1912 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001913 }
1914
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001915 return rc;
1916}
1917
Paul Crowley14c8c072018-09-18 13:30:21 -07001918int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001919 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001920 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001921 char encrypted_state[PROPERTY_VALUE_MAX];
1922 int rc;
1923
1924 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001925 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001926 SLOGE("device not encrypted, aborting");
1927 return -2;
1928 }
1929
1930 if (!master_key_saved) {
1931 SLOGE("encrypted fs not yet mounted, aborting");
1932 return -1;
1933 }
1934
1935 if (!saved_mount_point) {
1936 SLOGE("encrypted fs failed to save mount point, aborting");
1937 return -1;
1938 }
1939
Ken Sumrall160b4d62013-04-22 12:15:39 -07001940 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001941 SLOGE("Error getting crypt footer and key\n");
1942 return -1;
1943 }
1944
1945 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1946 /* If the device has no password, then just say the password is valid */
1947 rc = 0;
1948 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001949 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001950 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1951 /* They match, the password is correct */
1952 rc = 0;
1953 } else {
1954 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1955 sleep(1);
1956 rc = 1;
1957 }
1958 }
1959
1960 return rc;
1961}
1962
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001963/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08001964 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001965 * Presumably, at a minimum, the caller will update the
1966 * filesystem size and crypto_type_name after calling this function.
1967 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001968static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001969 off64_t off;
1970
1971 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001972 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001973 ftr->major_version = CURRENT_MAJOR_VERSION;
1974 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001975 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08001976 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07001977
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001978 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001979 case 1:
1980 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1981 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001982
Paul Crowley14c8c072018-09-18 13:30:21 -07001983 case 0:
1984 ftr->kdf_type = KDF_SCRYPT;
1985 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001986
Paul Crowley14c8c072018-09-18 13:30:21 -07001987 default:
1988 SLOGE("keymaster_check_compatibility failed");
1989 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001990 }
1991
Kenny Rootc4c70f12013-06-14 12:11:38 -07001992 get_device_scrypt_params(ftr);
1993
Ken Sumrall160b4d62013-04-22 12:15:39 -07001994 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1995 if (get_crypt_ftr_info(NULL, &off) == 0) {
1996 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07001997 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001998 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001999
2000 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002001}
2002
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002003#define FRAMEWORK_BOOT_WAIT 60
2004
Paul Crowley14c8c072018-09-18 13:30:21 -07002005static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2006 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002007 if (fd == -1) {
2008 SLOGE("Error opening file %s", filename);
2009 return -1;
2010 }
2011
2012 char block[CRYPT_INPLACE_BUFSIZE];
2013 memset(block, 0, sizeof(block));
2014 if (unix_read(fd, block, sizeof(block)) < 0) {
2015 SLOGE("Error reading file %s", filename);
2016 close(fd);
2017 return -1;
2018 }
2019
2020 close(fd);
2021
2022 SHA256_CTX c;
2023 SHA256_Init(&c);
2024 SHA256_Update(&c, block, sizeof(block));
2025 SHA256_Final(buf, &c);
2026
2027 return 0;
2028}
2029
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002030static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2031 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002032 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002033 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002034
Paul Lawrence87999172014-02-20 12:21:31 -08002035 /* The size of the userdata partition, and add in the vold volumes below */
2036 tot_encryption_size = crypt_ftr->fs_size;
2037
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002038 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002039 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002040
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002041 if (rc == ENABLE_INPLACE_ERR_DEV) {
2042 /* Hack for b/17898962 */
2043 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2044 cryptfs_reboot(RebootType::reboot);
2045 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002046
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002047 if (!rc) {
2048 crypt_ftr->encrypted_upto = cur_encryption_done;
2049 }
Paul Lawrence87999172014-02-20 12:21:31 -08002050
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002051 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2052 /* The inplace routine never actually sets the progress to 100% due
2053 * to the round down nature of integer division, so set it here */
2054 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002055 }
2056
2057 return rc;
2058}
2059
Paul Crowleyb64933a2017-10-31 08:25:55 -07002060static int vold_unmountAll(void) {
2061 VolumeManager* vm = VolumeManager::Instance();
2062 return vm->unmountAll();
2063}
2064
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002065int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002066 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002067 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002068 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002069 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002070 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002071 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002072 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002073 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002074 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002075 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002076 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002077 bool onlyCreateHeader = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002078
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002079 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002080 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2081 /* An encryption was underway and was interrupted */
2082 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2083 crypt_ftr.encrypted_upto = 0;
2084 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002085
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002086 /* At this point, we are in an inconsistent state. Until we successfully
2087 complete encryption, a reboot will leave us broken. So mark the
2088 encryption failed in case that happens.
2089 On successfully completing encryption, remove this flag */
2090 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002091
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002092 put_crypt_ftr_and_key(&crypt_ftr);
2093 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2094 if (!check_ftr_sha(&crypt_ftr)) {
2095 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2096 put_crypt_ftr_and_key(&crypt_ftr);
2097 goto error_unencrypted;
2098 }
2099
2100 /* Doing a reboot-encryption*/
2101 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2102 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2103 rebootEncryption = true;
2104 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002105 } else {
2106 // We don't want to accidentally reference invalid data.
2107 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002108 }
2109
2110 property_get("ro.crypto.state", encrypted_state, "");
2111 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2112 SLOGE("Device is already running encrypted, aborting");
2113 goto error_unencrypted;
2114 }
2115
2116 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002117 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2118 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002119
Ken Sumrall3ed82362011-01-28 23:31:16 -08002120 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002121 uint64_t nr_sec;
2122 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002123 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2124 goto error_unencrypted;
2125 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002126
2127 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002128 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002129 uint64_t fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002130 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002131 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002132
Paul Lawrence87999172014-02-20 12:21:31 -08002133 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002134
2135 if (fs_size_sec > max_fs_size_sec) {
2136 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2137 goto error_unencrypted;
2138 }
2139 }
2140
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002141 /* Get a wakelock as this may take a while, and we don't want the
2142 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2143 * wants to keep the screen on, it can grab a full wakelock.
2144 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002145 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002146 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2147
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002148 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002149 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002150 */
2151 property_set("vold.decrypt", "trigger_shutdown_framework");
2152 SLOGD("Just asked init to shut down class main\n");
2153
Jeff Sharkey9c484982015-03-31 10:35:33 -07002154 /* Ask vold to unmount all devices that it manages */
2155 if (vold_unmountAll()) {
2156 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002157 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002158
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002159 /* no_ui means we are being called from init, not settings.
2160 Now we always reboot from settings, so !no_ui means reboot
2161 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002162 if (!no_ui) {
2163 /* Try fallback, which is to reboot and try there */
2164 onlyCreateHeader = true;
2165 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2166 if (breadcrumb == 0) {
2167 SLOGE("Failed to create breadcrumb file");
2168 goto error_shutting_down;
2169 }
2170 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002171 }
2172
2173 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002174 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002175 /* Now that /data is unmounted, we need to mount a tmpfs
2176 * /data, set a property saying we're doing inplace encryption,
2177 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002178 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002179 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002180 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002181 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002182 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002183 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002184
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002185 /* restart the framework. */
2186 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002187 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002188
Ken Sumrall92736ef2012-10-17 20:57:14 -07002189 /* Ugh, shutting down the framework is not synchronous, so until it
2190 * can be fixed, this horrible hack will wait a moment for it all to
2191 * shut down before proceeding. Without it, some devices cannot
2192 * restart the graphics services.
2193 */
2194 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002195 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002196
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002197 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002198 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002199 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002200 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2201 goto error_shutting_down;
2202 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002203
Paul Lawrence87999172014-02-20 12:21:31 -08002204 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002205 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002206 } else {
2207 crypt_ftr.fs_size = nr_sec;
2208 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002209 /* At this point, we are in an inconsistent state. Until we successfully
2210 complete encryption, a reboot will leave us broken. So mark the
2211 encryption failed in case that happens.
2212 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002213 if (onlyCreateHeader) {
2214 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2215 } else {
2216 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2217 }
Paul Lawrence87999172014-02-20 12:21:31 -08002218 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002219 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2220 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002221
Paul Lawrence87999172014-02-20 12:21:31 -08002222 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002223 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2224 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002225 SLOGE("Cannot create encrypted master key\n");
2226 goto error_shutting_down;
2227 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002228
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002229 /* Replace scrypted intermediate key if we are preparing for a reboot */
2230 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002231 unsigned char fake_master_key[MAX_KEY_LEN];
2232 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002233 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002234 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2235 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002236 }
2237
Paul Lawrence87999172014-02-20 12:21:31 -08002238 /* Write the key to the end of the partition */
2239 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002240
Paul Lawrence87999172014-02-20 12:21:31 -08002241 /* If any persistent data has been remembered, save it.
2242 * If none, create a valid empty table and save that.
2243 */
2244 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002245 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2246 if (pdata) {
2247 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2248 persist_data = pdata;
2249 }
Paul Lawrence87999172014-02-20 12:21:31 -08002250 }
2251 if (persist_data) {
2252 save_persistent_data();
2253 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002254 }
2255
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002256 if (onlyCreateHeader) {
2257 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002258 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002259 }
2260
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002261 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002262 /* startup service classes main and late_start */
2263 property_set("vold.decrypt", "trigger_restart_min_framework");
2264 SLOGD("Just triggered restart_min_framework\n");
2265
2266 /* OK, the framework is restarted and will soon be showing a
2267 * progress bar. Time to setup an encrypted mapping, and
2268 * either write a new filesystem, or encrypt in place updating
2269 * the progress bar as we work.
2270 */
2271 }
2272
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002273 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002274 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002275 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002276
Paul Lawrence87999172014-02-20 12:21:31 -08002277 /* If we are continuing, check checksums match */
2278 rc = 0;
2279 if (previously_encrypted_upto) {
2280 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2281 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002282
Paul Crowley14c8c072018-09-18 13:30:21 -07002283 if (!rc &&
2284 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002285 SLOGE("Checksums do not match - trigger wipe");
2286 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002287 }
2288 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002289
Paul Lawrence87999172014-02-20 12:21:31 -08002290 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002291 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002292 previously_encrypted_upto);
2293 }
2294
2295 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002296 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002297 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002298 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002299 SLOGE("Error calculating checksum for continuing encryption");
2300 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002301 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002302 }
2303
2304 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002305 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002306
Paul Crowley14c8c072018-09-18 13:30:21 -07002307 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002308 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002309 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002310
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002311 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002312 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2313 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002314 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002315 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002316
Paul Lawrence6bfed202014-07-28 12:47:22 -07002317 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002318
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002319 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2320 char value[PROPERTY_VALUE_MAX];
2321 property_get("ro.crypto.state", value, "");
2322 if (!strcmp(value, "")) {
2323 /* default encryption - continue first boot sequence */
2324 property_set("ro.crypto.state", "encrypted");
2325 property_set("ro.crypto.type", "block");
2326 release_wake_lock(lockid);
2327 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2328 // Bring up cryptkeeper that will check the password and set it
2329 property_set("vold.decrypt", "trigger_shutdown_framework");
2330 sleep(2);
2331 property_set("vold.encrypt_progress", "");
2332 cryptfs_trigger_restart_min_framework();
2333 } else {
2334 cryptfs_check_passwd(DEFAULT_PASSWORD);
2335 cryptfs_restart_internal(1);
2336 }
2337 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002338 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002339 sleep(2); /* Give the UI a chance to show 100% progress */
2340 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002341 }
Paul Lawrence87999172014-02-20 12:21:31 -08002342 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002343 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002344 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002345 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002346 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002347 char value[PROPERTY_VALUE_MAX];
2348
Ken Sumrall319369a2012-06-27 16:30:18 -07002349 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002350 if (!strcmp(value, "1")) {
2351 /* wipe data if encryption failed */
2352 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002353 std::string err;
2354 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002355 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002356 if (!write_bootloader_message(options, &err)) {
2357 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002358 }
Josh Gaofec44372017-08-28 13:22:55 -07002359 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002360 } else {
2361 /* set property to trigger dialog */
2362 property_set("vold.encrypt_progress", "error_partially_encrypted");
2363 release_wake_lock(lockid);
2364 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002365 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002366 }
2367
Ken Sumrall3ed82362011-01-28 23:31:16 -08002368 /* hrm, the encrypt step claims success, but the reboot failed.
2369 * This should not happen.
2370 * Set the property and return. Hope the framework can deal with it.
2371 */
2372 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002373 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002374 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002375
2376error_unencrypted:
2377 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002378 if (lockid[0]) {
2379 release_wake_lock(lockid);
2380 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002381 return -1;
2382
2383error_shutting_down:
2384 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2385 * but the framework is stopped and not restarted to show the error, so it's up to
2386 * vold to restart the system.
2387 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002388 SLOGE(
2389 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2390 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002391 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002392
2393 /* shouldn't get here */
2394 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002395 if (lockid[0]) {
2396 release_wake_lock(lockid);
2397 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002398 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002399}
2400
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002401int cryptfs_enable(int type, const char* passwd, int no_ui) {
2402 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002403}
2404
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002405int cryptfs_enable_default(int no_ui) {
2406 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002407}
2408
Paul Crowley14c8c072018-09-18 13:30:21 -07002409int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002410 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002411 SLOGE("cryptfs_changepw not valid for file encryption");
2412 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002413 }
2414
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002415 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002416 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002417
2418 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002419 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002420 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002421 return -1;
2422 }
2423
Paul Lawrencef4faa572014-01-29 13:31:03 -08002424 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2425 SLOGE("Invalid crypt_type %d", crypt_type);
2426 return -1;
2427 }
2428
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002429 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002430 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002431 SLOGE("Error getting crypt footer and key");
2432 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002433 }
2434
Paul Lawrencef4faa572014-01-29 13:31:03 -08002435 crypt_ftr.crypt_type = crypt_type;
2436
Paul Crowley14c8c072018-09-18 13:30:21 -07002437 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2438 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002439 if (rc) {
2440 SLOGE("Encrypt master key failed: %d", rc);
2441 return -1;
2442 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002443 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002444 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002445
2446 return 0;
2447}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002448
Rubin Xu85c01f92014-10-13 12:49:54 +01002449static unsigned int persist_get_max_entries(int encrypted) {
2450 struct crypt_mnt_ftr crypt_ftr;
2451 unsigned int dsize;
2452 unsigned int max_persistent_entries;
2453
2454 /* If encrypted, use the values from the crypt_ftr, otherwise
2455 * use the values for the current spec.
2456 */
2457 if (encrypted) {
2458 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2459 return -1;
2460 }
2461 dsize = crypt_ftr.persist_data_size;
2462 } else {
2463 dsize = CRYPT_PERSIST_DATA_SIZE;
2464 }
2465
Paul Crowley14c8c072018-09-18 13:30:21 -07002466 max_persistent_entries =
2467 (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
Rubin Xu85c01f92014-10-13 12:49:54 +01002468
2469 return max_persistent_entries;
2470}
2471
Paul Crowley14c8c072018-09-18 13:30:21 -07002472static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002473 unsigned int i;
2474
2475 if (persist_data == NULL) {
2476 return -1;
2477 }
2478 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2479 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2480 /* We found it! */
2481 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2482 return 0;
2483 }
2484 }
2485
2486 return -1;
2487}
2488
Paul Crowley14c8c072018-09-18 13:30:21 -07002489static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002490 unsigned int i;
2491 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002492 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002493
2494 if (persist_data == NULL) {
2495 return -1;
2496 }
2497
Rubin Xu85c01f92014-10-13 12:49:54 +01002498 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002499
2500 num = persist_data->persist_valid_entries;
2501
2502 for (i = 0; i < num; i++) {
2503 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2504 /* We found an existing entry, update it! */
2505 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2506 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2507 return 0;
2508 }
2509 }
2510
2511 /* We didn't find it, add it to the end, if there is room */
2512 if (persist_data->persist_valid_entries < max_persistent_entries) {
2513 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2514 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2515 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2516 persist_data->persist_valid_entries++;
2517 return 0;
2518 }
2519
2520 return -1;
2521}
2522
Rubin Xu85c01f92014-10-13 12:49:54 +01002523/**
2524 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2525 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2526 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002527int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002528 std::string key_ = key;
2529 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002530
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002531 std::string parsed_field;
2532 unsigned parsed_index;
2533
2534 std::string::size_type split = key_.find_last_of('_');
2535 if (split == std::string::npos) {
2536 parsed_field = key_;
2537 parsed_index = 0;
2538 } else {
2539 parsed_field = key_.substr(0, split);
2540 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002541 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002542
2543 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002544}
2545
2546/*
2547 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2548 * remaining entries starting from index will be deleted.
2549 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2550 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2551 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2552 *
2553 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002554static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002555 unsigned int i;
2556 unsigned int j;
2557 unsigned int num;
2558
2559 if (persist_data == NULL) {
2560 return PERSIST_DEL_KEY_ERROR_OTHER;
2561 }
2562
2563 num = persist_data->persist_valid_entries;
2564
Paul Crowley14c8c072018-09-18 13:30:21 -07002565 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002566 // Filter out to-be-deleted entries in place.
2567 for (i = 0; i < num; i++) {
2568 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2569 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2570 j++;
2571 }
2572 }
2573
2574 if (j < num) {
2575 persist_data->persist_valid_entries = j;
2576 // Zeroise the remaining entries
2577 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2578 return PERSIST_DEL_KEY_OK;
2579 } else {
2580 // Did not find an entry matching the given fieldname
2581 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2582 }
2583}
2584
Paul Crowley14c8c072018-09-18 13:30:21 -07002585static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002586 unsigned int i;
2587 unsigned int count;
2588
2589 if (persist_data == NULL) {
2590 return -1;
2591 }
2592
2593 count = 0;
2594 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2595 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2596 count++;
2597 }
2598 }
2599
2600 return count;
2601}
2602
Ken Sumrall160b4d62013-04-22 12:15:39 -07002603/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002604int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002605 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002606 SLOGE("Cannot get field when file encrypted");
2607 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002608 }
2609
Ken Sumrall160b4d62013-04-22 12:15:39 -07002610 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002611 /* CRYPTO_GETFIELD_OK is success,
2612 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2613 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2614 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002615 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002616 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2617 int i;
2618 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002619
2620 if (persist_data == NULL) {
2621 load_persistent_data();
2622 if (persist_data == NULL) {
2623 SLOGE("Getfield error, cannot load persistent data");
2624 goto out;
2625 }
2626 }
2627
Rubin Xu85c01f92014-10-13 12:49:54 +01002628 // Read value from persistent entries. If the original value is split into multiple entries,
2629 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002630 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002631 // 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 -07002632 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002633 // value too small
2634 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2635 goto out;
2636 }
2637 rc = CRYPTO_GETFIELD_OK;
2638
2639 for (i = 1; /* break explicitly */; i++) {
2640 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002641 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002642 // If the fieldname is very long, we stop as soon as it begins to overflow the
2643 // maximum field length. At this point we have in fact fully read out the original
2644 // value because cryptfs_setfield would not allow fields with longer names to be
2645 // written in the first place.
2646 break;
2647 }
2648 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002649 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2650 // value too small.
2651 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2652 goto out;
2653 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002654 } else {
2655 // Exhaust all entries.
2656 break;
2657 }
2658 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002659 } else {
2660 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002661 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002662 }
2663
2664out:
2665 return rc;
2666}
2667
2668/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002669int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002670 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002671 SLOGE("Cannot set field when file encrypted");
2672 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002673 }
2674
Ken Sumrall160b4d62013-04-22 12:15:39 -07002675 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002676 /* 0 is success, negative values are error */
2677 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002678 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002679 unsigned int field_id;
2680 char temp_field[PROPERTY_KEY_MAX];
2681 unsigned int num_entries;
2682 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002683
2684 if (persist_data == NULL) {
2685 load_persistent_data();
2686 if (persist_data == NULL) {
2687 SLOGE("Setfield error, cannot load persistent data");
2688 goto out;
2689 }
2690 }
2691
2692 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002693 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002694 encrypted = 1;
2695 }
2696
Rubin Xu85c01f92014-10-13 12:49:54 +01002697 // Compute the number of entries required to store value, each entry can store up to
2698 // (PROPERTY_VALUE_MAX - 1) chars
2699 if (strlen(value) == 0) {
2700 // Empty value also needs one entry to store.
2701 num_entries = 1;
2702 } else {
2703 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2704 }
2705
2706 max_keylen = strlen(fieldname);
2707 if (num_entries > 1) {
2708 // Need an extra "_%d" suffix.
2709 max_keylen += 1 + log10(num_entries);
2710 }
2711 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2712 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002713 goto out;
2714 }
2715
Rubin Xu85c01f92014-10-13 12:49:54 +01002716 // Make sure we have enough space to write the new value
2717 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2718 persist_get_max_entries(encrypted)) {
2719 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2720 goto out;
2721 }
2722
2723 // Now that we know persist_data has enough space for value, let's delete the old field first
2724 // to make up space.
2725 persist_del_keys(fieldname, 0);
2726
2727 if (persist_set_key(fieldname, value, encrypted)) {
2728 // fail to set key, should not happen as we have already checked the available space
2729 SLOGE("persist_set_key() error during setfield()");
2730 goto out;
2731 }
2732
2733 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002734 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002735
2736 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2737 // fail to set key, should not happen as we have already checked the available space.
2738 SLOGE("persist_set_key() error during setfield()");
2739 goto out;
2740 }
2741 }
2742
Ken Sumrall160b4d62013-04-22 12:15:39 -07002743 /* If we are running encrypted, save the persistent data now */
2744 if (encrypted) {
2745 if (save_persistent_data()) {
2746 SLOGE("Setfield error, cannot save persistent data");
2747 goto out;
2748 }
2749 }
2750
Rubin Xu85c01f92014-10-13 12:49:54 +01002751 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002752
2753out:
2754 return rc;
2755}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002756
2757/* Checks userdata. Attempt to mount the volume if default-
2758 * encrypted.
2759 * On success trigger next init phase and return 0.
2760 * Currently do not handle failure - see TODO below.
2761 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002762int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002763 int crypt_type = cryptfs_get_password_type();
2764 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2765 SLOGE("Bad crypt type - error");
2766 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002767 SLOGD(
2768 "Password is not default - "
2769 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002770 property_set("vold.decrypt", "trigger_restart_min_framework");
2771 return 0;
2772 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2773 SLOGD("Password is default - restarting filesystem");
2774 cryptfs_restart_internal(0);
2775 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002776 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002777 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002778 }
2779
Paul Lawrence6bfed202014-07-28 12:47:22 -07002780 /** Corrupt. Allow us to boot into framework, which will detect bad
2781 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002782 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002783 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002784 return 0;
2785}
2786
2787/* Returns type of the password, default, pattern, pin or password.
2788 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002789int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002790 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002791 SLOGE("cryptfs_get_password_type not valid for file encryption");
2792 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002793 }
2794
Paul Lawrencef4faa572014-01-29 13:31:03 -08002795 struct crypt_mnt_ftr crypt_ftr;
2796
2797 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2798 SLOGE("Error getting crypt footer and key\n");
2799 return -1;
2800 }
2801
Paul Lawrence6bfed202014-07-28 12:47:22 -07002802 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2803 return -1;
2804 }
2805
Paul Lawrencef4faa572014-01-29 13:31:03 -08002806 return crypt_ftr.crypt_type;
2807}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002808
Paul Crowley14c8c072018-09-18 13:30:21 -07002809const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002810 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002811 SLOGE("cryptfs_get_password not valid for file encryption");
2812 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002813 }
2814
Paul Lawrence399317e2014-03-10 13:20:50 -07002815 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002816 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002817 if (now.tv_sec < password_expiry_time) {
2818 return password;
2819 } else {
2820 cryptfs_clear_password();
2821 return 0;
2822 }
2823}
2824
Paul Crowley14c8c072018-09-18 13:30:21 -07002825void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002826 if (password) {
2827 size_t len = strlen(password);
2828 memset(password, 0, len);
2829 free(password);
2830 password = 0;
2831 password_expiry_time = 0;
2832 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002833}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002834
Paul Crowley14c8c072018-09-18 13:30:21 -07002835int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002836 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07002837 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07002838}