blob: 00e5519cc34dc6eafdd993ec0aea26f794cf9169 [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
27#include "EncryptInplace.h"
28#include "Ext4Crypt.h"
29#include "Keymaster.h"
30#include "Process.h"
31#include "ScryptParameters.h"
32#include "VoldUtil.h"
33#include "VolumeManager.h"
34#include "secontext.h"
35
Logan Chien3f2b1222018-05-02 11:39:03 +080036#include <android-base/properties.h>
Logan Chiend557d762018-05-02 11:36:45 +080037#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080039#include <cutils/properties.h>
Paul Crowley3b71fc52017-10-09 10:55:21 -070040#include <ext4_utils/ext4_crypt.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070041#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080045#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080046#include <logwrap/logwrap.h>
47#include <openssl/evp.h>
48#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080050
51#include <ctype.h>
52#include <errno.h>
53#include <fcntl.h>
54#include <inttypes.h>
55#include <libgen.h>
56#include <linux/dm-ioctl.h>
57#include <linux/kdev_t.h>
58#include <math.h>
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <sys/ioctl.h>
63#include <sys/mount.h>
64#include <sys/param.h>
65#include <sys/stat.h>
66#include <sys/types.h>
67#include <sys/wait.h>
68#include <time.h>
69#include <unistd.h>
70
Wei Wang4375f1b2017-02-24 17:43:01 -080071extern "C" {
72#include <crypto_scrypt.h>
73}
Mark Salyzyn3e971272014-01-21 13:27:04 -080074
Mark Salyzyn5eecc442014-02-12 14:16:14 -080075#define UNUSED __attribute__((unused))
76
Ken Sumrall8f869aa2010-12-03 03:47:09 -080077#define DM_CRYPT_BUF_SIZE 4096
78
Jason parks70a4b3f2011-01-28 10:10:47 -060079#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080080
81constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
82constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070083constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080084
85// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070086static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060087
Paul Crowley14c8c072018-09-18 13:30:21 -070088#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070089
Paul Lawrence3bd36d52015-06-09 13:37:44 -070090#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080091
Paul Lawrence3d99eba2015-11-20 07:07:19 -080092#define CRYPTO_BLOCK_DEVICE "userdata"
93
94#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
95
Ken Sumrall29d8da82011-05-18 17:20:07 -070096#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070097#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070098
Ken Sumralle919efe2012-09-29 17:07:41 -070099#define TABLE_LOAD_RETRIES 10
100
Shawn Willden47ba10d2014-09-03 17:07:06 -0600101#define RSA_KEY_SIZE 2048
102#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
103#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600104#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700105
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700106#define RETRY_MOUNT_ATTEMPTS 10
107#define RETRY_MOUNT_DELAY_SECONDS 1
108
Paul Crowley5afbc622017-11-27 09:42:17 -0800109#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
110
Paul Crowley73473332017-11-21 15:43:51 -0800111static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
112
Greg Kaiser59ad0182018-02-16 13:01:36 -0800113static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700114static char* saved_mount_point;
115static int master_key_saved = 0;
116static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800117
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700118/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700119static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000120 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700121}
122
123/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700124static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800125 if (ftr->keymaster_blob_size) {
126 SLOGI("Already have key");
127 return 0;
128 }
129
Paul Crowley14c8c072018-09-18 13:30:21 -0700130 int rc = keymaster_create_key_for_cryptfs_scrypt(
131 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
132 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000133 if (rc) {
134 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800135 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000136 ftr->keymaster_blob_size = 0;
137 }
138 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700139 return -1;
140 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000141 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700142}
143
Shawn Willdene17a9c42014-09-08 13:04:08 -0600144/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700145static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
146 const size_t object_size, unsigned char** signature,
147 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600148 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600149 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600150 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600151
Shawn Willdene17a9c42014-09-08 13:04:08 -0600152 // To sign a message with RSA, the message must satisfy two
153 // constraints:
154 //
155 // 1. The message, when interpreted as a big-endian numeric value, must
156 // be strictly less than the public modulus of the RSA key. Note
157 // that because the most significant bit of the public modulus is
158 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
159 // key), an n-bit message with most significant bit 0 always
160 // satisfies this requirement.
161 //
162 // 2. The message must have the same length in bits as the public
163 // modulus of the RSA key. This requirement isn't mathematically
164 // necessary, but is necessary to ensure consistency in
165 // implementations.
166 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600167 case KDF_SCRYPT_KEYMASTER:
168 // This ensures the most significant byte of the signed message
169 // is zero. We could have zero-padded to the left instead, but
170 // this approach is slightly more robust against changes in
171 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600172 // so) because we really should be using a proper deterministic
173 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800174 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600175 SLOGI("Signing safely-padded object");
176 break;
177 default:
178 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000179 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600180 }
Paul Crowley73473332017-11-21 15:43:51 -0800181 for (;;) {
182 auto result = keymaster_sign_object_for_cryptfs_scrypt(
183 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
184 to_sign_size, signature, signature_size);
185 switch (result) {
186 case KeymasterSignResult::ok:
187 return 0;
188 case KeymasterSignResult::upgrade:
189 break;
190 default:
191 return -1;
192 }
193 SLOGD("Upgrading key");
194 if (keymaster_upgrade_key_for_cryptfs_scrypt(
195 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
196 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
197 &ftr->keymaster_blob_size) != 0) {
198 SLOGE("Failed to upgrade key");
199 return -1;
200 }
201 if (put_crypt_ftr_and_key(ftr) != 0) {
202 SLOGE("Failed to write upgraded key to disk");
203 }
204 SLOGD("Key upgraded successfully");
205 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600206}
207
Paul Lawrence399317e2014-03-10 13:20:50 -0700208/* Store password when userdata is successfully decrypted and mounted.
209 * Cleared by cryptfs_clear_password
210 *
211 * To avoid a double prompt at boot, we need to store the CryptKeeper
212 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
213 * Since the entire framework is torn down and rebuilt after encryption,
214 * we have to use a daemon or similar to store the password. Since vold
215 * is secured against IPC except from system processes, it seems a reasonable
216 * place to store this.
217 *
218 * password should be cleared once it has been used.
219 *
220 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800221 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700222static char* password = 0;
223static int password_expiry_time = 0;
224static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800225
Paul Crowley14c8c072018-09-18 13:30:21 -0700226enum class RebootType { reboot, recovery, shutdown };
227static void cryptfs_reboot(RebootType rt) {
228 switch (rt) {
229 case RebootType::reboot:
230 property_set(ANDROID_RB_PROPERTY, "reboot");
231 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800232
Paul Crowley14c8c072018-09-18 13:30:21 -0700233 case RebootType::recovery:
234 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
235 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800236
Paul Crowley14c8c072018-09-18 13:30:21 -0700237 case RebootType::shutdown:
238 property_set(ANDROID_RB_PROPERTY, "shutdown");
239 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700240 }
Paul Lawrence87999172014-02-20 12:21:31 -0800241
Ken Sumralladfba362013-06-04 16:37:52 -0700242 sleep(20);
243
244 /* Shouldn't get here, reboot should happen before sleep times out */
245 return;
246}
247
Paul Crowley14c8c072018-09-18 13:30:21 -0700248static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800249 memset(io, 0, dataSize);
250 io->data_size = dataSize;
251 io->data_start = sizeof(struct dm_ioctl);
252 io->version[0] = 4;
253 io->version[1] = 0;
254 io->version[2] = 0;
255 io->flags = flags;
256 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100257 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800258 }
259}
260
Greg Kaiser38723f22018-02-16 13:35:35 -0800261namespace {
262
263struct CryptoType;
264
265// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700266const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800267
268struct CryptoType {
269 // We should only be constructing CryptoTypes as part of
270 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
271 // which isn't pure or fully protected as a concession to being able to
272 // do it all at compile time. Add new CryptoTypes in
273 // supported_crypto_types[] below.
274 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
275 constexpr CryptoType set_keysize(uint32_t size) const {
276 return CryptoType(this->property_name, this->crypto_name, size);
277 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700278 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800279 return CryptoType(property, this->crypto_name, this->keysize);
280 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700281 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800282 return CryptoType(this->property_name, crypto, this->keysize);
283 }
284
Paul Crowley14c8c072018-09-18 13:30:21 -0700285 constexpr const char* get_property_name() const { return property_name; }
286 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800287 constexpr uint32_t get_keysize() const { return keysize; }
288
Paul Crowley14c8c072018-09-18 13:30:21 -0700289 private:
290 const char* property_name;
291 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800292 uint32_t keysize;
293
Paul Crowley14c8c072018-09-18 13:30:21 -0700294 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800295 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700296 friend const CryptoType& get_crypto_type();
297 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800298};
299
300// We only want to parse this read-only property once. But we need to wait
301// until the system is initialized before we can read it. So we use a static
302// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700303const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800304 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
305 return crypto_type;
306}
307
308constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700309 .set_property_name("AES-128-CBC")
310 .set_crypto_name("aes-cbc-essiv:sha256")
311 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800312
313constexpr CryptoType supported_crypto_types[] = {
314 default_crypto_type,
Greg Kaiser38723f22018-02-16 13:35:35 -0800315 // Add new CryptoTypes here. Order is not important.
316};
317
Greg Kaiser38723f22018-02-16 13:35:35 -0800318// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
319// We confirm all supported_crypto_types have a small enough keysize and
320// had both set_property_name() and set_crypto_name() called.
321
322template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700323constexpr size_t array_length(T (&)[N]) {
324 return N;
325}
Greg Kaiser38723f22018-02-16 13:35:35 -0800326
327constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
328 return (index >= array_length(supported_crypto_types));
329}
330
Paul Crowley14c8c072018-09-18 13:30:21 -0700331constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800332 return ((crypto_type.get_property_name() != nullptr) &&
333 (crypto_type.get_crypto_name() != nullptr) &&
334 (crypto_type.get_keysize() <= MAX_KEY_LEN));
335}
336
337// Note in C++11 that constexpr functions can only have a single line.
338// So our code is a bit convoluted (using recursion instead of a loop),
339// but it's asserting at compile time that all of our key lengths are valid.
340constexpr bool validateSupportedCryptoTypes(size_t index) {
341 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700342 (isValidCryptoType(supported_crypto_types[index]) &&
343 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800344}
345
346static_assert(validateSupportedCryptoTypes(0),
347 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
348 "incompletely constructed.");
349// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
350
Greg Kaiser38723f22018-02-16 13:35:35 -0800351// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700352const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800353 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
354 char paramstr[PROPERTY_VALUE_MAX];
355
Paul Crowley14c8c072018-09-18 13:30:21 -0700356 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
357 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800358 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
359 return ctype;
360 }
361 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700362 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
363 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800364 return default_crypto_type;
365}
366
367} // namespace
368
Kenny Rootc4c70f12013-06-14 12:11:38 -0700369/**
370 * Gets the default device scrypt parameters for key derivation time tuning.
371 * The parameters should lead to about one second derivation time for the
372 * given device.
373 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700374static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700375 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000376 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700377
Paul Crowley63c18d32016-02-10 14:02:47 +0000378 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
379 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
380 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
381 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700382 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000383 ftr->N_factor = Nf;
384 ftr->r_factor = rf;
385 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700386}
387
Greg Kaiser57f9af62018-02-16 13:13:58 -0800388uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800389 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800390}
391
Paul Crowley14c8c072018-09-18 13:30:21 -0700392const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800393 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800394}
395
Paul Crowley14c8c072018-09-18 13:30:21 -0700396static unsigned int get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800397 int fd, block_size;
398 struct ext4_super_block sb;
399 off64_t len;
400
Paul Crowley14c8c072018-09-18 13:30:21 -0700401 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800402 SLOGE("Cannot open device to get filesystem size ");
403 return 0;
404 }
405
406 if (lseek64(fd, 1024, SEEK_SET) < 0) {
407 SLOGE("Cannot seek to superblock");
408 return 0;
409 }
410
411 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
412 SLOGE("Cannot read superblock");
413 return 0;
414 }
415
416 close(fd);
417
Daniel Rosenberge82df162014-08-15 22:19:23 +0000418 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
419 SLOGE("Not a valid ext4 superblock");
420 return 0;
421 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800422 block_size = 1024 << sb.s_log_block_size;
423 /* compute length in bytes */
Paul Crowley14c8c072018-09-18 13:30:21 -0700424 len = (((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800425
426 /* return length in sectors */
Paul Crowley14c8c072018-09-18 13:30:21 -0700427 return (unsigned int)(len / 512);
Ken Sumrall3ed82362011-01-28 23:31:16 -0800428}
429
Paul Crowley14c8c072018-09-18 13:30:21 -0700430static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
431 static int cached_data = 0;
432 static off64_t cached_off = 0;
433 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
434 int fd;
435 char key_loc[PROPERTY_VALUE_MAX];
436 char real_blkdev[PROPERTY_VALUE_MAX];
437 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700438
Paul Crowley14c8c072018-09-18 13:30:21 -0700439 if (!cached_data) {
440 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700441
Paul Crowley14c8c072018-09-18 13:30:21 -0700442 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
443 if ((fd = open(real_blkdev, O_RDWR | O_CLOEXEC)) < 0) {
444 SLOGE("Cannot open real block device %s\n", real_blkdev);
445 return -1;
446 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700447
Paul Crowley14c8c072018-09-18 13:30:21 -0700448 unsigned long nr_sec = 0;
449 get_blkdev_size(fd, &nr_sec);
450 if (nr_sec != 0) {
451 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
452 * encryption info footer and key, and plenty of bytes to spare for future
453 * growth.
454 */
455 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
456 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
457 cached_data = 1;
458 } else {
459 SLOGE("Cannot get size of block device %s\n", real_blkdev);
460 }
461 close(fd);
462 } else {
463 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
464 cached_off = 0;
465 cached_data = 1;
466 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700467 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700468
Paul Crowley14c8c072018-09-18 13:30:21 -0700469 if (cached_data) {
470 if (metadata_fname) {
471 *metadata_fname = cached_metadata_fname;
472 }
473 if (off) {
474 *off = cached_off;
475 }
476 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700477 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700478
Paul Crowley14c8c072018-09-18 13:30:21 -0700479 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700480}
481
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800482/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700483static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800484 SHA256_CTX c;
485 SHA256_Init(&c);
486 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
487 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
488 SHA256_Final(crypt_ftr->sha256, &c);
489}
490
Ken Sumralle8744072011-01-18 22:01:55 -0800491/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800492 * update the failed mount count but not change the key.
493 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700494static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
495 int fd;
496 unsigned int cnt;
497 /* starting_off is set to the SEEK_SET offset
498 * where the crypto structure starts
499 */
500 off64_t starting_off;
501 int rc = -1;
502 char* fname = NULL;
503 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800504
Paul Crowley14c8c072018-09-18 13:30:21 -0700505 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800506
Paul Crowley14c8c072018-09-18 13:30:21 -0700507 if (get_crypt_ftr_info(&fname, &starting_off)) {
508 SLOGE("Unable to get crypt_ftr_info\n");
509 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800510 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700511 if (fname[0] != '/') {
512 SLOGE("Unexpected value for crypto key location\n");
513 return -1;
514 }
515 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
516 SLOGE("Cannot open footer file %s for put\n", fname);
517 return -1;
518 }
Ken Sumralle8744072011-01-18 22:01:55 -0800519
Paul Crowley14c8c072018-09-18 13:30:21 -0700520 /* Seek to the start of the crypt footer */
521 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
522 SLOGE("Cannot seek to real block device footer\n");
523 goto errout;
524 }
525
526 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
527 SLOGE("Cannot write real block device footer\n");
528 goto errout;
529 }
530
531 fstat(fd, &statbuf);
532 /* If the keys are kept on a raw block device, do not try to truncate it. */
533 if (S_ISREG(statbuf.st_mode)) {
534 if (ftruncate(fd, 0x4000)) {
535 SLOGE("Cannot set footer file size\n");
536 goto errout;
537 }
538 }
539
540 /* Success! */
541 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800542
543errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700544 close(fd);
545 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800546}
547
Paul Crowley14c8c072018-09-18 13:30:21 -0700548static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800549 struct crypt_mnt_ftr copy;
550 memcpy(&copy, crypt_ftr, sizeof(copy));
551 set_ftr_sha(&copy);
552 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
553}
554
Paul Crowley14c8c072018-09-18 13:30:21 -0700555static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700556 return TEMP_FAILURE_RETRY(read(fd, buff, len));
557}
558
Paul Crowley14c8c072018-09-18 13:30:21 -0700559static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700560 return TEMP_FAILURE_RETRY(write(fd, buff, len));
561}
562
Paul Crowley14c8c072018-09-18 13:30:21 -0700563static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700564 memset(pdata, 0, len);
565 pdata->persist_magic = PERSIST_DATA_MAGIC;
566 pdata->persist_valid_entries = 0;
567}
568
569/* A routine to update the passed in crypt_ftr to the lastest version.
570 * fd is open read/write on the device that holds the crypto footer and persistent
571 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
572 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
573 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700574static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700575 int orig_major = crypt_ftr->major_version;
576 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700577
Kenny Root7434b312013-06-14 11:29:53 -0700578 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700579 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700580 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700581
Kenny Rootc4c70f12013-06-14 12:11:38 -0700582 SLOGW("upgrading crypto footer to 1.1");
583
Paul Crowley14c8c072018-09-18 13:30:21 -0700584 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700585 if (pdata == NULL) {
586 SLOGE("Cannot allocate persisent data\n");
587 return;
588 }
589 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
590
591 /* Need to initialize the persistent data area */
592 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
593 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100594 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700595 return;
596 }
597 /* Write all zeros to the first copy, making it invalid */
598 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
599
600 /* Write a valid but empty structure to the second copy */
601 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
602 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
603
604 /* Update the footer */
605 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
606 crypt_ftr->persist_data_offset[0] = pdata_offset;
607 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
608 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100609 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700610 }
611
Paul Lawrencef4faa572014-01-29 13:31:03 -0800612 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700613 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800614 /* But keep the old kdf_type.
615 * It will get updated later to KDF_SCRYPT after the password has been verified.
616 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700617 crypt_ftr->kdf_type = KDF_PBKDF2;
618 get_device_scrypt_params(crypt_ftr);
619 crypt_ftr->minor_version = 2;
620 }
621
Paul Lawrencef4faa572014-01-29 13:31:03 -0800622 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
623 SLOGW("upgrading crypto footer to 1.3");
624 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
625 crypt_ftr->minor_version = 3;
626 }
627
Kenny Root7434b312013-06-14 11:29:53 -0700628 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
629 if (lseek64(fd, offset, SEEK_SET) == -1) {
630 SLOGE("Cannot seek to crypt footer\n");
631 return;
632 }
633 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700634 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700635}
636
Paul Crowley14c8c072018-09-18 13:30:21 -0700637static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
638 int fd;
639 unsigned int cnt;
640 off64_t starting_off;
641 int rc = -1;
642 char* fname = NULL;
643 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700644
Paul Crowley14c8c072018-09-18 13:30:21 -0700645 if (get_crypt_ftr_info(&fname, &starting_off)) {
646 SLOGE("Unable to get crypt_ftr_info\n");
647 return -1;
648 }
649 if (fname[0] != '/') {
650 SLOGE("Unexpected value for crypto key location\n");
651 return -1;
652 }
653 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
654 SLOGE("Cannot open footer file %s for get\n", fname);
655 return -1;
656 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800657
Paul Crowley14c8c072018-09-18 13:30:21 -0700658 /* Make sure it's 16 Kbytes in length */
659 fstat(fd, &statbuf);
660 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
661 SLOGE("footer file %s is not the expected size!\n", fname);
662 goto errout;
663 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700664
Paul Crowley14c8c072018-09-18 13:30:21 -0700665 /* Seek to the start of the crypt footer */
666 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
667 SLOGE("Cannot seek to real block device footer\n");
668 goto errout;
669 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700670
Paul Crowley14c8c072018-09-18 13:30:21 -0700671 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
672 SLOGE("Cannot read real block device footer\n");
673 goto errout;
674 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800675
Paul Crowley14c8c072018-09-18 13:30:21 -0700676 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
677 SLOGE("Bad magic for real block device %s\n", fname);
678 goto errout;
679 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800680
Paul Crowley14c8c072018-09-18 13:30:21 -0700681 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
682 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
683 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
684 goto errout;
685 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800686
Paul Crowley14c8c072018-09-18 13:30:21 -0700687 // We risk buffer overflows with oversized keys, so we just reject them.
688 // 0-sized keys are problematic (essentially by-passing encryption), and
689 // AES-CBC key wrapping only works for multiples of 16 bytes.
690 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
691 (crypt_ftr->keysize > MAX_KEY_LEN)) {
692 SLOGE(
693 "Invalid keysize (%u) for block device %s; Must be non-zero, "
694 "divisible by 16, and <= %d\n",
695 crypt_ftr->keysize, fname, MAX_KEY_LEN);
696 goto errout;
697 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800698
Paul Crowley14c8c072018-09-18 13:30:21 -0700699 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
700 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
701 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
702 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800703
Paul Crowley14c8c072018-09-18 13:30:21 -0700704 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
705 * copy on disk before returning.
706 */
707 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
708 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
709 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800710
Paul Crowley14c8c072018-09-18 13:30:21 -0700711 /* Success! */
712 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800713
714errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700715 close(fd);
716 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800717}
718
Paul Crowley14c8c072018-09-18 13:30:21 -0700719static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700720 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
721 crypt_ftr->persist_data_offset[1]) {
722 SLOGE("Crypt_ftr persist data regions overlap");
723 return -1;
724 }
725
726 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
727 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
728 return -1;
729 }
730
731 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700732 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700733 CRYPT_FOOTER_OFFSET) {
734 SLOGE("Persistent data extends past crypto footer");
735 return -1;
736 }
737
738 return 0;
739}
740
Paul Crowley14c8c072018-09-18 13:30:21 -0700741static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700742 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700743 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700744 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700745 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700746 int found = 0;
747 int fd;
748 int ret;
749 int i;
750
751 if (persist_data) {
752 /* Nothing to do, we've already loaded or initialized it */
753 return 0;
754 }
755
Ken Sumrall160b4d62013-04-22 12:15:39 -0700756 /* If not encrypted, just allocate an empty table and initialize it */
757 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700758 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800759 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700760 if (pdata) {
761 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
762 persist_data = pdata;
763 return 0;
764 }
765 return -1;
766 }
767
Paul Crowley14c8c072018-09-18 13:30:21 -0700768 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700769 return -1;
770 }
771
Paul Crowley14c8c072018-09-18 13:30:21 -0700772 if ((crypt_ftr.major_version < 1) ||
773 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700774 SLOGE("Crypt_ftr version doesn't support persistent data");
775 return -1;
776 }
777
778 if (get_crypt_ftr_info(&fname, NULL)) {
779 return -1;
780 }
781
782 ret = validate_persistent_data_storage(&crypt_ftr);
783 if (ret) {
784 return -1;
785 }
786
Paul Crowley14c8c072018-09-18 13:30:21 -0700787 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700788 if (fd < 0) {
789 SLOGE("Cannot open %s metadata file", fname);
790 return -1;
791 }
792
Wei Wang4375f1b2017-02-24 17:43:01 -0800793 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800794 if (pdata == NULL) {
795 SLOGE("Cannot allocate memory for persistent data");
796 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700797 }
798
799 for (i = 0; i < 2; i++) {
800 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
801 SLOGE("Cannot seek to read persistent data on %s", fname);
802 goto err2;
803 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700804 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700805 SLOGE("Error reading persistent data on iteration %d", i);
806 goto err2;
807 }
808 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
809 found = 1;
810 break;
811 }
812 }
813
814 if (!found) {
815 SLOGI("Could not find valid persistent data, creating");
816 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
817 }
818
819 /* Success */
820 persist_data = pdata;
821 close(fd);
822 return 0;
823
824err2:
825 free(pdata);
826
827err:
828 close(fd);
829 return -1;
830}
831
Paul Crowley14c8c072018-09-18 13:30:21 -0700832static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700833 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700834 struct crypt_persist_data* pdata;
835 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700836 off64_t write_offset;
837 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700838 int fd;
839 int ret;
840
841 if (persist_data == NULL) {
842 SLOGE("No persistent data to save");
843 return -1;
844 }
845
Paul Crowley14c8c072018-09-18 13:30:21 -0700846 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700847 return -1;
848 }
849
Paul Crowley14c8c072018-09-18 13:30:21 -0700850 if ((crypt_ftr.major_version < 1) ||
851 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700852 SLOGE("Crypt_ftr version doesn't support persistent data");
853 return -1;
854 }
855
856 ret = validate_persistent_data_storage(&crypt_ftr);
857 if (ret) {
858 return -1;
859 }
860
861 if (get_crypt_ftr_info(&fname, NULL)) {
862 return -1;
863 }
864
Paul Crowley14c8c072018-09-18 13:30:21 -0700865 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700866 if (fd < 0) {
867 SLOGE("Cannot open %s metadata file", fname);
868 return -1;
869 }
870
Wei Wang4375f1b2017-02-24 17:43:01 -0800871 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700872 if (pdata == NULL) {
873 SLOGE("Cannot allocate persistant data");
874 goto err;
875 }
876
877 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
878 SLOGE("Cannot seek to read persistent data on %s", fname);
879 goto err2;
880 }
881
882 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700883 SLOGE("Error reading persistent data before save");
884 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700885 }
886
887 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
888 /* The first copy is the curent valid copy, so write to
889 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700890 write_offset = crypt_ftr.persist_data_offset[1];
891 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700892 } else {
893 /* The second copy must be the valid copy, so write to
894 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700895 write_offset = crypt_ftr.persist_data_offset[0];
896 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700897 }
898
899 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100900 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700901 SLOGE("Cannot seek to write persistent data");
902 goto err2;
903 }
904 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700905 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100906 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700907 SLOGE("Cannot seek to erase previous persistent data");
908 goto err2;
909 }
910 fsync(fd);
911 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -0700912 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700913 SLOGE("Cannot write to erase previous persistent data");
914 goto err2;
915 }
916 fsync(fd);
917 } else {
918 SLOGE("Cannot write to save persistent data");
919 goto err2;
920 }
921
922 /* Success */
923 free(pdata);
924 close(fd);
925 return 0;
926
927err2:
928 free(pdata);
929err:
930 close(fd);
931 return -1;
932}
933
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800934/* Convert a binary key of specified length into an ascii hex string equivalent,
935 * without the leading 0x and with null termination
936 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700937static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
938 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700939 unsigned int i, a;
940 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941
Paul Crowley14c8c072018-09-18 13:30:21 -0700942 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700943 /* For each byte, write out two ascii hex digits */
944 nibble = (master_key[i] >> 4) & 0xf;
945 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800946
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700947 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -0700948 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700949 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800950
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700951 /* Add the null termination */
952 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800953}
954
Paul Crowley14c8c072018-09-18 13:30:21 -0700955static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
956 const unsigned char* master_key, const char* real_blk_name,
957 const char* name, int fd, const char* extra_params) {
958 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
959 struct dm_ioctl* io;
960 struct dm_target_spec* tgt;
961 char* crypt_params;
962 // We need two ASCII characters to represent each byte, and need space for
963 // the '\0' terminator.
964 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
965 size_t buff_offset;
966 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800967
Paul Crowley14c8c072018-09-18 13:30:21 -0700968 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800969
Paul Crowley14c8c072018-09-18 13:30:21 -0700970 /* Load the mapping table for this device */
971 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800972
Paul Crowley14c8c072018-09-18 13:30:21 -0700973 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
974 io->target_count = 1;
975 tgt->status = 0;
976 tgt->sector_start = 0;
977 tgt->length = crypt_ftr->fs_size;
978 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800979
Paul Crowley14c8c072018-09-18 13:30:21 -0700980 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
981 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800982
Paul Crowley14c8c072018-09-18 13:30:21 -0700983 buff_offset = crypt_params - buffer;
984 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
985 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
986 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
987 crypt_params += strlen(crypt_params) + 1;
988 crypt_params =
989 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
990 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800991
Paul Crowley14c8c072018-09-18 13:30:21 -0700992 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
993 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
994 break;
995 }
996 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800997 }
Ken Sumralldb5e0262013-02-05 17:39:48 -0800998
Paul Crowley14c8c072018-09-18 13:30:21 -0700999 if (i == TABLE_LOAD_RETRIES) {
1000 /* We failed to load the table, return an error */
1001 return -1;
1002 } else {
1003 return i + 1;
1004 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001005}
1006
Paul Crowley14c8c072018-09-18 13:30:21 -07001007static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001008 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001009 struct dm_ioctl* io;
1010 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001011
Paul Crowley14c8c072018-09-18 13:30:21 -07001012 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001013
1014 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1015
1016 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1017 return -1;
1018 }
1019
1020 /* Iterate over the returned versions, looking for name of "crypt".
1021 * When found, get and return the version.
1022 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001023 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001024 while (v->next) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001025 if (!strcmp(v->name, "crypt")) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001026 /* We found the crypt driver, return the version, and get out */
1027 version[0] = v->version[0];
1028 version[1] = v->version[1];
1029 version[2] = v->version[2];
1030 return 0;
1031 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001032 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001033 }
1034
1035 return -1;
1036}
1037
Paul Crowley5afbc622017-11-27 09:42:17 -08001038static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1039 if (extra_params_vec.empty()) return "";
1040 std::string extra_params = std::to_string(extra_params_vec.size());
1041 for (const auto& p : extra_params_vec) {
1042 extra_params.append(" ");
1043 extra_params.append(p);
1044 }
1045 return extra_params;
1046}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001047
Paul Crowley5afbc622017-11-27 09:42:17 -08001048static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1049 const char* real_blk_name, char* crypto_blk_name, const char* name,
1050 uint32_t flags) {
1051 char buffer[DM_CRYPT_BUF_SIZE];
1052 struct dm_ioctl* io;
1053 unsigned int minor;
1054 int fd = 0;
1055 int err;
1056 int retval = -1;
1057 int version[3];
1058 int load_count;
1059 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001060
Paul Crowley5afbc622017-11-27 09:42:17 -08001061 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1062 SLOGE("Cannot open device-mapper\n");
1063 goto errout;
1064 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001065
Paul Crowley5afbc622017-11-27 09:42:17 -08001066 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001067
Paul Crowley5afbc622017-11-27 09:42:17 -08001068 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1069 err = ioctl(fd, DM_DEV_CREATE, io);
1070 if (err) {
1071 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1072 goto errout;
1073 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001074
Paul Crowley5afbc622017-11-27 09:42:17 -08001075 /* Get the device status, in particular, the name of it's device file */
1076 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1077 if (ioctl(fd, DM_DEV_STATUS, io)) {
1078 SLOGE("Cannot retrieve dm-crypt device status\n");
1079 goto errout;
1080 }
1081 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1082 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001083
Paul Crowley5afbc622017-11-27 09:42:17 -08001084 if (!get_dm_crypt_version(fd, name, version)) {
1085 /* Support for allow_discards was added in version 1.11.0 */
1086 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1087 extra_params_vec.emplace_back("allow_discards");
1088 }
1089 }
1090 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1091 extra_params_vec.emplace_back("allow_encrypt_override");
1092 }
1093 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1094 extra_params_as_string(extra_params_vec).c_str());
1095 if (load_count < 0) {
1096 SLOGE("Cannot load dm-crypt mapping table.\n");
1097 goto errout;
1098 } else if (load_count > 1) {
1099 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1100 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001101
Paul Crowley5afbc622017-11-27 09:42:17 -08001102 /* Resume this device to activate it */
1103 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001104
Paul Crowley5afbc622017-11-27 09:42:17 -08001105 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1106 SLOGE("Cannot resume the dm-crypt device\n");
1107 goto errout;
1108 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001109
Paul Crowley5afbc622017-11-27 09:42:17 -08001110 /* We made it here with no errors. Woot! */
1111 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001112
1113errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001114 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 -08001115
Paul Crowley14c8c072018-09-18 13:30:21 -07001116 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117}
1118
Paul Crowley14c8c072018-09-18 13:30:21 -07001119static int delete_crypto_blk_dev(const char* name) {
1120 int fd;
1121 char buffer[DM_CRYPT_BUF_SIZE];
1122 struct dm_ioctl* io;
1123 int retval = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001124
Paul Crowley14c8c072018-09-18 13:30:21 -07001125 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1126 SLOGE("Cannot open device-mapper\n");
1127 goto errout;
1128 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001129
Paul Crowley14c8c072018-09-18 13:30:21 -07001130 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131
Paul Crowley14c8c072018-09-18 13:30:21 -07001132 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1133 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1134 SLOGE("Cannot remove dm-crypt device\n");
1135 goto errout;
1136 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001137
Paul Crowley14c8c072018-09-18 13:30:21 -07001138 /* We made it here with no errors. Woot! */
1139 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001140
1141errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001142 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 -08001143
Paul Crowley14c8c072018-09-18 13:30:21 -07001144 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001145}
1146
Paul Crowley14c8c072018-09-18 13:30:21 -07001147static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1148 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001149 SLOGI("Using pbkdf2 for cryptfs KDF");
1150
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001151 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001152 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1153 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001154}
1155
Paul Crowley14c8c072018-09-18 13:30:21 -07001156static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001157 SLOGI("Using scrypt for cryptfs KDF");
1158
Paul Crowley14c8c072018-09-18 13:30:21 -07001159 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001160
1161 int N = 1 << ftr->N_factor;
1162 int r = 1 << ftr->r_factor;
1163 int p = 1 << ftr->p_factor;
1164
1165 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001166 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001167 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001168
Paul Crowley14c8c072018-09-18 13:30:21 -07001169 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001170}
1171
Paul Crowley14c8c072018-09-18 13:30:21 -07001172static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1173 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001174 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1175
1176 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001177 size_t signature_size;
1178 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001179 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001180
1181 int N = 1 << ftr->N_factor;
1182 int r = 1 << ftr->r_factor;
1183 int p = 1 << ftr->p_factor;
1184
Paul Crowley14c8c072018-09-18 13:30:21 -07001185 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001186 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001187
1188 if (rc) {
1189 SLOGE("scrypt failed");
1190 return -1;
1191 }
1192
Paul Crowley14c8c072018-09-18 13:30:21 -07001193 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001194 SLOGE("Signing failed");
1195 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001196 }
1197
Paul Crowley14c8c072018-09-18 13:30:21 -07001198 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1199 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001200 free(signature);
1201
1202 if (rc) {
1203 SLOGE("scrypt failed");
1204 return -1;
1205 }
1206
1207 return 0;
1208}
1209
Paul Crowley14c8c072018-09-18 13:30:21 -07001210static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1211 const unsigned char* decrypted_master_key,
1212 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1213 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001214 EVP_CIPHER_CTX e_ctx;
1215 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001216 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001217
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001218 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001219 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001220
1221 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001222 case KDF_SCRYPT_KEYMASTER:
1223 if (keymaster_create_key(crypt_ftr)) {
1224 SLOGE("keymaster_create_key failed");
1225 return -1;
1226 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001227
Paul Crowley14c8c072018-09-18 13:30:21 -07001228 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1229 SLOGE("scrypt failed");
1230 return -1;
1231 }
1232 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001233
Paul Crowley14c8c072018-09-18 13:30:21 -07001234 case KDF_SCRYPT:
1235 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1236 SLOGE("scrypt failed");
1237 return -1;
1238 }
1239 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001240
Paul Crowley14c8c072018-09-18 13:30:21 -07001241 default:
1242 SLOGE("Invalid kdf_type");
1243 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001244 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001245
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001246 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001247 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001248 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1249 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001250 SLOGE("EVP_EncryptInit failed\n");
1251 return -1;
1252 }
1253 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001254
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001255 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001256 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1257 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001258 SLOGE("EVP_EncryptUpdate failed\n");
1259 return -1;
1260 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001261 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001262 SLOGE("EVP_EncryptFinal failed\n");
1263 return -1;
1264 }
1265
Greg Kaiser59ad0182018-02-16 13:01:36 -08001266 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001267 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1268 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001269 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001270
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001271 /* Store the scrypt of the intermediate key, so we can validate if it's a
1272 password error or mount error when things go wrong.
1273 Note there's no need to check for errors, since if this is incorrect, we
1274 simply won't wipe userdata, which is the correct default behavior
1275 */
1276 int N = 1 << crypt_ftr->N_factor;
1277 int r = 1 << crypt_ftr->r_factor;
1278 int p = 1 << crypt_ftr->p_factor;
1279
Paul Crowley14c8c072018-09-18 13:30:21 -07001280 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1281 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001282 sizeof(crypt_ftr->scrypted_intermediate_key));
1283
1284 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001285 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001286 }
1287
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001288 EVP_CIPHER_CTX_cleanup(&e_ctx);
1289
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001290 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001291}
1292
Paul Crowley14c8c072018-09-18 13:30:21 -07001293static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1294 const unsigned char* encrypted_master_key, size_t keysize,
1295 unsigned char* decrypted_master_key, kdf_func kdf,
1296 void* kdf_params, unsigned char** intermediate_key,
1297 size_t* intermediate_key_size) {
1298 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1299 EVP_CIPHER_CTX d_ctx;
1300 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001301
Paul Crowley14c8c072018-09-18 13:30:21 -07001302 /* Turn the password into an intermediate key and IV that can decrypt the
1303 master key */
1304 if (kdf(passwd, salt, ikey, kdf_params)) {
1305 SLOGE("kdf failed");
1306 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001307 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001308
Paul Crowley14c8c072018-09-18 13:30:21 -07001309 /* Initialize the decryption engine */
1310 EVP_CIPHER_CTX_init(&d_ctx);
1311 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1312 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1313 return -1;
1314 }
1315 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1316 /* Decrypt the master key */
1317 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1318 keysize)) {
1319 return -1;
1320 }
1321 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1322 return -1;
1323 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001324
Paul Crowley14c8c072018-09-18 13:30:21 -07001325 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1326 return -1;
1327 }
1328
1329 /* Copy intermediate key if needed by params */
1330 if (intermediate_key && intermediate_key_size) {
1331 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1332 if (*intermediate_key) {
1333 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1334 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1335 }
1336 }
1337
1338 EVP_CIPHER_CTX_cleanup(&d_ctx);
1339
1340 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001341}
1342
Paul Crowley14c8c072018-09-18 13:30:21 -07001343static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001344 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001345 *kdf = scrypt_keymaster;
1346 *kdf_params = ftr;
1347 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001348 *kdf = scrypt;
1349 *kdf_params = ftr;
1350 } else {
1351 *kdf = pbkdf2;
1352 *kdf_params = NULL;
1353 }
1354}
1355
Paul Crowley14c8c072018-09-18 13:30:21 -07001356static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1357 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1358 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001359 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001360 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001361 int ret;
1362
1363 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001364 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1365 decrypted_master_key, kdf, kdf_params, intermediate_key,
1366 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001367 if (ret != 0) {
1368 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001369 }
1370
1371 return ret;
1372}
1373
Paul Crowley14c8c072018-09-18 13:30:21 -07001374static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1375 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001376 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001377 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001378
1379 /* Get some random bits for a key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001380 fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001381 read(fd, key_buf, sizeof(key_buf));
1382 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001383 close(fd);
1384
1385 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001386 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001387}
1388
Paul Crowley14c8c072018-09-18 13:30:21 -07001389int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001390 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001391#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001392
1393 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001394 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001395 if (umount(mountpoint) == 0) {
1396 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001397 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001398
1399 if (errno == EINVAL) {
1400 /* EINVAL is returned if the directory is not a mountpoint,
1401 * i.e. there is no filesystem mounted there. So just get out.
1402 */
1403 break;
1404 }
1405
1406 err = errno;
1407
1408 /* If allowed, be increasingly aggressive before the last two retries */
1409 if (kill) {
1410 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1411 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001412 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001413 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1414 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001415 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001416 }
1417 }
1418
1419 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001420 }
1421
1422 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001423 SLOGD("unmounting %s succeeded\n", mountpoint);
1424 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001425 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001426 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1427 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1428 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001429 }
1430
1431 return rc;
1432}
1433
Paul Crowley14c8c072018-09-18 13:30:21 -07001434static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001435 // NOTE: post_fs_data results in init calling back around to vold, so all
1436 // callers to this method must be async
1437
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001438 /* Do the prep of the /data filesystem */
1439 property_set("vold.post_fs_data_done", "0");
1440 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001441 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001442
Ken Sumrallc5872692013-05-14 15:26:31 -07001443 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001444 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001445 /* We timed out to prep /data in time. Continue wait. */
1446 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001447 }
Wei Wang42e38102017-06-07 10:46:12 -07001448 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001449}
1450
Paul Crowley14c8c072018-09-18 13:30:21 -07001451static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001452 // Mark the footer as bad
1453 struct crypt_mnt_ftr crypt_ftr;
1454 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1455 SLOGE("Failed to get crypto footer - panic");
1456 return;
1457 }
1458
1459 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1460 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1461 SLOGE("Failed to set crypto footer - panic");
1462 return;
1463 }
1464}
1465
Paul Crowley14c8c072018-09-18 13:30:21 -07001466static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001467 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001468 SLOGE("Failed to mount tmpfs on data - panic");
1469 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001470 }
1471
1472 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1473 SLOGE("Failed to trigger post fs data - panic");
1474 return;
1475 }
1476
1477 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1478 SLOGE("Failed to trigger restart min framework - panic");
1479 return;
1480 }
1481}
1482
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001483/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001484static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001485 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001486 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001487 static int restart_successful = 0;
1488
1489 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001490 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001491 SLOGE("Encrypted filesystem not validated, aborting");
1492 return -1;
1493 }
1494
1495 if (restart_successful) {
1496 SLOGE("System already restarted with encrypted disk, aborting");
1497 return -1;
1498 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001499
Paul Lawrencef4faa572014-01-29 13:31:03 -08001500 if (restart_main) {
1501 /* Here is where we shut down the framework. The init scripts
1502 * start all services in one of three classes: core, main or late_start.
1503 * On boot, we start core and main. Now, we stop main, but not core,
1504 * as core includes vold and a few other really important things that
1505 * we need to keep running. Once main has stopped, we should be able
1506 * to umount the tmpfs /data, then mount the encrypted /data.
1507 * We then restart the class main, and also the class late_start.
1508 * At the moment, I've only put a few things in late_start that I know
1509 * are not needed to bring up the framework, and that also cause problems
1510 * with unmounting the tmpfs /data, but I hope to add add more services
1511 * to the late_start class as we optimize this to decrease the delay
1512 * till the user is asked for the password to the filesystem.
1513 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001514
Paul Lawrencef4faa572014-01-29 13:31:03 -08001515 /* The init files are setup to stop the class main when vold.decrypt is
1516 * set to trigger_reset_main.
1517 */
1518 property_set("vold.decrypt", "trigger_reset_main");
1519 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001520
Paul Lawrencef4faa572014-01-29 13:31:03 -08001521 /* Ugh, shutting down the framework is not synchronous, so until it
1522 * can be fixed, this horrible hack will wait a moment for it all to
1523 * shut down before proceeding. Without it, some devices cannot
1524 * restart the graphics services.
1525 */
1526 sleep(2);
1527 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001528
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001529 /* Now that the framework is shutdown, we should be able to umount()
1530 * the tmpfs filesystem, and mount the real one.
1531 */
1532
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001533 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1534 if (strlen(crypto_blkdev) == 0) {
1535 SLOGE("fs_crypto_blkdev not set\n");
1536 return -1;
1537 }
1538
Paul Crowley14c8c072018-09-18 13:30:21 -07001539 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001540 /* If ro.crypto.readonly is set to 1, mount the decrypted
1541 * filesystem readonly. This is used when /data is mounted by
1542 * recovery mode.
1543 */
1544 char ro_prop[PROPERTY_VALUE_MAX];
1545 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001546 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001547 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001548 if (rec) {
1549 rec->flags |= MS_RDONLY;
1550 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001551 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001552
Ken Sumralle5032c42012-04-01 23:58:44 -07001553 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001554 int retries = RETRY_MOUNT_ATTEMPTS;
1555 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001556
1557 /*
1558 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1559 * partitions in the fsck domain.
1560 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001561 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001562 SLOGE("Failed to setexeccon");
1563 return -1;
1564 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001565 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001566 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1567 /* TODO: invoke something similar to
1568 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1569 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001570 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001571 if (--retries) {
1572 sleep(RETRY_MOUNT_DELAY_SECONDS);
1573 } else {
1574 /* Let's hope that a reboot clears away whatever is keeping
1575 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001576 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001577 }
1578 } else {
1579 SLOGE("Failed to mount decrypted data");
1580 cryptfs_set_corrupt();
1581 cryptfs_trigger_restart_min_framework();
1582 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001583 if (setexeccon(NULL)) {
1584 SLOGE("Failed to setexeccon");
1585 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001586 return -1;
1587 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001588 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001589 if (setexeccon(NULL)) {
1590 SLOGE("Failed to setexeccon");
1591 return -1;
1592 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001593
Ken Sumralle5032c42012-04-01 23:58:44 -07001594 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001595 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001596 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001597
1598 /* startup service classes main and late_start */
1599 property_set("vold.decrypt", "trigger_restart_framework");
1600 SLOGD("Just triggered restart_framework\n");
1601
1602 /* Give it a few moments to get started */
1603 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001604 }
1605
Ken Sumrall0cc16632011-01-18 20:32:26 -08001606 if (rc == 0) {
1607 restart_successful = 1;
1608 }
1609
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001610 return rc;
1611}
1612
Paul Crowley14c8c072018-09-18 13:30:21 -07001613int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001614 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001615 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001616 SLOGE("cryptfs_restart not valid for file encryption:");
1617 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001618 }
1619
Paul Lawrencef4faa572014-01-29 13:31:03 -08001620 /* Call internal implementation forcing a restart of main service group */
1621 return cryptfs_restart_internal(1);
1622}
1623
Paul Crowley14c8c072018-09-18 13:30:21 -07001624static int do_crypto_complete(const char* mount_point) {
1625 struct crypt_mnt_ftr crypt_ftr;
1626 char encrypted_state[PROPERTY_VALUE_MAX];
1627 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001628
Paul Crowley14c8c072018-09-18 13:30:21 -07001629 property_get("ro.crypto.state", encrypted_state, "");
1630 if (strcmp(encrypted_state, "encrypted")) {
1631 SLOGE("not running with encryption, aborting");
1632 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001633 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001634
Paul Crowley14c8c072018-09-18 13:30:21 -07001635 // crypto_complete is full disk encrypted status
1636 if (e4crypt_is_native()) {
1637 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1638 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001639
Paul Crowley14c8c072018-09-18 13:30:21 -07001640 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1641 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001642
Paul Crowley14c8c072018-09-18 13:30:21 -07001643 /*
1644 * Only report this error if key_loc is a file and it exists.
1645 * If the device was never encrypted, and /data is not mountable for
1646 * some reason, returning 1 should prevent the UI from presenting the
1647 * a "enter password" screen, or worse, a "press button to wipe the
1648 * device" screen.
1649 */
1650 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1651 SLOGE("master key file does not exist, aborting");
1652 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1653 } else {
1654 SLOGE("Error getting crypt footer and key\n");
1655 return CRYPTO_COMPLETE_BAD_METADATA;
1656 }
1657 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001658
Paul Crowley14c8c072018-09-18 13:30:21 -07001659 // Test for possible error flags
1660 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1661 SLOGE("Encryption process is partway completed\n");
1662 return CRYPTO_COMPLETE_PARTIAL;
1663 }
1664
1665 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1666 SLOGE("Encryption process was interrupted but cannot continue\n");
1667 return CRYPTO_COMPLETE_INCONSISTENT;
1668 }
1669
1670 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1671 SLOGE("Encryption is successful but data is corrupt\n");
1672 return CRYPTO_COMPLETE_CORRUPT;
1673 }
1674
1675 /* We passed the test! We shall diminish, and return to the west */
1676 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001677}
1678
Paul Crowley14c8c072018-09-18 13:30:21 -07001679static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1680 const char* mount_point, const char* label) {
1681 unsigned char decrypted_master_key[MAX_KEY_LEN];
1682 char crypto_blkdev[MAXPATHLEN];
1683 char real_blkdev[MAXPATHLEN];
1684 char tmp_mount_point[64];
1685 unsigned int orig_failed_decrypt_count;
1686 int rc;
1687 int use_keymaster = 0;
1688 int upgrade = 0;
1689 unsigned char* intermediate_key = 0;
1690 size_t intermediate_key_size = 0;
1691 int N = 1 << crypt_ftr->N_factor;
1692 int r = 1 << crypt_ftr->r_factor;
1693 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001694
Paul Crowley14c8c072018-09-18 13:30:21 -07001695 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1696 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001697
Paul Crowley14c8c072018-09-18 13:30:21 -07001698 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1699 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1700 &intermediate_key_size)) {
1701 SLOGE("Failed to decrypt master key\n");
1702 rc = -1;
1703 goto errout;
1704 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001705 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001706
Paul Crowley14c8c072018-09-18 13:30:21 -07001707 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001708
Paul Crowley14c8c072018-09-18 13:30:21 -07001709 // Create crypto block device - all (non fatal) code paths
1710 // need it
1711 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
1712 0)) {
1713 SLOGE("Error creating decrypted block device\n");
1714 rc = -1;
1715 goto errout;
1716 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717
Paul Crowley14c8c072018-09-18 13:30:21 -07001718 /* Work out if the problem is the password or the data */
1719 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001720
Paul Crowley14c8c072018-09-18 13:30:21 -07001721 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1722 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1723 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001724
Paul Crowley14c8c072018-09-18 13:30:21 -07001725 // Does the key match the crypto footer?
1726 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1727 sizeof(scrypted_intermediate_key)) == 0) {
1728 SLOGI("Password matches");
1729 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001730 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001731 /* Try mounting the file system anyway, just in case the problem's with
1732 * the footer, not the key. */
1733 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1734 mkdir(tmp_mount_point, 0755);
1735 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1736 SLOGE("Error temp mounting decrypted block device\n");
1737 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001738
Paul Crowley14c8c072018-09-18 13:30:21 -07001739 rc = ++crypt_ftr->failed_decrypt_count;
1740 put_crypt_ftr_and_key(crypt_ftr);
1741 } else {
1742 /* Success! */
1743 SLOGI("Password did not match but decrypted drive mounted - continue");
1744 umount(tmp_mount_point);
1745 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001746 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001747 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001748
Paul Crowley14c8c072018-09-18 13:30:21 -07001749 if (rc == 0) {
1750 crypt_ftr->failed_decrypt_count = 0;
1751 if (orig_failed_decrypt_count != 0) {
1752 put_crypt_ftr_and_key(crypt_ftr);
1753 }
1754
1755 /* Save the name of the crypto block device
1756 * so we can mount it when restarting the framework. */
1757 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1758
1759 /* Also save a the master key so we can reencrypted the key
1760 * the key when we want to change the password on it. */
1761 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1762 saved_mount_point = strdup(mount_point);
1763 master_key_saved = 1;
1764 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1765 rc = 0;
1766
1767 // Upgrade if we're not using the latest KDF.
1768 use_keymaster = keymaster_check_compatibility();
1769 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1770 // Don't allow downgrade
1771 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1772 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1773 upgrade = 1;
1774 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1775 crypt_ftr->kdf_type = KDF_SCRYPT;
1776 upgrade = 1;
1777 }
1778
1779 if (upgrade) {
1780 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1781 crypt_ftr->master_key, crypt_ftr);
1782 if (!rc) {
1783 rc = put_crypt_ftr_and_key(crypt_ftr);
1784 }
1785 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1786
1787 // Do not fail even if upgrade failed - machine is bootable
1788 // Note that if this code is ever hit, there is a *serious* problem
1789 // since KDFs should never fail. You *must* fix the kdf before
1790 // proceeding!
1791 if (rc) {
1792 SLOGW(
1793 "Upgrade failed with error %d,"
1794 " but continuing with previous state",
1795 rc);
1796 rc = 0;
1797 }
1798 }
1799 }
1800
1801errout:
1802 if (intermediate_key) {
1803 memset(intermediate_key, 0, intermediate_key_size);
1804 free(intermediate_key);
1805 }
1806 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001807}
1808
Ken Sumrall29d8da82011-05-18 17:20:07 -07001809/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001810 * Called by vold when it's asked to mount an encrypted external
1811 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001812 * as any metadata is been stored in a separate, small partition. We
1813 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001814 *
1815 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001816 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001817int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1818 char* out_crypto_blkdev) {
1819 int fd = open(real_blkdev, O_RDONLY | O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001820 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001821 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001822 return -1;
1823 }
1824
1825 unsigned long nr_sec = 0;
1826 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001827 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001828
Ken Sumrall29d8da82011-05-18 17:20:07 -07001829 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001830 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001831 return -1;
1832 }
1833
Jeff Sharkey9c484982015-03-31 10:35:33 -07001834 struct crypt_mnt_ftr ext_crypt_ftr;
1835 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1836 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001837 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001838 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001839 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001840 uint32_t flags = 0;
1841 if (e4crypt_is_native() &&
1842 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1843 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001844
Paul Crowley385cb8c2018-03-29 13:27:23 -07001845 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001846}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001847
Jeff Sharkey9c484982015-03-31 10:35:33 -07001848/*
1849 * Called by vold when it's asked to unmount an encrypted external
1850 * storage volume.
1851 */
1852int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001853 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001854}
1855
Paul Crowley14c8c072018-09-18 13:30:21 -07001856int cryptfs_crypto_complete(void) {
1857 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001858}
1859
Paul Crowley14c8c072018-09-18 13:30:21 -07001860int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001861 char encrypted_state[PROPERTY_VALUE_MAX];
1862 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001863 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1864 SLOGE(
1865 "encrypted fs already validated or not running with encryption,"
1866 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001867 return -1;
1868 }
1869
1870 if (get_crypt_ftr_and_key(crypt_ftr)) {
1871 SLOGE("Error getting crypt footer and key");
1872 return -1;
1873 }
1874
1875 return 0;
1876}
1877
Paul Crowley14c8c072018-09-18 13:30:21 -07001878int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001879 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001880 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001881 SLOGE("cryptfs_check_passwd not valid for file encryption");
1882 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001883 }
1884
Paul Lawrencef4faa572014-01-29 13:31:03 -08001885 struct crypt_mnt_ftr crypt_ftr;
1886 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001887
Paul Lawrencef4faa572014-01-29 13:31:03 -08001888 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001889 if (rc) {
1890 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001891 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001892 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001893
Paul Crowley14c8c072018-09-18 13:30:21 -07001894 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001895 if (rc) {
1896 SLOGE("Password did not match");
1897 return rc;
1898 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001899
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001900 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1901 // Here we have a default actual password but a real password
1902 // we must test against the scrypted value
1903 // First, we must delete the crypto block device that
1904 // test_mount_encrypted_fs leaves behind as a side effect
1905 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001906 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1907 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001908 if (rc) {
1909 SLOGE("Default password did not match on reboot encryption");
1910 return rc;
1911 }
1912
1913 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1914 put_crypt_ftr_and_key(&crypt_ftr);
1915 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1916 if (rc) {
1917 SLOGE("Could not change password on reboot encryption");
1918 return rc;
1919 }
1920 }
1921
1922 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001923 cryptfs_clear_password();
1924 password = strdup(passwd);
1925 struct timespec now;
1926 clock_gettime(CLOCK_BOOTTIME, &now);
1927 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001928 }
1929
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001930 return rc;
1931}
1932
Paul Crowley14c8c072018-09-18 13:30:21 -07001933int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001934 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001935 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001936 char encrypted_state[PROPERTY_VALUE_MAX];
1937 int rc;
1938
1939 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001940 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001941 SLOGE("device not encrypted, aborting");
1942 return -2;
1943 }
1944
1945 if (!master_key_saved) {
1946 SLOGE("encrypted fs not yet mounted, aborting");
1947 return -1;
1948 }
1949
1950 if (!saved_mount_point) {
1951 SLOGE("encrypted fs failed to save mount point, aborting");
1952 return -1;
1953 }
1954
Ken Sumrall160b4d62013-04-22 12:15:39 -07001955 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001956 SLOGE("Error getting crypt footer and key\n");
1957 return -1;
1958 }
1959
1960 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1961 /* If the device has no password, then just say the password is valid */
1962 rc = 0;
1963 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001964 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001965 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1966 /* They match, the password is correct */
1967 rc = 0;
1968 } else {
1969 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1970 sleep(1);
1971 rc = 1;
1972 }
1973 }
1974
1975 return rc;
1976}
1977
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001978/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08001979 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001980 * Presumably, at a minimum, the caller will update the
1981 * filesystem size and crypto_type_name after calling this function.
1982 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001983static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001984 off64_t off;
1985
1986 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001987 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001988 ftr->major_version = CURRENT_MAJOR_VERSION;
1989 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001990 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08001991 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07001992
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001993 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001994 case 1:
1995 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1996 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001997
Paul Crowley14c8c072018-09-18 13:30:21 -07001998 case 0:
1999 ftr->kdf_type = KDF_SCRYPT;
2000 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002001
Paul Crowley14c8c072018-09-18 13:30:21 -07002002 default:
2003 SLOGE("keymaster_check_compatibility failed");
2004 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002005 }
2006
Kenny Rootc4c70f12013-06-14 12:11:38 -07002007 get_device_scrypt_params(ftr);
2008
Ken Sumrall160b4d62013-04-22 12:15:39 -07002009 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2010 if (get_crypt_ftr_info(NULL, &off) == 0) {
2011 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002012 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002013 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002014
2015 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002016}
2017
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002018#define FRAMEWORK_BOOT_WAIT 60
2019
Paul Crowley14c8c072018-09-18 13:30:21 -07002020static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2021 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002022 if (fd == -1) {
2023 SLOGE("Error opening file %s", filename);
2024 return -1;
2025 }
2026
2027 char block[CRYPT_INPLACE_BUFSIZE];
2028 memset(block, 0, sizeof(block));
2029 if (unix_read(fd, block, sizeof(block)) < 0) {
2030 SLOGE("Error reading file %s", filename);
2031 close(fd);
2032 return -1;
2033 }
2034
2035 close(fd);
2036
2037 SHA256_CTX c;
2038 SHA256_Init(&c);
2039 SHA256_Update(&c, block, sizeof(block));
2040 SHA256_Final(buf, &c);
2041
2042 return 0;
2043}
2044
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002045static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2046 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002047 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002048 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002049
Paul Lawrence87999172014-02-20 12:21:31 -08002050 /* The size of the userdata partition, and add in the vold volumes below */
2051 tot_encryption_size = crypt_ftr->fs_size;
2052
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002053 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002054 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002055
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002056 if (rc == ENABLE_INPLACE_ERR_DEV) {
2057 /* Hack for b/17898962 */
2058 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2059 cryptfs_reboot(RebootType::reboot);
2060 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002061
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002062 if (!rc) {
2063 crypt_ftr->encrypted_upto = cur_encryption_done;
2064 }
Paul Lawrence87999172014-02-20 12:21:31 -08002065
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002066 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2067 /* The inplace routine never actually sets the progress to 100% due
2068 * to the round down nature of integer division, so set it here */
2069 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002070 }
2071
2072 return rc;
2073}
2074
Paul Crowleyb64933a2017-10-31 08:25:55 -07002075static int vold_unmountAll(void) {
2076 VolumeManager* vm = VolumeManager::Instance();
2077 return vm->unmountAll();
2078}
2079
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002080int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002081 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002082 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002083 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002084 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002085 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002086 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002087 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002088 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002089 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002090 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002091 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002092 bool onlyCreateHeader = false;
2093 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002094
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002095 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002096 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2097 /* An encryption was underway and was interrupted */
2098 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2099 crypt_ftr.encrypted_upto = 0;
2100 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002101
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002102 /* At this point, we are in an inconsistent state. Until we successfully
2103 complete encryption, a reboot will leave us broken. So mark the
2104 encryption failed in case that happens.
2105 On successfully completing encryption, remove this flag */
2106 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002107
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002108 put_crypt_ftr_and_key(&crypt_ftr);
2109 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2110 if (!check_ftr_sha(&crypt_ftr)) {
2111 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2112 put_crypt_ftr_and_key(&crypt_ftr);
2113 goto error_unencrypted;
2114 }
2115
2116 /* Doing a reboot-encryption*/
2117 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2118 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2119 rebootEncryption = true;
2120 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002121 } else {
2122 // We don't want to accidentally reference invalid data.
2123 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002124 }
2125
2126 property_get("ro.crypto.state", encrypted_state, "");
2127 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2128 SLOGE("Device is already running encrypted, aborting");
2129 goto error_unencrypted;
2130 }
2131
2132 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002133 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2134 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002135
Ken Sumrall3ed82362011-01-28 23:31:16 -08002136 /* Get the size of the real block device */
Paul Crowley14c8c072018-09-18 13:30:21 -07002137 fd = open(real_blkdev, O_RDONLY | O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002138 if (fd == -1) {
2139 SLOGE("Cannot open block device %s\n", real_blkdev);
2140 goto error_unencrypted;
2141 }
2142 unsigned long nr_sec;
2143 get_blkdev_size(fd, &nr_sec);
2144 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002145 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2146 goto error_unencrypted;
2147 }
2148 close(fd);
2149
2150 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002151 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002152 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002153 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002154 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002155
Paul Lawrence87999172014-02-20 12:21:31 -08002156 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002157
2158 if (fs_size_sec > max_fs_size_sec) {
2159 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2160 goto error_unencrypted;
2161 }
2162 }
2163
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002164 /* Get a wakelock as this may take a while, and we don't want the
2165 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2166 * wants to keep the screen on, it can grab a full wakelock.
2167 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002168 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002169 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2170
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002171 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002172 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002173 */
2174 property_set("vold.decrypt", "trigger_shutdown_framework");
2175 SLOGD("Just asked init to shut down class main\n");
2176
Jeff Sharkey9c484982015-03-31 10:35:33 -07002177 /* Ask vold to unmount all devices that it manages */
2178 if (vold_unmountAll()) {
2179 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002180 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002181
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002182 /* no_ui means we are being called from init, not settings.
2183 Now we always reboot from settings, so !no_ui means reboot
2184 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002185 if (!no_ui) {
2186 /* Try fallback, which is to reboot and try there */
2187 onlyCreateHeader = true;
2188 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2189 if (breadcrumb == 0) {
2190 SLOGE("Failed to create breadcrumb file");
2191 goto error_shutting_down;
2192 }
2193 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002194 }
2195
2196 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002197 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002198 /* Now that /data is unmounted, we need to mount a tmpfs
2199 * /data, set a property saying we're doing inplace encryption,
2200 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002201 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002202 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002203 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002204 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002205 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002206 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002207
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002208 /* restart the framework. */
2209 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002210 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002211
Ken Sumrall92736ef2012-10-17 20:57:14 -07002212 /* Ugh, shutting down the framework is not synchronous, so until it
2213 * can be fixed, this horrible hack will wait a moment for it all to
2214 * shut down before proceeding. Without it, some devices cannot
2215 * restart the graphics services.
2216 */
2217 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002218 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002219
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002220 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002221 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002222 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002223 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2224 goto error_shutting_down;
2225 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002226
Paul Lawrence87999172014-02-20 12:21:31 -08002227 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002228 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002229 } else {
2230 crypt_ftr.fs_size = nr_sec;
2231 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002232 /* At this point, we are in an inconsistent state. Until we successfully
2233 complete encryption, a reboot will leave us broken. So mark the
2234 encryption failed in case that happens.
2235 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002236 if (onlyCreateHeader) {
2237 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2238 } else {
2239 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2240 }
Paul Lawrence87999172014-02-20 12:21:31 -08002241 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002242 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2243 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002244
Paul Lawrence87999172014-02-20 12:21:31 -08002245 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002246 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2247 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002248 SLOGE("Cannot create encrypted master key\n");
2249 goto error_shutting_down;
2250 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002251
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002252 /* Replace scrypted intermediate key if we are preparing for a reboot */
2253 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002254 unsigned char fake_master_key[MAX_KEY_LEN];
2255 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002256 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002257 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2258 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002259 }
2260
Paul Lawrence87999172014-02-20 12:21:31 -08002261 /* Write the key to the end of the partition */
2262 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002263
Paul Lawrence87999172014-02-20 12:21:31 -08002264 /* If any persistent data has been remembered, save it.
2265 * If none, create a valid empty table and save that.
2266 */
2267 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002268 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2269 if (pdata) {
2270 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2271 persist_data = pdata;
2272 }
Paul Lawrence87999172014-02-20 12:21:31 -08002273 }
2274 if (persist_data) {
2275 save_persistent_data();
2276 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002277 }
2278
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002279 if (onlyCreateHeader) {
2280 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002281 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002282 }
2283
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002284 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002285 /* startup service classes main and late_start */
2286 property_set("vold.decrypt", "trigger_restart_min_framework");
2287 SLOGD("Just triggered restart_min_framework\n");
2288
2289 /* OK, the framework is restarted and will soon be showing a
2290 * progress bar. Time to setup an encrypted mapping, and
2291 * either write a new filesystem, or encrypt in place updating
2292 * the progress bar as we work.
2293 */
2294 }
2295
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002296 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002297 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002298 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002299
Paul Lawrence87999172014-02-20 12:21:31 -08002300 /* If we are continuing, check checksums match */
2301 rc = 0;
2302 if (previously_encrypted_upto) {
2303 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2304 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002305
Paul Crowley14c8c072018-09-18 13:30:21 -07002306 if (!rc &&
2307 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002308 SLOGE("Checksums do not match - trigger wipe");
2309 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002310 }
2311 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002312
Paul Lawrence87999172014-02-20 12:21:31 -08002313 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002314 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002315 previously_encrypted_upto);
2316 }
2317
2318 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002319 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002320 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002321 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002322 SLOGE("Error calculating checksum for continuing encryption");
2323 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002324 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002325 }
2326
2327 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002328 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002329
Paul Crowley14c8c072018-09-18 13:30:21 -07002330 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002331 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002332 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002333
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002334 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002335 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2336 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002337 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002338 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002339
Paul Lawrence6bfed202014-07-28 12:47:22 -07002340 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002341
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002342 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2343 char value[PROPERTY_VALUE_MAX];
2344 property_get("ro.crypto.state", value, "");
2345 if (!strcmp(value, "")) {
2346 /* default encryption - continue first boot sequence */
2347 property_set("ro.crypto.state", "encrypted");
2348 property_set("ro.crypto.type", "block");
2349 release_wake_lock(lockid);
2350 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2351 // Bring up cryptkeeper that will check the password and set it
2352 property_set("vold.decrypt", "trigger_shutdown_framework");
2353 sleep(2);
2354 property_set("vold.encrypt_progress", "");
2355 cryptfs_trigger_restart_min_framework();
2356 } else {
2357 cryptfs_check_passwd(DEFAULT_PASSWORD);
2358 cryptfs_restart_internal(1);
2359 }
2360 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002361 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002362 sleep(2); /* Give the UI a chance to show 100% progress */
2363 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002364 }
Paul Lawrence87999172014-02-20 12:21:31 -08002365 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002366 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002367 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002368 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002369 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002370 char value[PROPERTY_VALUE_MAX];
2371
Ken Sumrall319369a2012-06-27 16:30:18 -07002372 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002373 if (!strcmp(value, "1")) {
2374 /* wipe data if encryption failed */
2375 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002376 std::string err;
2377 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002378 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002379 if (!write_bootloader_message(options, &err)) {
2380 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002381 }
Josh Gaofec44372017-08-28 13:22:55 -07002382 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002383 } else {
2384 /* set property to trigger dialog */
2385 property_set("vold.encrypt_progress", "error_partially_encrypted");
2386 release_wake_lock(lockid);
2387 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002388 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002389 }
2390
Ken Sumrall3ed82362011-01-28 23:31:16 -08002391 /* hrm, the encrypt step claims success, but the reboot failed.
2392 * This should not happen.
2393 * Set the property and return. Hope the framework can deal with it.
2394 */
2395 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002396 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002397 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002398
2399error_unencrypted:
2400 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002401 if (lockid[0]) {
2402 release_wake_lock(lockid);
2403 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002404 return -1;
2405
2406error_shutting_down:
2407 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2408 * but the framework is stopped and not restarted to show the error, so it's up to
2409 * vold to restart the system.
2410 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002411 SLOGE(
2412 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2413 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002414 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002415
2416 /* shouldn't get here */
2417 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002418 if (lockid[0]) {
2419 release_wake_lock(lockid);
2420 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002421 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002422}
2423
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002424int cryptfs_enable(int type, const char* passwd, int no_ui) {
2425 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002426}
2427
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002428int cryptfs_enable_default(int no_ui) {
2429 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002430}
2431
Paul Crowley14c8c072018-09-18 13:30:21 -07002432int cryptfs_changepw(int crypt_type, const char* newpw) {
Paul Crowley38132a12016-02-09 09:50:32 +00002433 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002434 SLOGE("cryptfs_changepw not valid for file encryption");
2435 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002436 }
2437
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002438 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002439 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002440
2441 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002442 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002443 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002444 return -1;
2445 }
2446
Paul Lawrencef4faa572014-01-29 13:31:03 -08002447 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2448 SLOGE("Invalid crypt_type %d", crypt_type);
2449 return -1;
2450 }
2451
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002452 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002453 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002454 SLOGE("Error getting crypt footer and key");
2455 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002456 }
2457
Paul Lawrencef4faa572014-01-29 13:31:03 -08002458 crypt_ftr.crypt_type = crypt_type;
2459
Paul Crowley14c8c072018-09-18 13:30:21 -07002460 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2461 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002462 if (rc) {
2463 SLOGE("Encrypt master key failed: %d", rc);
2464 return -1;
2465 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002466 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002467 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002468
2469 return 0;
2470}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002471
Rubin Xu85c01f92014-10-13 12:49:54 +01002472static unsigned int persist_get_max_entries(int encrypted) {
2473 struct crypt_mnt_ftr crypt_ftr;
2474 unsigned int dsize;
2475 unsigned int max_persistent_entries;
2476
2477 /* If encrypted, use the values from the crypt_ftr, otherwise
2478 * use the values for the current spec.
2479 */
2480 if (encrypted) {
2481 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2482 return -1;
2483 }
2484 dsize = crypt_ftr.persist_data_size;
2485 } else {
2486 dsize = CRYPT_PERSIST_DATA_SIZE;
2487 }
2488
Paul Crowley14c8c072018-09-18 13:30:21 -07002489 max_persistent_entries =
2490 (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
Rubin Xu85c01f92014-10-13 12:49:54 +01002491
2492 return max_persistent_entries;
2493}
2494
Paul Crowley14c8c072018-09-18 13:30:21 -07002495static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002496 unsigned int i;
2497
2498 if (persist_data == NULL) {
2499 return -1;
2500 }
2501 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2502 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2503 /* We found it! */
2504 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2505 return 0;
2506 }
2507 }
2508
2509 return -1;
2510}
2511
Paul Crowley14c8c072018-09-18 13:30:21 -07002512static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002513 unsigned int i;
2514 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002515 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002516
2517 if (persist_data == NULL) {
2518 return -1;
2519 }
2520
Rubin Xu85c01f92014-10-13 12:49:54 +01002521 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002522
2523 num = persist_data->persist_valid_entries;
2524
2525 for (i = 0; i < num; i++) {
2526 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2527 /* We found an existing entry, update it! */
2528 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2529 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2530 return 0;
2531 }
2532 }
2533
2534 /* We didn't find it, add it to the end, if there is room */
2535 if (persist_data->persist_valid_entries < max_persistent_entries) {
2536 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2537 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2538 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2539 persist_data->persist_valid_entries++;
2540 return 0;
2541 }
2542
2543 return -1;
2544}
2545
Rubin Xu85c01f92014-10-13 12:49:54 +01002546/**
2547 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2548 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2549 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002550int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002551 std::string key_ = key;
2552 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002553
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002554 std::string parsed_field;
2555 unsigned parsed_index;
2556
2557 std::string::size_type split = key_.find_last_of('_');
2558 if (split == std::string::npos) {
2559 parsed_field = key_;
2560 parsed_index = 0;
2561 } else {
2562 parsed_field = key_.substr(0, split);
2563 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002564 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002565
2566 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002567}
2568
2569/*
2570 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2571 * remaining entries starting from index will be deleted.
2572 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2573 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2574 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2575 *
2576 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002577static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002578 unsigned int i;
2579 unsigned int j;
2580 unsigned int num;
2581
2582 if (persist_data == NULL) {
2583 return PERSIST_DEL_KEY_ERROR_OTHER;
2584 }
2585
2586 num = persist_data->persist_valid_entries;
2587
Paul Crowley14c8c072018-09-18 13:30:21 -07002588 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002589 // Filter out to-be-deleted entries in place.
2590 for (i = 0; i < num; i++) {
2591 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2592 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2593 j++;
2594 }
2595 }
2596
2597 if (j < num) {
2598 persist_data->persist_valid_entries = j;
2599 // Zeroise the remaining entries
2600 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2601 return PERSIST_DEL_KEY_OK;
2602 } else {
2603 // Did not find an entry matching the given fieldname
2604 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2605 }
2606}
2607
Paul Crowley14c8c072018-09-18 13:30:21 -07002608static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002609 unsigned int i;
2610 unsigned int count;
2611
2612 if (persist_data == NULL) {
2613 return -1;
2614 }
2615
2616 count = 0;
2617 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2618 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2619 count++;
2620 }
2621 }
2622
2623 return count;
2624}
2625
Ken Sumrall160b4d62013-04-22 12:15:39 -07002626/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002627int cryptfs_getfield(const char* fieldname, char* value, int len) {
Paul Crowley38132a12016-02-09 09:50:32 +00002628 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002629 SLOGE("Cannot get field when file encrypted");
2630 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002631 }
2632
Ken Sumrall160b4d62013-04-22 12:15:39 -07002633 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002634 /* CRYPTO_GETFIELD_OK is success,
2635 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2636 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2637 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002638 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002639 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2640 int i;
2641 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002642
2643 if (persist_data == NULL) {
2644 load_persistent_data();
2645 if (persist_data == NULL) {
2646 SLOGE("Getfield error, cannot load persistent data");
2647 goto out;
2648 }
2649 }
2650
Rubin Xu85c01f92014-10-13 12:49:54 +01002651 // Read value from persistent entries. If the original value is split into multiple entries,
2652 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002653 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002654 // 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 -07002655 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002656 // value too small
2657 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2658 goto out;
2659 }
2660 rc = CRYPTO_GETFIELD_OK;
2661
2662 for (i = 1; /* break explicitly */; i++) {
2663 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002664 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002665 // If the fieldname is very long, we stop as soon as it begins to overflow the
2666 // maximum field length. At this point we have in fact fully read out the original
2667 // value because cryptfs_setfield would not allow fields with longer names to be
2668 // written in the first place.
2669 break;
2670 }
2671 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002672 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2673 // value too small.
2674 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2675 goto out;
2676 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002677 } else {
2678 // Exhaust all entries.
2679 break;
2680 }
2681 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002682 } else {
2683 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002684 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002685 }
2686
2687out:
2688 return rc;
2689}
2690
2691/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002692int cryptfs_setfield(const char* fieldname, const char* value) {
Paul Crowley38132a12016-02-09 09:50:32 +00002693 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002694 SLOGE("Cannot set field when file encrypted");
2695 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002696 }
2697
Ken Sumrall160b4d62013-04-22 12:15:39 -07002698 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002699 /* 0 is success, negative values are error */
2700 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002701 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002702 unsigned int field_id;
2703 char temp_field[PROPERTY_KEY_MAX];
2704 unsigned int num_entries;
2705 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002706
2707 if (persist_data == NULL) {
2708 load_persistent_data();
2709 if (persist_data == NULL) {
2710 SLOGE("Setfield error, cannot load persistent data");
2711 goto out;
2712 }
2713 }
2714
2715 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002716 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002717 encrypted = 1;
2718 }
2719
Rubin Xu85c01f92014-10-13 12:49:54 +01002720 // Compute the number of entries required to store value, each entry can store up to
2721 // (PROPERTY_VALUE_MAX - 1) chars
2722 if (strlen(value) == 0) {
2723 // Empty value also needs one entry to store.
2724 num_entries = 1;
2725 } else {
2726 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2727 }
2728
2729 max_keylen = strlen(fieldname);
2730 if (num_entries > 1) {
2731 // Need an extra "_%d" suffix.
2732 max_keylen += 1 + log10(num_entries);
2733 }
2734 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2735 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002736 goto out;
2737 }
2738
Rubin Xu85c01f92014-10-13 12:49:54 +01002739 // Make sure we have enough space to write the new value
2740 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2741 persist_get_max_entries(encrypted)) {
2742 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2743 goto out;
2744 }
2745
2746 // Now that we know persist_data has enough space for value, let's delete the old field first
2747 // to make up space.
2748 persist_del_keys(fieldname, 0);
2749
2750 if (persist_set_key(fieldname, value, encrypted)) {
2751 // fail to set key, should not happen as we have already checked the available space
2752 SLOGE("persist_set_key() error during setfield()");
2753 goto out;
2754 }
2755
2756 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002757 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002758
2759 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2760 // fail to set key, should not happen as we have already checked the available space.
2761 SLOGE("persist_set_key() error during setfield()");
2762 goto out;
2763 }
2764 }
2765
Ken Sumrall160b4d62013-04-22 12:15:39 -07002766 /* If we are running encrypted, save the persistent data now */
2767 if (encrypted) {
2768 if (save_persistent_data()) {
2769 SLOGE("Setfield error, cannot save persistent data");
2770 goto out;
2771 }
2772 }
2773
Rubin Xu85c01f92014-10-13 12:49:54 +01002774 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002775
2776out:
2777 return rc;
2778}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002779
2780/* Checks userdata. Attempt to mount the volume if default-
2781 * encrypted.
2782 * On success trigger next init phase and return 0.
2783 * Currently do not handle failure - see TODO below.
2784 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002785int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002786 int crypt_type = cryptfs_get_password_type();
2787 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2788 SLOGE("Bad crypt type - error");
2789 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002790 SLOGD(
2791 "Password is not default - "
2792 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002793 property_set("vold.decrypt", "trigger_restart_min_framework");
2794 return 0;
2795 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2796 SLOGD("Password is default - restarting filesystem");
2797 cryptfs_restart_internal(0);
2798 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002799 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002800 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002801 }
2802
Paul Lawrence6bfed202014-07-28 12:47:22 -07002803 /** Corrupt. Allow us to boot into framework, which will detect bad
2804 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002805 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002806 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002807 return 0;
2808}
2809
2810/* Returns type of the password, default, pattern, pin or password.
2811 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002812int cryptfs_get_password_type(void) {
Paul Crowley38132a12016-02-09 09:50:32 +00002813 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002814 SLOGE("cryptfs_get_password_type not valid for file encryption");
2815 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002816 }
2817
Paul Lawrencef4faa572014-01-29 13:31:03 -08002818 struct crypt_mnt_ftr crypt_ftr;
2819
2820 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2821 SLOGE("Error getting crypt footer and key\n");
2822 return -1;
2823 }
2824
Paul Lawrence6bfed202014-07-28 12:47:22 -07002825 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2826 return -1;
2827 }
2828
Paul Lawrencef4faa572014-01-29 13:31:03 -08002829 return crypt_ftr.crypt_type;
2830}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002831
Paul Crowley14c8c072018-09-18 13:30:21 -07002832const char* cryptfs_get_password() {
Paul Crowley38132a12016-02-09 09:50:32 +00002833 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002834 SLOGE("cryptfs_get_password not valid for file encryption");
2835 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002836 }
2837
Paul Lawrence399317e2014-03-10 13:20:50 -07002838 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002839 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002840 if (now.tv_sec < password_expiry_time) {
2841 return password;
2842 } else {
2843 cryptfs_clear_password();
2844 return 0;
2845 }
2846}
2847
Paul Crowley14c8c072018-09-18 13:30:21 -07002848void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002849 if (password) {
2850 size_t len = strlen(password);
2851 memset(password, 0, len);
2852 free(password);
2853 password = 0;
2854 password_expiry_time = 0;
2855 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002856}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002857
Paul Crowley14c8c072018-09-18 13:30:21 -07002858int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002859 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07002860 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07002861}