blob: 383bbe8432444a52206b9877b23f19172fae1200 [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"
29#include "Ext4Crypt.h"
30#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>
Paul Crowley3b71fc52017-10-09 10:55:21 -070041#include <ext4_utils/ext4_crypt.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070042#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080043#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
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
Paul Crowley14c8c072018-09-18 13:30:21 -0700397static unsigned int get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800398 int fd, block_size;
399 struct ext4_super_block sb;
400 off64_t len;
401
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 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700425 len = (((off64_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 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700428 return (unsigned int)(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;
433 static off64_t cached_off = 0;
434 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
435 int fd;
436 char key_loc[PROPERTY_VALUE_MAX];
437 char real_blkdev[PROPERTY_VALUE_MAX];
438 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700439
Paul Crowley14c8c072018-09-18 13:30:21 -0700440 if (!cached_data) {
441 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700442
Paul Crowley14c8c072018-09-18 13:30:21 -0700443 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
444 if ((fd = open(real_blkdev, O_RDWR | O_CLOEXEC)) < 0) {
445 SLOGE("Cannot open real block device %s\n", real_blkdev);
446 return -1;
447 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700448
Paul Crowley14c8c072018-09-18 13:30:21 -0700449 unsigned long nr_sec = 0;
450 get_blkdev_size(fd, &nr_sec);
451 if (nr_sec != 0) {
452 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
453 * encryption info footer and key, and plenty of bytes to spare for future
454 * growth.
455 */
456 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
457 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
458 cached_data = 1;
459 } else {
460 SLOGE("Cannot get size of block device %s\n", real_blkdev);
461 }
462 close(fd);
463 } else {
464 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
465 cached_off = 0;
466 cached_data = 1;
467 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700468 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700469
Paul Crowley14c8c072018-09-18 13:30:21 -0700470 if (cached_data) {
471 if (metadata_fname) {
472 *metadata_fname = cached_metadata_fname;
473 }
474 if (off) {
475 *off = cached_off;
476 }
477 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700478 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700479
Paul Crowley14c8c072018-09-18 13:30:21 -0700480 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700481}
482
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800483/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700484static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800485 SHA256_CTX c;
486 SHA256_Init(&c);
487 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
488 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
489 SHA256_Final(crypt_ftr->sha256, &c);
490}
491
Ken Sumralle8744072011-01-18 22:01:55 -0800492/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800493 * update the failed mount count but not change the key.
494 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700495static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
496 int fd;
497 unsigned int cnt;
498 /* starting_off is set to the SEEK_SET offset
499 * where the crypto structure starts
500 */
501 off64_t starting_off;
502 int rc = -1;
503 char* fname = NULL;
504 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800505
Paul Crowley14c8c072018-09-18 13:30:21 -0700506 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800507
Paul Crowley14c8c072018-09-18 13:30:21 -0700508 if (get_crypt_ftr_info(&fname, &starting_off)) {
509 SLOGE("Unable to get crypt_ftr_info\n");
510 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800511 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700512 if (fname[0] != '/') {
513 SLOGE("Unexpected value for crypto key location\n");
514 return -1;
515 }
516 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
517 SLOGE("Cannot open footer file %s for put\n", fname);
518 return -1;
519 }
Ken Sumralle8744072011-01-18 22:01:55 -0800520
Paul Crowley14c8c072018-09-18 13:30:21 -0700521 /* Seek to the start of the crypt footer */
522 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
523 SLOGE("Cannot seek to real block device footer\n");
524 goto errout;
525 }
526
527 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
528 SLOGE("Cannot write real block device footer\n");
529 goto errout;
530 }
531
532 fstat(fd, &statbuf);
533 /* If the keys are kept on a raw block device, do not try to truncate it. */
534 if (S_ISREG(statbuf.st_mode)) {
535 if (ftruncate(fd, 0x4000)) {
536 SLOGE("Cannot set footer file size\n");
537 goto errout;
538 }
539 }
540
541 /* Success! */
542 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800543
544errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700545 close(fd);
546 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800547}
548
Paul Crowley14c8c072018-09-18 13:30:21 -0700549static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800550 struct crypt_mnt_ftr copy;
551 memcpy(&copy, crypt_ftr, sizeof(copy));
552 set_ftr_sha(&copy);
553 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
554}
555
Paul Crowley14c8c072018-09-18 13:30:21 -0700556static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700557 return TEMP_FAILURE_RETRY(read(fd, buff, len));
558}
559
Paul Crowley14c8c072018-09-18 13:30:21 -0700560static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700561 return TEMP_FAILURE_RETRY(write(fd, buff, len));
562}
563
Paul Crowley14c8c072018-09-18 13:30:21 -0700564static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700565 memset(pdata, 0, len);
566 pdata->persist_magic = PERSIST_DATA_MAGIC;
567 pdata->persist_valid_entries = 0;
568}
569
570/* A routine to update the passed in crypt_ftr to the lastest version.
571 * fd is open read/write on the device that holds the crypto footer and persistent
572 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
573 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
574 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700575static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700576 int orig_major = crypt_ftr->major_version;
577 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700578
Kenny Root7434b312013-06-14 11:29:53 -0700579 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700580 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700581 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700582
Kenny Rootc4c70f12013-06-14 12:11:38 -0700583 SLOGW("upgrading crypto footer to 1.1");
584
Paul Crowley14c8c072018-09-18 13:30:21 -0700585 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700586 if (pdata == NULL) {
587 SLOGE("Cannot allocate persisent data\n");
588 return;
589 }
590 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
591
592 /* Need to initialize the persistent data area */
593 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
594 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100595 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700596 return;
597 }
598 /* Write all zeros to the first copy, making it invalid */
599 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
600
601 /* Write a valid but empty structure to the second copy */
602 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
603 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
604
605 /* Update the footer */
606 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
607 crypt_ftr->persist_data_offset[0] = pdata_offset;
608 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
609 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100610 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700611 }
612
Paul Lawrencef4faa572014-01-29 13:31:03 -0800613 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700614 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800615 /* But keep the old kdf_type.
616 * It will get updated later to KDF_SCRYPT after the password has been verified.
617 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700618 crypt_ftr->kdf_type = KDF_PBKDF2;
619 get_device_scrypt_params(crypt_ftr);
620 crypt_ftr->minor_version = 2;
621 }
622
Paul Lawrencef4faa572014-01-29 13:31:03 -0800623 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
624 SLOGW("upgrading crypto footer to 1.3");
625 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
626 crypt_ftr->minor_version = 3;
627 }
628
Kenny Root7434b312013-06-14 11:29:53 -0700629 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
630 if (lseek64(fd, offset, SEEK_SET) == -1) {
631 SLOGE("Cannot seek to crypt footer\n");
632 return;
633 }
634 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700635 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700636}
637
Paul Crowley14c8c072018-09-18 13:30:21 -0700638static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
639 int fd;
640 unsigned int cnt;
641 off64_t starting_off;
642 int rc = -1;
643 char* fname = NULL;
644 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700645
Paul Crowley14c8c072018-09-18 13:30:21 -0700646 if (get_crypt_ftr_info(&fname, &starting_off)) {
647 SLOGE("Unable to get crypt_ftr_info\n");
648 return -1;
649 }
650 if (fname[0] != '/') {
651 SLOGE("Unexpected value for crypto key location\n");
652 return -1;
653 }
654 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
655 SLOGE("Cannot open footer file %s for get\n", fname);
656 return -1;
657 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800658
Paul Crowley14c8c072018-09-18 13:30:21 -0700659 /* Make sure it's 16 Kbytes in length */
660 fstat(fd, &statbuf);
661 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
662 SLOGE("footer file %s is not the expected size!\n", fname);
663 goto errout;
664 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700665
Paul Crowley14c8c072018-09-18 13:30:21 -0700666 /* Seek to the start of the crypt footer */
667 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
668 SLOGE("Cannot seek to real block device footer\n");
669 goto errout;
670 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700671
Paul Crowley14c8c072018-09-18 13:30:21 -0700672 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
673 SLOGE("Cannot read real block device footer\n");
674 goto errout;
675 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800676
Paul Crowley14c8c072018-09-18 13:30:21 -0700677 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
678 SLOGE("Bad magic for real block device %s\n", fname);
679 goto errout;
680 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800681
Paul Crowley14c8c072018-09-18 13:30:21 -0700682 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
683 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
684 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
685 goto errout;
686 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800687
Paul Crowley14c8c072018-09-18 13:30:21 -0700688 // We risk buffer overflows with oversized keys, so we just reject them.
689 // 0-sized keys are problematic (essentially by-passing encryption), and
690 // AES-CBC key wrapping only works for multiples of 16 bytes.
691 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
692 (crypt_ftr->keysize > MAX_KEY_LEN)) {
693 SLOGE(
694 "Invalid keysize (%u) for block device %s; Must be non-zero, "
695 "divisible by 16, and <= %d\n",
696 crypt_ftr->keysize, fname, MAX_KEY_LEN);
697 goto errout;
698 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800699
Paul Crowley14c8c072018-09-18 13:30:21 -0700700 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
701 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
702 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
703 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800704
Paul Crowley14c8c072018-09-18 13:30:21 -0700705 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
706 * copy on disk before returning.
707 */
708 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
709 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
710 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800711
Paul Crowley14c8c072018-09-18 13:30:21 -0700712 /* Success! */
713 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800714
715errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700716 close(fd);
717 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800718}
719
Paul Crowley14c8c072018-09-18 13:30:21 -0700720static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700721 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
722 crypt_ftr->persist_data_offset[1]) {
723 SLOGE("Crypt_ftr persist data regions overlap");
724 return -1;
725 }
726
727 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
728 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
729 return -1;
730 }
731
732 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700733 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700734 CRYPT_FOOTER_OFFSET) {
735 SLOGE("Persistent data extends past crypto footer");
736 return -1;
737 }
738
739 return 0;
740}
741
Paul Crowley14c8c072018-09-18 13:30:21 -0700742static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700743 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700744 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700745 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700746 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700747 int found = 0;
748 int fd;
749 int ret;
750 int i;
751
752 if (persist_data) {
753 /* Nothing to do, we've already loaded or initialized it */
754 return 0;
755 }
756
Ken Sumrall160b4d62013-04-22 12:15:39 -0700757 /* If not encrypted, just allocate an empty table and initialize it */
758 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700759 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800760 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700761 if (pdata) {
762 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
763 persist_data = pdata;
764 return 0;
765 }
766 return -1;
767 }
768
Paul Crowley14c8c072018-09-18 13:30:21 -0700769 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700770 return -1;
771 }
772
Paul Crowley14c8c072018-09-18 13:30:21 -0700773 if ((crypt_ftr.major_version < 1) ||
774 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700775 SLOGE("Crypt_ftr version doesn't support persistent data");
776 return -1;
777 }
778
779 if (get_crypt_ftr_info(&fname, NULL)) {
780 return -1;
781 }
782
783 ret = validate_persistent_data_storage(&crypt_ftr);
784 if (ret) {
785 return -1;
786 }
787
Paul Crowley14c8c072018-09-18 13:30:21 -0700788 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700789 if (fd < 0) {
790 SLOGE("Cannot open %s metadata file", fname);
791 return -1;
792 }
793
Wei Wang4375f1b2017-02-24 17:43:01 -0800794 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800795 if (pdata == NULL) {
796 SLOGE("Cannot allocate memory for persistent data");
797 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700798 }
799
800 for (i = 0; i < 2; i++) {
801 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
802 SLOGE("Cannot seek to read persistent data on %s", fname);
803 goto err2;
804 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700805 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700806 SLOGE("Error reading persistent data on iteration %d", i);
807 goto err2;
808 }
809 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
810 found = 1;
811 break;
812 }
813 }
814
815 if (!found) {
816 SLOGI("Could not find valid persistent data, creating");
817 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
818 }
819
820 /* Success */
821 persist_data = pdata;
822 close(fd);
823 return 0;
824
825err2:
826 free(pdata);
827
828err:
829 close(fd);
830 return -1;
831}
832
Paul Crowley14c8c072018-09-18 13:30:21 -0700833static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700834 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700835 struct crypt_persist_data* pdata;
836 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700837 off64_t write_offset;
838 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700839 int fd;
840 int ret;
841
842 if (persist_data == NULL) {
843 SLOGE("No persistent data to save");
844 return -1;
845 }
846
Paul Crowley14c8c072018-09-18 13:30:21 -0700847 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700848 return -1;
849 }
850
Paul Crowley14c8c072018-09-18 13:30:21 -0700851 if ((crypt_ftr.major_version < 1) ||
852 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700853 SLOGE("Crypt_ftr version doesn't support persistent data");
854 return -1;
855 }
856
857 ret = validate_persistent_data_storage(&crypt_ftr);
858 if (ret) {
859 return -1;
860 }
861
862 if (get_crypt_ftr_info(&fname, NULL)) {
863 return -1;
864 }
865
Paul Crowley14c8c072018-09-18 13:30:21 -0700866 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700867 if (fd < 0) {
868 SLOGE("Cannot open %s metadata file", fname);
869 return -1;
870 }
871
Wei Wang4375f1b2017-02-24 17:43:01 -0800872 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700873 if (pdata == NULL) {
874 SLOGE("Cannot allocate persistant data");
875 goto err;
876 }
877
878 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
879 SLOGE("Cannot seek to read persistent data on %s", fname);
880 goto err2;
881 }
882
883 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700884 SLOGE("Error reading persistent data before save");
885 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700886 }
887
888 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
889 /* The first copy is the curent valid copy, so write to
890 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700891 write_offset = crypt_ftr.persist_data_offset[1];
892 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700893 } else {
894 /* The second copy must be the valid copy, so write to
895 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700896 write_offset = crypt_ftr.persist_data_offset[0];
897 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700898 }
899
900 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100901 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700902 SLOGE("Cannot seek to write persistent data");
903 goto err2;
904 }
905 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700906 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100907 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700908 SLOGE("Cannot seek to erase previous persistent data");
909 goto err2;
910 }
911 fsync(fd);
912 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -0700913 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700914 SLOGE("Cannot write to erase previous persistent data");
915 goto err2;
916 }
917 fsync(fd);
918 } else {
919 SLOGE("Cannot write to save persistent data");
920 goto err2;
921 }
922
923 /* Success */
924 free(pdata);
925 close(fd);
926 return 0;
927
928err2:
929 free(pdata);
930err:
931 close(fd);
932 return -1;
933}
934
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800935/* Convert a binary key of specified length into an ascii hex string equivalent,
936 * without the leading 0x and with null termination
937 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700938static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
939 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700940 unsigned int i, a;
941 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800942
Paul Crowley14c8c072018-09-18 13:30:21 -0700943 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700944 /* For each byte, write out two ascii hex digits */
945 nibble = (master_key[i] >> 4) & 0xf;
946 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800947
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700948 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -0700949 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700950 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800951
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700952 /* Add the null termination */
953 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800954}
955
Paul Crowley14c8c072018-09-18 13:30:21 -0700956static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
957 const unsigned char* master_key, const char* real_blk_name,
958 const char* name, int fd, const char* extra_params) {
959 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
960 struct dm_ioctl* io;
961 struct dm_target_spec* tgt;
962 char* crypt_params;
963 // We need two ASCII characters to represent each byte, and need space for
964 // the '\0' terminator.
965 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
966 size_t buff_offset;
967 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800968
Paul Crowley14c8c072018-09-18 13:30:21 -0700969 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800970
Paul Crowley14c8c072018-09-18 13:30:21 -0700971 /* Load the mapping table for this device */
972 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800973
Paul Crowley14c8c072018-09-18 13:30:21 -0700974 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
975 io->target_count = 1;
976 tgt->status = 0;
977 tgt->sector_start = 0;
978 tgt->length = crypt_ftr->fs_size;
979 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800980
Paul Crowley14c8c072018-09-18 13:30:21 -0700981 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
982 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800983
Paul Crowley14c8c072018-09-18 13:30:21 -0700984 buff_offset = crypt_params - buffer;
985 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
986 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
987 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
988 crypt_params += strlen(crypt_params) + 1;
989 crypt_params =
990 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
991 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800992
Paul Crowley14c8c072018-09-18 13:30:21 -0700993 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
994 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
995 break;
996 }
997 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800998 }
Ken Sumralldb5e0262013-02-05 17:39:48 -0800999
Paul Crowley14c8c072018-09-18 13:30:21 -07001000 if (i == TABLE_LOAD_RETRIES) {
1001 /* We failed to load the table, return an error */
1002 return -1;
1003 } else {
1004 return i + 1;
1005 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001006}
1007
Paul Crowley14c8c072018-09-18 13:30:21 -07001008static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001009 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001010 struct dm_ioctl* io;
1011 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001012
Paul Crowley14c8c072018-09-18 13:30:21 -07001013 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001014
1015 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1016
1017 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1018 return -1;
1019 }
1020
1021 /* Iterate over the returned versions, looking for name of "crypt".
1022 * When found, get and return the version.
1023 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001024 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001025 while (v->next) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001026 if (!strcmp(v->name, "crypt")) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001027 /* We found the crypt driver, return the version, and get out */
1028 version[0] = v->version[0];
1029 version[1] = v->version[1];
1030 version[2] = v->version[2];
1031 return 0;
1032 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001033 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001034 }
1035
1036 return -1;
1037}
1038
Paul Crowley5afbc622017-11-27 09:42:17 -08001039static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1040 if (extra_params_vec.empty()) return "";
1041 std::string extra_params = std::to_string(extra_params_vec.size());
1042 for (const auto& p : extra_params_vec) {
1043 extra_params.append(" ");
1044 extra_params.append(p);
1045 }
1046 return extra_params;
1047}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001048
Paul Crowley5afbc622017-11-27 09:42:17 -08001049static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1050 const char* real_blk_name, char* crypto_blk_name, const char* name,
1051 uint32_t flags) {
1052 char buffer[DM_CRYPT_BUF_SIZE];
1053 struct dm_ioctl* io;
1054 unsigned int minor;
1055 int fd = 0;
1056 int err;
1057 int retval = -1;
1058 int version[3];
1059 int load_count;
1060 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001061
Paul Crowley5afbc622017-11-27 09:42:17 -08001062 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1063 SLOGE("Cannot open device-mapper\n");
1064 goto errout;
1065 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001066
Paul Crowley5afbc622017-11-27 09:42:17 -08001067 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001068
Paul Crowley5afbc622017-11-27 09:42:17 -08001069 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1070 err = ioctl(fd, DM_DEV_CREATE, io);
1071 if (err) {
1072 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1073 goto errout;
1074 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001075
Paul Crowley5afbc622017-11-27 09:42:17 -08001076 /* Get the device status, in particular, the name of it's device file */
1077 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1078 if (ioctl(fd, DM_DEV_STATUS, io)) {
1079 SLOGE("Cannot retrieve dm-crypt device status\n");
1080 goto errout;
1081 }
1082 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1083 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001084
Paul Crowley5afbc622017-11-27 09:42:17 -08001085 if (!get_dm_crypt_version(fd, name, version)) {
1086 /* Support for allow_discards was added in version 1.11.0 */
1087 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1088 extra_params_vec.emplace_back("allow_discards");
1089 }
1090 }
1091 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1092 extra_params_vec.emplace_back("allow_encrypt_override");
1093 }
1094 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1095 extra_params_as_string(extra_params_vec).c_str());
1096 if (load_count < 0) {
1097 SLOGE("Cannot load dm-crypt mapping table.\n");
1098 goto errout;
1099 } else if (load_count > 1) {
1100 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1101 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001102
Paul Crowley5afbc622017-11-27 09:42:17 -08001103 /* Resume this device to activate it */
1104 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001105
Paul Crowley5afbc622017-11-27 09:42:17 -08001106 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1107 SLOGE("Cannot resume the dm-crypt device\n");
1108 goto errout;
1109 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001110
Paul Crowley5afbc622017-11-27 09:42:17 -08001111 /* We made it here with no errors. Woot! */
1112 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001113
1114errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001115 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001116
Paul Crowley14c8c072018-09-18 13:30:21 -07001117 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001118}
1119
Paul Crowley14c8c072018-09-18 13:30:21 -07001120static int delete_crypto_blk_dev(const char* name) {
1121 int fd;
1122 char buffer[DM_CRYPT_BUF_SIZE];
1123 struct dm_ioctl* io;
1124 int retval = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125
Paul Crowley14c8c072018-09-18 13:30:21 -07001126 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1127 SLOGE("Cannot open device-mapper\n");
1128 goto errout;
1129 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001130
Paul Crowley14c8c072018-09-18 13:30:21 -07001131 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001132
Paul Crowley14c8c072018-09-18 13:30:21 -07001133 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1134 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1135 SLOGE("Cannot remove dm-crypt device\n");
1136 goto errout;
1137 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001138
Paul Crowley14c8c072018-09-18 13:30:21 -07001139 /* We made it here with no errors. Woot! */
1140 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001141
1142errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001143 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001144
Paul Crowley14c8c072018-09-18 13:30:21 -07001145 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001146}
1147
Paul Crowley14c8c072018-09-18 13:30:21 -07001148static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1149 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001150 SLOGI("Using pbkdf2 for cryptfs KDF");
1151
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001152 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001153 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1154 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001155}
1156
Paul Crowley14c8c072018-09-18 13:30:21 -07001157static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001158 SLOGI("Using scrypt for cryptfs KDF");
1159
Paul Crowley14c8c072018-09-18 13:30:21 -07001160 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001161
1162 int N = 1 << ftr->N_factor;
1163 int r = 1 << ftr->r_factor;
1164 int p = 1 << ftr->p_factor;
1165
1166 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001167 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001168 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001169
Paul Crowley14c8c072018-09-18 13:30:21 -07001170 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001171}
1172
Paul Crowley14c8c072018-09-18 13:30:21 -07001173static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1174 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001175 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1176
1177 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001178 size_t signature_size;
1179 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001180 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001181
1182 int N = 1 << ftr->N_factor;
1183 int r = 1 << ftr->r_factor;
1184 int p = 1 << ftr->p_factor;
1185
Paul Crowley14c8c072018-09-18 13:30:21 -07001186 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001187 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001188
1189 if (rc) {
1190 SLOGE("scrypt failed");
1191 return -1;
1192 }
1193
Paul Crowley14c8c072018-09-18 13:30:21 -07001194 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001195 SLOGE("Signing failed");
1196 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001197 }
1198
Paul Crowley14c8c072018-09-18 13:30:21 -07001199 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1200 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001201 free(signature);
1202
1203 if (rc) {
1204 SLOGE("scrypt failed");
1205 return -1;
1206 }
1207
1208 return 0;
1209}
1210
Paul Crowley14c8c072018-09-18 13:30:21 -07001211static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1212 const unsigned char* decrypted_master_key,
1213 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1214 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001215 EVP_CIPHER_CTX e_ctx;
1216 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001217 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001218
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001219 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001220 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001221
1222 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001223 case KDF_SCRYPT_KEYMASTER:
1224 if (keymaster_create_key(crypt_ftr)) {
1225 SLOGE("keymaster_create_key failed");
1226 return -1;
1227 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001228
Paul Crowley14c8c072018-09-18 13:30:21 -07001229 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1230 SLOGE("scrypt failed");
1231 return -1;
1232 }
1233 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001234
Paul Crowley14c8c072018-09-18 13:30:21 -07001235 case KDF_SCRYPT:
1236 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1237 SLOGE("scrypt failed");
1238 return -1;
1239 }
1240 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001241
Paul Crowley14c8c072018-09-18 13:30:21 -07001242 default:
1243 SLOGE("Invalid kdf_type");
1244 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001245 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001246
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001247 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001248 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001249 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1250 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251 SLOGE("EVP_EncryptInit failed\n");
1252 return -1;
1253 }
1254 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001255
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001256 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001257 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1258 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259 SLOGE("EVP_EncryptUpdate failed\n");
1260 return -1;
1261 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001262 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001263 SLOGE("EVP_EncryptFinal failed\n");
1264 return -1;
1265 }
1266
Greg Kaiser59ad0182018-02-16 13:01:36 -08001267 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001268 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1269 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001270 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001271
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001272 /* Store the scrypt of the intermediate key, so we can validate if it's a
1273 password error or mount error when things go wrong.
1274 Note there's no need to check for errors, since if this is incorrect, we
1275 simply won't wipe userdata, which is the correct default behavior
1276 */
1277 int N = 1 << crypt_ftr->N_factor;
1278 int r = 1 << crypt_ftr->r_factor;
1279 int p = 1 << crypt_ftr->p_factor;
1280
Paul Crowley14c8c072018-09-18 13:30:21 -07001281 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1282 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001283 sizeof(crypt_ftr->scrypted_intermediate_key));
1284
1285 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001286 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001287 }
1288
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001289 EVP_CIPHER_CTX_cleanup(&e_ctx);
1290
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001291 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001292}
1293
Paul Crowley14c8c072018-09-18 13:30:21 -07001294static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1295 const unsigned char* encrypted_master_key, size_t keysize,
1296 unsigned char* decrypted_master_key, kdf_func kdf,
1297 void* kdf_params, unsigned char** intermediate_key,
1298 size_t* intermediate_key_size) {
1299 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1300 EVP_CIPHER_CTX d_ctx;
1301 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302
Paul Crowley14c8c072018-09-18 13:30:21 -07001303 /* Turn the password into an intermediate key and IV that can decrypt the
1304 master key */
1305 if (kdf(passwd, salt, ikey, kdf_params)) {
1306 SLOGE("kdf failed");
1307 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001308 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001309
Paul Crowley14c8c072018-09-18 13:30:21 -07001310 /* Initialize the decryption engine */
1311 EVP_CIPHER_CTX_init(&d_ctx);
1312 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1313 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1314 return -1;
1315 }
1316 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1317 /* Decrypt the master key */
1318 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1319 keysize)) {
1320 return -1;
1321 }
1322 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1323 return -1;
1324 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001325
Paul Crowley14c8c072018-09-18 13:30:21 -07001326 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1327 return -1;
1328 }
1329
1330 /* Copy intermediate key if needed by params */
1331 if (intermediate_key && intermediate_key_size) {
1332 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1333 if (*intermediate_key) {
1334 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1335 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1336 }
1337 }
1338
1339 EVP_CIPHER_CTX_cleanup(&d_ctx);
1340
1341 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001342}
1343
Paul Crowley14c8c072018-09-18 13:30:21 -07001344static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001345 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001346 *kdf = scrypt_keymaster;
1347 *kdf_params = ftr;
1348 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001349 *kdf = scrypt;
1350 *kdf_params = ftr;
1351 } else {
1352 *kdf = pbkdf2;
1353 *kdf_params = NULL;
1354 }
1355}
1356
Paul Crowley14c8c072018-09-18 13:30:21 -07001357static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1358 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1359 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001360 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001361 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001362 int ret;
1363
1364 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001365 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1366 decrypted_master_key, kdf, kdf_params, intermediate_key,
1367 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001368 if (ret != 0) {
1369 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001370 }
1371
1372 return ret;
1373}
1374
Paul Crowley14c8c072018-09-18 13:30:21 -07001375static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1376 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001377 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001378 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001379
1380 /* Get some random bits for a key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001381 fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001382 read(fd, key_buf, sizeof(key_buf));
1383 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001384 close(fd);
1385
1386 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001387 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001388}
1389
Paul Crowley14c8c072018-09-18 13:30:21 -07001390int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001391 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001392#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001393
1394 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001395 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001396 if (umount(mountpoint) == 0) {
1397 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001398 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001399
1400 if (errno == EINVAL) {
1401 /* EINVAL is returned if the directory is not a mountpoint,
1402 * i.e. there is no filesystem mounted there. So just get out.
1403 */
1404 break;
1405 }
1406
1407 err = errno;
1408
1409 /* If allowed, be increasingly aggressive before the last two retries */
1410 if (kill) {
1411 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1412 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001413 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001414 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1415 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001416 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001417 }
1418 }
1419
1420 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001421 }
1422
1423 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001424 SLOGD("unmounting %s succeeded\n", mountpoint);
1425 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001427 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1428 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1429 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430 }
1431
1432 return rc;
1433}
1434
Paul Crowley14c8c072018-09-18 13:30:21 -07001435static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001436 // NOTE: post_fs_data results in init calling back around to vold, so all
1437 // callers to this method must be async
1438
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001439 /* Do the prep of the /data filesystem */
1440 property_set("vold.post_fs_data_done", "0");
1441 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001442 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001443
Ken Sumrallc5872692013-05-14 15:26:31 -07001444 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001445 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001446 /* We timed out to prep /data in time. Continue wait. */
1447 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001448 }
Wei Wang42e38102017-06-07 10:46:12 -07001449 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001450}
1451
Paul Crowley14c8c072018-09-18 13:30:21 -07001452static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001453 // Mark the footer as bad
1454 struct crypt_mnt_ftr crypt_ftr;
1455 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1456 SLOGE("Failed to get crypto footer - panic");
1457 return;
1458 }
1459
1460 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1461 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1462 SLOGE("Failed to set crypto footer - panic");
1463 return;
1464 }
1465}
1466
Paul Crowley14c8c072018-09-18 13:30:21 -07001467static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001468 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001469 SLOGE("Failed to mount tmpfs on data - panic");
1470 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001471 }
1472
1473 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1474 SLOGE("Failed to trigger post fs data - panic");
1475 return;
1476 }
1477
1478 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1479 SLOGE("Failed to trigger restart min framework - panic");
1480 return;
1481 }
1482}
1483
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001484/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001485static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001486 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001487 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001488 static int restart_successful = 0;
1489
1490 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001491 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001492 SLOGE("Encrypted filesystem not validated, aborting");
1493 return -1;
1494 }
1495
1496 if (restart_successful) {
1497 SLOGE("System already restarted with encrypted disk, aborting");
1498 return -1;
1499 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001500
Paul Lawrencef4faa572014-01-29 13:31:03 -08001501 if (restart_main) {
1502 /* Here is where we shut down the framework. The init scripts
1503 * start all services in one of three classes: core, main or late_start.
1504 * On boot, we start core and main. Now, we stop main, but not core,
1505 * as core includes vold and a few other really important things that
1506 * we need to keep running. Once main has stopped, we should be able
1507 * to umount the tmpfs /data, then mount the encrypted /data.
1508 * We then restart the class main, and also the class late_start.
1509 * At the moment, I've only put a few things in late_start that I know
1510 * are not needed to bring up the framework, and that also cause problems
1511 * with unmounting the tmpfs /data, but I hope to add add more services
1512 * to the late_start class as we optimize this to decrease the delay
1513 * till the user is asked for the password to the filesystem.
1514 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001515
Paul Lawrencef4faa572014-01-29 13:31:03 -08001516 /* The init files are setup to stop the class main when vold.decrypt is
1517 * set to trigger_reset_main.
1518 */
1519 property_set("vold.decrypt", "trigger_reset_main");
1520 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521
Paul Lawrencef4faa572014-01-29 13:31:03 -08001522 /* Ugh, shutting down the framework is not synchronous, so until it
1523 * can be fixed, this horrible hack will wait a moment for it all to
1524 * shut down before proceeding. Without it, some devices cannot
1525 * restart the graphics services.
1526 */
1527 sleep(2);
1528 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001529
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001530 /* Now that the framework is shutdown, we should be able to umount()
1531 * the tmpfs filesystem, and mount the real one.
1532 */
1533
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001534 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1535 if (strlen(crypto_blkdev) == 0) {
1536 SLOGE("fs_crypto_blkdev not set\n");
1537 return -1;
1538 }
1539
Paul Crowley14c8c072018-09-18 13:30:21 -07001540 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001541 /* If ro.crypto.readonly is set to 1, mount the decrypted
1542 * filesystem readonly. This is used when /data is mounted by
1543 * recovery mode.
1544 */
1545 char ro_prop[PROPERTY_VALUE_MAX];
1546 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001547 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001548 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001549 if (rec) {
1550 rec->flags |= MS_RDONLY;
1551 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001552 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001553
Ken Sumralle5032c42012-04-01 23:58:44 -07001554 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001555 int retries = RETRY_MOUNT_ATTEMPTS;
1556 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001557
1558 /*
1559 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1560 * partitions in the fsck domain.
1561 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001562 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001563 SLOGE("Failed to setexeccon");
1564 return -1;
1565 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001566 bool needs_cp = android::vold::cp_needsCheckpoint();
1567 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1568 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001569 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1570 /* TODO: invoke something similar to
1571 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1572 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001573 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001574 if (--retries) {
1575 sleep(RETRY_MOUNT_DELAY_SECONDS);
1576 } else {
1577 /* Let's hope that a reboot clears away whatever is keeping
1578 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001579 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001580 }
1581 } else {
1582 SLOGE("Failed to mount decrypted data");
1583 cryptfs_set_corrupt();
1584 cryptfs_trigger_restart_min_framework();
1585 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001586 if (setexeccon(NULL)) {
1587 SLOGE("Failed to setexeccon");
1588 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001589 return -1;
1590 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001591 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001592 if (setexeccon(NULL)) {
1593 SLOGE("Failed to setexeccon");
1594 return -1;
1595 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596
Ken Sumralle5032c42012-04-01 23:58:44 -07001597 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001598 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001599 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001600
1601 /* startup service classes main and late_start */
1602 property_set("vold.decrypt", "trigger_restart_framework");
1603 SLOGD("Just triggered restart_framework\n");
1604
1605 /* Give it a few moments to get started */
1606 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001607 }
1608
Ken Sumrall0cc16632011-01-18 20:32:26 -08001609 if (rc == 0) {
1610 restart_successful = 1;
1611 }
1612
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001613 return rc;
1614}
1615
Paul Crowley14c8c072018-09-18 13:30:21 -07001616int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001617 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001618 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001619 SLOGE("cryptfs_restart not valid for file encryption:");
1620 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001621 }
1622
Paul Lawrencef4faa572014-01-29 13:31:03 -08001623 /* Call internal implementation forcing a restart of main service group */
1624 return cryptfs_restart_internal(1);
1625}
1626
Paul Crowley14c8c072018-09-18 13:30:21 -07001627static int do_crypto_complete(const char* mount_point) {
1628 struct crypt_mnt_ftr crypt_ftr;
1629 char encrypted_state[PROPERTY_VALUE_MAX];
1630 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001631
Paul Crowley14c8c072018-09-18 13:30:21 -07001632 property_get("ro.crypto.state", encrypted_state, "");
1633 if (strcmp(encrypted_state, "encrypted")) {
1634 SLOGE("not running with encryption, aborting");
1635 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001636 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001637
Paul Crowley14c8c072018-09-18 13:30:21 -07001638 // crypto_complete is full disk encrypted status
1639 if (e4crypt_is_native()) {
1640 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1641 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001642
Paul Crowley14c8c072018-09-18 13:30:21 -07001643 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1644 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001645
Paul Crowley14c8c072018-09-18 13:30:21 -07001646 /*
1647 * Only report this error if key_loc is a file and it exists.
1648 * If the device was never encrypted, and /data is not mountable for
1649 * some reason, returning 1 should prevent the UI from presenting the
1650 * a "enter password" screen, or worse, a "press button to wipe the
1651 * device" screen.
1652 */
1653 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1654 SLOGE("master key file does not exist, aborting");
1655 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1656 } else {
1657 SLOGE("Error getting crypt footer and key\n");
1658 return CRYPTO_COMPLETE_BAD_METADATA;
1659 }
1660 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001661
Paul Crowley14c8c072018-09-18 13:30:21 -07001662 // Test for possible error flags
1663 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1664 SLOGE("Encryption process is partway completed\n");
1665 return CRYPTO_COMPLETE_PARTIAL;
1666 }
1667
1668 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1669 SLOGE("Encryption process was interrupted but cannot continue\n");
1670 return CRYPTO_COMPLETE_INCONSISTENT;
1671 }
1672
1673 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1674 SLOGE("Encryption is successful but data is corrupt\n");
1675 return CRYPTO_COMPLETE_CORRUPT;
1676 }
1677
1678 /* We passed the test! We shall diminish, and return to the west */
1679 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001680}
1681
Paul Crowley14c8c072018-09-18 13:30:21 -07001682static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1683 const char* mount_point, const char* label) {
1684 unsigned char decrypted_master_key[MAX_KEY_LEN];
1685 char crypto_blkdev[MAXPATHLEN];
1686 char real_blkdev[MAXPATHLEN];
1687 char tmp_mount_point[64];
1688 unsigned int orig_failed_decrypt_count;
1689 int rc;
1690 int use_keymaster = 0;
1691 int upgrade = 0;
1692 unsigned char* intermediate_key = 0;
1693 size_t intermediate_key_size = 0;
1694 int N = 1 << crypt_ftr->N_factor;
1695 int r = 1 << crypt_ftr->r_factor;
1696 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001697
Paul Crowley14c8c072018-09-18 13:30:21 -07001698 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1699 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001700
Paul Crowley14c8c072018-09-18 13:30:21 -07001701 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1702 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1703 &intermediate_key_size)) {
1704 SLOGE("Failed to decrypt master key\n");
1705 rc = -1;
1706 goto errout;
1707 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001708 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001709
Paul Crowley14c8c072018-09-18 13:30:21 -07001710 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001711
Paul Crowley14c8c072018-09-18 13:30:21 -07001712 // Create crypto block device - all (non fatal) code paths
1713 // need it
1714 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
1715 0)) {
1716 SLOGE("Error creating decrypted block device\n");
1717 rc = -1;
1718 goto errout;
1719 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001720
Paul Crowley14c8c072018-09-18 13:30:21 -07001721 /* Work out if the problem is the password or the data */
1722 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001723
Paul Crowley14c8c072018-09-18 13:30:21 -07001724 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1725 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1726 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001727
Paul Crowley14c8c072018-09-18 13:30:21 -07001728 // Does the key match the crypto footer?
1729 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1730 sizeof(scrypted_intermediate_key)) == 0) {
1731 SLOGI("Password matches");
1732 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001733 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001734 /* Try mounting the file system anyway, just in case the problem's with
1735 * the footer, not the key. */
1736 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1737 mkdir(tmp_mount_point, 0755);
1738 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1739 SLOGE("Error temp mounting decrypted block device\n");
1740 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001741
Paul Crowley14c8c072018-09-18 13:30:21 -07001742 rc = ++crypt_ftr->failed_decrypt_count;
1743 put_crypt_ftr_and_key(crypt_ftr);
1744 } else {
1745 /* Success! */
1746 SLOGI("Password did not match but decrypted drive mounted - continue");
1747 umount(tmp_mount_point);
1748 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001749 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001750 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001751
Paul Crowley14c8c072018-09-18 13:30:21 -07001752 if (rc == 0) {
1753 crypt_ftr->failed_decrypt_count = 0;
1754 if (orig_failed_decrypt_count != 0) {
1755 put_crypt_ftr_and_key(crypt_ftr);
1756 }
1757
1758 /* Save the name of the crypto block device
1759 * so we can mount it when restarting the framework. */
1760 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1761
1762 /* Also save a the master key so we can reencrypted the key
1763 * the key when we want to change the password on it. */
1764 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1765 saved_mount_point = strdup(mount_point);
1766 master_key_saved = 1;
1767 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1768 rc = 0;
1769
1770 // Upgrade if we're not using the latest KDF.
1771 use_keymaster = keymaster_check_compatibility();
1772 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1773 // Don't allow downgrade
1774 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1775 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1776 upgrade = 1;
1777 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1778 crypt_ftr->kdf_type = KDF_SCRYPT;
1779 upgrade = 1;
1780 }
1781
1782 if (upgrade) {
1783 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1784 crypt_ftr->master_key, crypt_ftr);
1785 if (!rc) {
1786 rc = put_crypt_ftr_and_key(crypt_ftr);
1787 }
1788 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1789
1790 // Do not fail even if upgrade failed - machine is bootable
1791 // Note that if this code is ever hit, there is a *serious* problem
1792 // since KDFs should never fail. You *must* fix the kdf before
1793 // proceeding!
1794 if (rc) {
1795 SLOGW(
1796 "Upgrade failed with error %d,"
1797 " but continuing with previous state",
1798 rc);
1799 rc = 0;
1800 }
1801 }
1802 }
1803
1804errout:
1805 if (intermediate_key) {
1806 memset(intermediate_key, 0, intermediate_key_size);
1807 free(intermediate_key);
1808 }
1809 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001810}
1811
Ken Sumrall29d8da82011-05-18 17:20:07 -07001812/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001813 * Called by vold when it's asked to mount an encrypted external
1814 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001815 * as any metadata is been stored in a separate, small partition. We
1816 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001817 *
1818 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001819 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001820int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1821 char* out_crypto_blkdev) {
1822 int fd = open(real_blkdev, O_RDONLY | O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001823 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001824 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001825 return -1;
1826 }
1827
1828 unsigned long nr_sec = 0;
1829 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001830 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001831
Ken Sumrall29d8da82011-05-18 17:20:07 -07001832 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001833 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001834 return -1;
1835 }
1836
Jeff Sharkey9c484982015-03-31 10:35:33 -07001837 struct crypt_mnt_ftr ext_crypt_ftr;
1838 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1839 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001840 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001841 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001842 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001843 uint32_t flags = 0;
1844 if (e4crypt_is_native() &&
1845 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1846 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001847
Paul Crowley385cb8c2018-03-29 13:27:23 -07001848 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001849}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001850
Jeff Sharkey9c484982015-03-31 10:35:33 -07001851/*
1852 * Called by vold when it's asked to unmount an encrypted external
1853 * storage volume.
1854 */
1855int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001856 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001857}
1858
Paul Crowley14c8c072018-09-18 13:30:21 -07001859int cryptfs_crypto_complete(void) {
1860 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001861}
1862
Paul Crowley14c8c072018-09-18 13:30:21 -07001863int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001864 char encrypted_state[PROPERTY_VALUE_MAX];
1865 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001866 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1867 SLOGE(
1868 "encrypted fs already validated or not running with encryption,"
1869 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001870 return -1;
1871 }
1872
1873 if (get_crypt_ftr_and_key(crypt_ftr)) {
1874 SLOGE("Error getting crypt footer and key");
1875 return -1;
1876 }
1877
1878 return 0;
1879}
1880
Paul Crowley14c8c072018-09-18 13:30:21 -07001881int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001882 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001883 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001884 SLOGE("cryptfs_check_passwd not valid for file encryption");
1885 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001886 }
1887
Paul Lawrencef4faa572014-01-29 13:31:03 -08001888 struct crypt_mnt_ftr crypt_ftr;
1889 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001890
Paul Lawrencef4faa572014-01-29 13:31:03 -08001891 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001892 if (rc) {
1893 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001894 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001895 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001896
Paul Crowley14c8c072018-09-18 13:30:21 -07001897 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001898 if (rc) {
1899 SLOGE("Password did not match");
1900 return rc;
1901 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001902
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001903 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1904 // Here we have a default actual password but a real password
1905 // we must test against the scrypted value
1906 // First, we must delete the crypto block device that
1907 // test_mount_encrypted_fs leaves behind as a side effect
1908 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001909 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1910 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001911 if (rc) {
1912 SLOGE("Default password did not match on reboot encryption");
1913 return rc;
1914 }
1915
1916 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1917 put_crypt_ftr_and_key(&crypt_ftr);
1918 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1919 if (rc) {
1920 SLOGE("Could not change password on reboot encryption");
1921 return rc;
1922 }
1923 }
1924
1925 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001926 cryptfs_clear_password();
1927 password = strdup(passwd);
1928 struct timespec now;
1929 clock_gettime(CLOCK_BOOTTIME, &now);
1930 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001931 }
1932
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001933 return rc;
1934}
1935
Paul Crowley14c8c072018-09-18 13:30:21 -07001936int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001937 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001938 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001939 char encrypted_state[PROPERTY_VALUE_MAX];
1940 int rc;
1941
1942 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001943 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001944 SLOGE("device not encrypted, aborting");
1945 return -2;
1946 }
1947
1948 if (!master_key_saved) {
1949 SLOGE("encrypted fs not yet mounted, aborting");
1950 return -1;
1951 }
1952
1953 if (!saved_mount_point) {
1954 SLOGE("encrypted fs failed to save mount point, aborting");
1955 return -1;
1956 }
1957
Ken Sumrall160b4d62013-04-22 12:15:39 -07001958 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001959 SLOGE("Error getting crypt footer and key\n");
1960 return -1;
1961 }
1962
1963 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1964 /* If the device has no password, then just say the password is valid */
1965 rc = 0;
1966 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001967 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001968 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1969 /* They match, the password is correct */
1970 rc = 0;
1971 } else {
1972 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1973 sleep(1);
1974 rc = 1;
1975 }
1976 }
1977
1978 return rc;
1979}
1980
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001981/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08001982 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001983 * Presumably, at a minimum, the caller will update the
1984 * filesystem size and crypto_type_name after calling this function.
1985 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001986static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001987 off64_t off;
1988
1989 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001990 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001991 ftr->major_version = CURRENT_MAJOR_VERSION;
1992 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001993 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08001994 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07001995
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001996 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001997 case 1:
1998 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1999 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002000
Paul Crowley14c8c072018-09-18 13:30:21 -07002001 case 0:
2002 ftr->kdf_type = KDF_SCRYPT;
2003 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002004
Paul Crowley14c8c072018-09-18 13:30:21 -07002005 default:
2006 SLOGE("keymaster_check_compatibility failed");
2007 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002008 }
2009
Kenny Rootc4c70f12013-06-14 12:11:38 -07002010 get_device_scrypt_params(ftr);
2011
Ken Sumrall160b4d62013-04-22 12:15:39 -07002012 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2013 if (get_crypt_ftr_info(NULL, &off) == 0) {
2014 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002015 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002016 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002017
2018 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002019}
2020
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002021#define FRAMEWORK_BOOT_WAIT 60
2022
Paul Crowley14c8c072018-09-18 13:30:21 -07002023static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2024 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002025 if (fd == -1) {
2026 SLOGE("Error opening file %s", filename);
2027 return -1;
2028 }
2029
2030 char block[CRYPT_INPLACE_BUFSIZE];
2031 memset(block, 0, sizeof(block));
2032 if (unix_read(fd, block, sizeof(block)) < 0) {
2033 SLOGE("Error reading file %s", filename);
2034 close(fd);
2035 return -1;
2036 }
2037
2038 close(fd);
2039
2040 SHA256_CTX c;
2041 SHA256_Init(&c);
2042 SHA256_Update(&c, block, sizeof(block));
2043 SHA256_Final(buf, &c);
2044
2045 return 0;
2046}
2047
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002048static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2049 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002050 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002051 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002052
Paul Lawrence87999172014-02-20 12:21:31 -08002053 /* The size of the userdata partition, and add in the vold volumes below */
2054 tot_encryption_size = crypt_ftr->fs_size;
2055
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002056 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002057 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002058
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002059 if (rc == ENABLE_INPLACE_ERR_DEV) {
2060 /* Hack for b/17898962 */
2061 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2062 cryptfs_reboot(RebootType::reboot);
2063 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002064
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002065 if (!rc) {
2066 crypt_ftr->encrypted_upto = cur_encryption_done;
2067 }
Paul Lawrence87999172014-02-20 12:21:31 -08002068
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002069 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2070 /* The inplace routine never actually sets the progress to 100% due
2071 * to the round down nature of integer division, so set it here */
2072 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002073 }
2074
2075 return rc;
2076}
2077
Paul Crowleyb64933a2017-10-31 08:25:55 -07002078static int vold_unmountAll(void) {
2079 VolumeManager* vm = VolumeManager::Instance();
2080 return vm->unmountAll();
2081}
2082
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002083int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002084 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002085 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002086 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002087 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002088 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002089 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002090 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002091 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002092 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002093 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002094 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002095 bool onlyCreateHeader = false;
2096 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002097
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002098 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002099 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2100 /* An encryption was underway and was interrupted */
2101 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2102 crypt_ftr.encrypted_upto = 0;
2103 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002104
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002105 /* At this point, we are in an inconsistent state. Until we successfully
2106 complete encryption, a reboot will leave us broken. So mark the
2107 encryption failed in case that happens.
2108 On successfully completing encryption, remove this flag */
2109 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002110
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002111 put_crypt_ftr_and_key(&crypt_ftr);
2112 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2113 if (!check_ftr_sha(&crypt_ftr)) {
2114 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2115 put_crypt_ftr_and_key(&crypt_ftr);
2116 goto error_unencrypted;
2117 }
2118
2119 /* Doing a reboot-encryption*/
2120 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2121 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2122 rebootEncryption = true;
2123 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002124 } else {
2125 // We don't want to accidentally reference invalid data.
2126 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002127 }
2128
2129 property_get("ro.crypto.state", encrypted_state, "");
2130 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2131 SLOGE("Device is already running encrypted, aborting");
2132 goto error_unencrypted;
2133 }
2134
2135 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002136 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2137 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002138
Ken Sumrall3ed82362011-01-28 23:31:16 -08002139 /* Get the size of the real block device */
Paul Crowley14c8c072018-09-18 13:30:21 -07002140 fd = open(real_blkdev, O_RDONLY | O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002141 if (fd == -1) {
2142 SLOGE("Cannot open block device %s\n", real_blkdev);
2143 goto error_unencrypted;
2144 }
2145 unsigned long nr_sec;
2146 get_blkdev_size(fd, &nr_sec);
2147 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002148 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2149 goto error_unencrypted;
2150 }
2151 close(fd);
2152
2153 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002154 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002155 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002156 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002157 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002158
Paul Lawrence87999172014-02-20 12:21:31 -08002159 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002160
2161 if (fs_size_sec > max_fs_size_sec) {
2162 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2163 goto error_unencrypted;
2164 }
2165 }
2166
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002167 /* Get a wakelock as this may take a while, and we don't want the
2168 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2169 * wants to keep the screen on, it can grab a full wakelock.
2170 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002171 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002172 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2173
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002174 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002175 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002176 */
2177 property_set("vold.decrypt", "trigger_shutdown_framework");
2178 SLOGD("Just asked init to shut down class main\n");
2179
Jeff Sharkey9c484982015-03-31 10:35:33 -07002180 /* Ask vold to unmount all devices that it manages */
2181 if (vold_unmountAll()) {
2182 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002183 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002184
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002185 /* no_ui means we are being called from init, not settings.
2186 Now we always reboot from settings, so !no_ui means reboot
2187 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002188 if (!no_ui) {
2189 /* Try fallback, which is to reboot and try there */
2190 onlyCreateHeader = true;
2191 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2192 if (breadcrumb == 0) {
2193 SLOGE("Failed to create breadcrumb file");
2194 goto error_shutting_down;
2195 }
2196 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002197 }
2198
2199 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002200 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002201 /* Now that /data is unmounted, we need to mount a tmpfs
2202 * /data, set a property saying we're doing inplace encryption,
2203 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002204 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002205 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002206 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002207 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002208 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002209 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002210
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002211 /* restart the framework. */
2212 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002213 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002214
Ken Sumrall92736ef2012-10-17 20:57:14 -07002215 /* Ugh, shutting down the framework is not synchronous, so until it
2216 * can be fixed, this horrible hack will wait a moment for it all to
2217 * shut down before proceeding. Without it, some devices cannot
2218 * restart the graphics services.
2219 */
2220 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002221 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002222
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002223 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002224 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002225 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002226 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2227 goto error_shutting_down;
2228 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002229
Paul Lawrence87999172014-02-20 12:21:31 -08002230 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002231 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002232 } else {
2233 crypt_ftr.fs_size = nr_sec;
2234 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002235 /* At this point, we are in an inconsistent state. Until we successfully
2236 complete encryption, a reboot will leave us broken. So mark the
2237 encryption failed in case that happens.
2238 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002239 if (onlyCreateHeader) {
2240 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2241 } else {
2242 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2243 }
Paul Lawrence87999172014-02-20 12:21:31 -08002244 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002245 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2246 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002247
Paul Lawrence87999172014-02-20 12:21:31 -08002248 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002249 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2250 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002251 SLOGE("Cannot create encrypted master key\n");
2252 goto error_shutting_down;
2253 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002254
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002255 /* Replace scrypted intermediate key if we are preparing for a reboot */
2256 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002257 unsigned char fake_master_key[MAX_KEY_LEN];
2258 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002259 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002260 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2261 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002262 }
2263
Paul Lawrence87999172014-02-20 12:21:31 -08002264 /* Write the key to the end of the partition */
2265 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002266
Paul Lawrence87999172014-02-20 12:21:31 -08002267 /* If any persistent data has been remembered, save it.
2268 * If none, create a valid empty table and save that.
2269 */
2270 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002271 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2272 if (pdata) {
2273 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2274 persist_data = pdata;
2275 }
Paul Lawrence87999172014-02-20 12:21:31 -08002276 }
2277 if (persist_data) {
2278 save_persistent_data();
2279 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002280 }
2281
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002282 if (onlyCreateHeader) {
2283 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002284 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002285 }
2286
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002287 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002288 /* startup service classes main and late_start */
2289 property_set("vold.decrypt", "trigger_restart_min_framework");
2290 SLOGD("Just triggered restart_min_framework\n");
2291
2292 /* OK, the framework is restarted and will soon be showing a
2293 * progress bar. Time to setup an encrypted mapping, and
2294 * either write a new filesystem, or encrypt in place updating
2295 * the progress bar as we work.
2296 */
2297 }
2298
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002299 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002300 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002301 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002302
Paul Lawrence87999172014-02-20 12:21:31 -08002303 /* If we are continuing, check checksums match */
2304 rc = 0;
2305 if (previously_encrypted_upto) {
2306 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2307 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002308
Paul Crowley14c8c072018-09-18 13:30:21 -07002309 if (!rc &&
2310 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002311 SLOGE("Checksums do not match - trigger wipe");
2312 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002313 }
2314 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002315
Paul Lawrence87999172014-02-20 12:21:31 -08002316 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002317 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002318 previously_encrypted_upto);
2319 }
2320
2321 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002322 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002323 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002324 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002325 SLOGE("Error calculating checksum for continuing encryption");
2326 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002327 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002328 }
2329
2330 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002331 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002332
Paul Crowley14c8c072018-09-18 13:30:21 -07002333 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002334 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002335 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002336
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002337 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002338 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2339 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002340 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002341 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002342
Paul Lawrence6bfed202014-07-28 12:47:22 -07002343 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002344
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002345 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2346 char value[PROPERTY_VALUE_MAX];
2347 property_get("ro.crypto.state", value, "");
2348 if (!strcmp(value, "")) {
2349 /* default encryption - continue first boot sequence */
2350 property_set("ro.crypto.state", "encrypted");
2351 property_set("ro.crypto.type", "block");
2352 release_wake_lock(lockid);
2353 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2354 // Bring up cryptkeeper that will check the password and set it
2355 property_set("vold.decrypt", "trigger_shutdown_framework");
2356 sleep(2);
2357 property_set("vold.encrypt_progress", "");
2358 cryptfs_trigger_restart_min_framework();
2359 } else {
2360 cryptfs_check_passwd(DEFAULT_PASSWORD);
2361 cryptfs_restart_internal(1);
2362 }
2363 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002364 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002365 sleep(2); /* Give the UI a chance to show 100% progress */
2366 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002367 }
Paul Lawrence87999172014-02-20 12:21:31 -08002368 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002369 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002370 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002371 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002372 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002373 char value[PROPERTY_VALUE_MAX];
2374
Ken Sumrall319369a2012-06-27 16:30:18 -07002375 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002376 if (!strcmp(value, "1")) {
2377 /* wipe data if encryption failed */
2378 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002379 std::string err;
2380 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002381 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002382 if (!write_bootloader_message(options, &err)) {
2383 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002384 }
Josh Gaofec44372017-08-28 13:22:55 -07002385 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002386 } else {
2387 /* set property to trigger dialog */
2388 property_set("vold.encrypt_progress", "error_partially_encrypted");
2389 release_wake_lock(lockid);
2390 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002391 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002392 }
2393
Ken Sumrall3ed82362011-01-28 23:31:16 -08002394 /* hrm, the encrypt step claims success, but the reboot failed.
2395 * This should not happen.
2396 * Set the property and return. Hope the framework can deal with it.
2397 */
2398 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002399 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002400 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002401
2402error_unencrypted:
2403 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002404 if (lockid[0]) {
2405 release_wake_lock(lockid);
2406 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002407 return -1;
2408
2409error_shutting_down:
2410 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2411 * but the framework is stopped and not restarted to show the error, so it's up to
2412 * vold to restart the system.
2413 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002414 SLOGE(
2415 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2416 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002417 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002418
2419 /* shouldn't get here */
2420 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002421 if (lockid[0]) {
2422 release_wake_lock(lockid);
2423 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002424 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002425}
2426
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002427int cryptfs_enable(int type, const char* passwd, int no_ui) {
2428 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002429}
2430
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002431int cryptfs_enable_default(int no_ui) {
2432 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002433}
2434
Paul Crowley14c8c072018-09-18 13:30:21 -07002435int cryptfs_changepw(int crypt_type, const char* newpw) {
Paul Crowley38132a12016-02-09 09:50:32 +00002436 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002437 SLOGE("cryptfs_changepw not valid for file encryption");
2438 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002439 }
2440
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002441 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002442 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002443
2444 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002445 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002446 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002447 return -1;
2448 }
2449
Paul Lawrencef4faa572014-01-29 13:31:03 -08002450 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2451 SLOGE("Invalid crypt_type %d", crypt_type);
2452 return -1;
2453 }
2454
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002455 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002456 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002457 SLOGE("Error getting crypt footer and key");
2458 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002459 }
2460
Paul Lawrencef4faa572014-01-29 13:31:03 -08002461 crypt_ftr.crypt_type = crypt_type;
2462
Paul Crowley14c8c072018-09-18 13:30:21 -07002463 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2464 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002465 if (rc) {
2466 SLOGE("Encrypt master key failed: %d", rc);
2467 return -1;
2468 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002469 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002470 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002471
2472 return 0;
2473}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002474
Rubin Xu85c01f92014-10-13 12:49:54 +01002475static unsigned int persist_get_max_entries(int encrypted) {
2476 struct crypt_mnt_ftr crypt_ftr;
2477 unsigned int dsize;
2478 unsigned int max_persistent_entries;
2479
2480 /* If encrypted, use the values from the crypt_ftr, otherwise
2481 * use the values for the current spec.
2482 */
2483 if (encrypted) {
2484 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2485 return -1;
2486 }
2487 dsize = crypt_ftr.persist_data_size;
2488 } else {
2489 dsize = CRYPT_PERSIST_DATA_SIZE;
2490 }
2491
Paul Crowley14c8c072018-09-18 13:30:21 -07002492 max_persistent_entries =
2493 (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
Rubin Xu85c01f92014-10-13 12:49:54 +01002494
2495 return max_persistent_entries;
2496}
2497
Paul Crowley14c8c072018-09-18 13:30:21 -07002498static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002499 unsigned int i;
2500
2501 if (persist_data == NULL) {
2502 return -1;
2503 }
2504 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2505 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2506 /* We found it! */
2507 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2508 return 0;
2509 }
2510 }
2511
2512 return -1;
2513}
2514
Paul Crowley14c8c072018-09-18 13:30:21 -07002515static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002516 unsigned int i;
2517 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002518 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002519
2520 if (persist_data == NULL) {
2521 return -1;
2522 }
2523
Rubin Xu85c01f92014-10-13 12:49:54 +01002524 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002525
2526 num = persist_data->persist_valid_entries;
2527
2528 for (i = 0; i < num; i++) {
2529 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2530 /* We found an existing entry, update it! */
2531 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2532 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2533 return 0;
2534 }
2535 }
2536
2537 /* We didn't find it, add it to the end, if there is room */
2538 if (persist_data->persist_valid_entries < max_persistent_entries) {
2539 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2540 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2541 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2542 persist_data->persist_valid_entries++;
2543 return 0;
2544 }
2545
2546 return -1;
2547}
2548
Rubin Xu85c01f92014-10-13 12:49:54 +01002549/**
2550 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2551 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2552 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002553int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002554 std::string key_ = key;
2555 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002556
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002557 std::string parsed_field;
2558 unsigned parsed_index;
2559
2560 std::string::size_type split = key_.find_last_of('_');
2561 if (split == std::string::npos) {
2562 parsed_field = key_;
2563 parsed_index = 0;
2564 } else {
2565 parsed_field = key_.substr(0, split);
2566 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002567 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002568
2569 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002570}
2571
2572/*
2573 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2574 * remaining entries starting from index will be deleted.
2575 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2576 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2577 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2578 *
2579 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002580static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002581 unsigned int i;
2582 unsigned int j;
2583 unsigned int num;
2584
2585 if (persist_data == NULL) {
2586 return PERSIST_DEL_KEY_ERROR_OTHER;
2587 }
2588
2589 num = persist_data->persist_valid_entries;
2590
Paul Crowley14c8c072018-09-18 13:30:21 -07002591 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002592 // Filter out to-be-deleted entries in place.
2593 for (i = 0; i < num; i++) {
2594 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2595 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2596 j++;
2597 }
2598 }
2599
2600 if (j < num) {
2601 persist_data->persist_valid_entries = j;
2602 // Zeroise the remaining entries
2603 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2604 return PERSIST_DEL_KEY_OK;
2605 } else {
2606 // Did not find an entry matching the given fieldname
2607 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2608 }
2609}
2610
Paul Crowley14c8c072018-09-18 13:30:21 -07002611static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002612 unsigned int i;
2613 unsigned int count;
2614
2615 if (persist_data == NULL) {
2616 return -1;
2617 }
2618
2619 count = 0;
2620 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2621 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2622 count++;
2623 }
2624 }
2625
2626 return count;
2627}
2628
Ken Sumrall160b4d62013-04-22 12:15:39 -07002629/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002630int cryptfs_getfield(const char* fieldname, char* value, int len) {
Paul Crowley38132a12016-02-09 09:50:32 +00002631 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002632 SLOGE("Cannot get field when file encrypted");
2633 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002634 }
2635
Ken Sumrall160b4d62013-04-22 12:15:39 -07002636 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002637 /* CRYPTO_GETFIELD_OK is success,
2638 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2639 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2640 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002641 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002642 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2643 int i;
2644 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002645
2646 if (persist_data == NULL) {
2647 load_persistent_data();
2648 if (persist_data == NULL) {
2649 SLOGE("Getfield error, cannot load persistent data");
2650 goto out;
2651 }
2652 }
2653
Rubin Xu85c01f92014-10-13 12:49:54 +01002654 // Read value from persistent entries. If the original value is split into multiple entries,
2655 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002656 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002657 // 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 -07002658 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002659 // value too small
2660 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2661 goto out;
2662 }
2663 rc = CRYPTO_GETFIELD_OK;
2664
2665 for (i = 1; /* break explicitly */; i++) {
2666 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002667 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002668 // If the fieldname is very long, we stop as soon as it begins to overflow the
2669 // maximum field length. At this point we have in fact fully read out the original
2670 // value because cryptfs_setfield would not allow fields with longer names to be
2671 // written in the first place.
2672 break;
2673 }
2674 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002675 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2676 // value too small.
2677 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2678 goto out;
2679 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002680 } else {
2681 // Exhaust all entries.
2682 break;
2683 }
2684 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002685 } else {
2686 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002687 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002688 }
2689
2690out:
2691 return rc;
2692}
2693
2694/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002695int cryptfs_setfield(const char* fieldname, const char* value) {
Paul Crowley38132a12016-02-09 09:50:32 +00002696 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002697 SLOGE("Cannot set field when file encrypted");
2698 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002699 }
2700
Ken Sumrall160b4d62013-04-22 12:15:39 -07002701 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002702 /* 0 is success, negative values are error */
2703 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002704 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002705 unsigned int field_id;
2706 char temp_field[PROPERTY_KEY_MAX];
2707 unsigned int num_entries;
2708 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002709
2710 if (persist_data == NULL) {
2711 load_persistent_data();
2712 if (persist_data == NULL) {
2713 SLOGE("Setfield error, cannot load persistent data");
2714 goto out;
2715 }
2716 }
2717
2718 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002719 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002720 encrypted = 1;
2721 }
2722
Rubin Xu85c01f92014-10-13 12:49:54 +01002723 // Compute the number of entries required to store value, each entry can store up to
2724 // (PROPERTY_VALUE_MAX - 1) chars
2725 if (strlen(value) == 0) {
2726 // Empty value also needs one entry to store.
2727 num_entries = 1;
2728 } else {
2729 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2730 }
2731
2732 max_keylen = strlen(fieldname);
2733 if (num_entries > 1) {
2734 // Need an extra "_%d" suffix.
2735 max_keylen += 1 + log10(num_entries);
2736 }
2737 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2738 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002739 goto out;
2740 }
2741
Rubin Xu85c01f92014-10-13 12:49:54 +01002742 // Make sure we have enough space to write the new value
2743 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2744 persist_get_max_entries(encrypted)) {
2745 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2746 goto out;
2747 }
2748
2749 // Now that we know persist_data has enough space for value, let's delete the old field first
2750 // to make up space.
2751 persist_del_keys(fieldname, 0);
2752
2753 if (persist_set_key(fieldname, value, encrypted)) {
2754 // fail to set key, should not happen as we have already checked the available space
2755 SLOGE("persist_set_key() error during setfield()");
2756 goto out;
2757 }
2758
2759 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002760 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002761
2762 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2763 // fail to set key, should not happen as we have already checked the available space.
2764 SLOGE("persist_set_key() error during setfield()");
2765 goto out;
2766 }
2767 }
2768
Ken Sumrall160b4d62013-04-22 12:15:39 -07002769 /* If we are running encrypted, save the persistent data now */
2770 if (encrypted) {
2771 if (save_persistent_data()) {
2772 SLOGE("Setfield error, cannot save persistent data");
2773 goto out;
2774 }
2775 }
2776
Rubin Xu85c01f92014-10-13 12:49:54 +01002777 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002778
2779out:
2780 return rc;
2781}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002782
2783/* Checks userdata. Attempt to mount the volume if default-
2784 * encrypted.
2785 * On success trigger next init phase and return 0.
2786 * Currently do not handle failure - see TODO below.
2787 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002788int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002789 int crypt_type = cryptfs_get_password_type();
2790 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2791 SLOGE("Bad crypt type - error");
2792 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002793 SLOGD(
2794 "Password is not default - "
2795 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002796 property_set("vold.decrypt", "trigger_restart_min_framework");
2797 return 0;
2798 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2799 SLOGD("Password is default - restarting filesystem");
2800 cryptfs_restart_internal(0);
2801 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002802 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002803 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002804 }
2805
Paul Lawrence6bfed202014-07-28 12:47:22 -07002806 /** Corrupt. Allow us to boot into framework, which will detect bad
2807 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002808 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002809 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002810 return 0;
2811}
2812
2813/* Returns type of the password, default, pattern, pin or password.
2814 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002815int cryptfs_get_password_type(void) {
Paul Crowley38132a12016-02-09 09:50:32 +00002816 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002817 SLOGE("cryptfs_get_password_type not valid for file encryption");
2818 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002819 }
2820
Paul Lawrencef4faa572014-01-29 13:31:03 -08002821 struct crypt_mnt_ftr crypt_ftr;
2822
2823 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2824 SLOGE("Error getting crypt footer and key\n");
2825 return -1;
2826 }
2827
Paul Lawrence6bfed202014-07-28 12:47:22 -07002828 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2829 return -1;
2830 }
2831
Paul Lawrencef4faa572014-01-29 13:31:03 -08002832 return crypt_ftr.crypt_type;
2833}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002834
Paul Crowley14c8c072018-09-18 13:30:21 -07002835const char* cryptfs_get_password() {
Paul Crowley38132a12016-02-09 09:50:32 +00002836 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002837 SLOGE("cryptfs_get_password not valid for file encryption");
2838 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002839 }
2840
Paul Lawrence399317e2014-03-10 13:20:50 -07002841 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002842 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002843 if (now.tv_sec < password_expiry_time) {
2844 return password;
2845 } else {
2846 cryptfs_clear_password();
2847 return 0;
2848 }
2849}
2850
Paul Crowley14c8c072018-09-18 13:30:21 -07002851void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002852 if (password) {
2853 size_t len = strlen(password);
2854 memset(password, 0, len);
2855 free(password);
2856 password = 0;
2857 password_expiry_time = 0;
2858 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002859}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002860
Paul Crowley14c8c072018-09-18 13:30:21 -07002861int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002862 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07002863 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07002864}