blob: 2ac20e12de92628fd988a1f787443239ce9ed3fa [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
Logan Chiend557d762018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
Daniel Rosenberg65f99c92018-08-28 01:58:49 -070027#include "Checkpoint.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070029#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080030#include "Keymaster.h"
31#include "Process.h"
32#include "ScryptParameters.h"
Paul Crowleycfe39722018-10-30 15:59:24 -070033#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080034#include "VoldUtil.h"
35#include "VolumeManager.h"
36#include "secontext.h"
37
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <android-base/properties.h>
Logan Chiend557d762018-05-02 11:36:45 +080039#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080040#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070042#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080043#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070045#include <fscrypt/fscrypt.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080046#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080047#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080048#include <logwrap/logwrap.h>
49#include <openssl/evp.h>
50#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080051#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080052
53#include <ctype.h>
54#include <errno.h>
55#include <fcntl.h>
56#include <inttypes.h>
57#include <libgen.h>
58#include <linux/dm-ioctl.h>
59#include <linux/kdev_t.h>
60#include <math.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <string.h>
64#include <sys/ioctl.h>
65#include <sys/mount.h>
66#include <sys/param.h>
67#include <sys/stat.h>
68#include <sys/types.h>
69#include <sys/wait.h>
70#include <time.h>
71#include <unistd.h>
72
Wei Wang4375f1b2017-02-24 17:43:01 -080073extern "C" {
74#include <crypto_scrypt.h>
75}
Mark Salyzyn3e971272014-01-21 13:27:04 -080076
Paul Crowleycfe39722018-10-30 15:59:24 -070077using namespace std::chrono_literals;
78
Mark Salyzyn5eecc442014-02-12 14:16:14 -080079#define UNUSED __attribute__((unused))
80
Ken Sumrall8f869aa2010-12-03 03:47:09 -080081#define DM_CRYPT_BUF_SIZE 4096
82
Jason parks70a4b3f2011-01-28 10:10:47 -060083#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080084
85constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
86constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070087constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080088
89// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070090static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060091
Paul Crowley14c8c072018-09-18 13:30:21 -070092#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070093
Paul Lawrence3bd36d52015-06-09 13:37:44 -070094#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080095
Paul Lawrence3d99eba2015-11-20 07:07:19 -080096#define CRYPTO_BLOCK_DEVICE "userdata"
97
98#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
99
Ken Sumrall29d8da82011-05-18 17:20:07 -0700100#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700101#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700102
Ken Sumralle919efe2012-09-29 17:07:41 -0700103#define TABLE_LOAD_RETRIES 10
104
Shawn Willden47ba10d2014-09-03 17:07:06 -0600105#define RSA_KEY_SIZE 2048
106#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
107#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600108#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700109
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700110#define RETRY_MOUNT_ATTEMPTS 10
111#define RETRY_MOUNT_DELAY_SECONDS 1
112
Paul Crowley5afbc622017-11-27 09:42:17 -0800113#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
114
Paul Crowley73473332017-11-21 15:43:51 -0800115static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
116
Greg Kaiser59ad0182018-02-16 13:01:36 -0800117static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700118static char* saved_mount_point;
119static int master_key_saved = 0;
120static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800121
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700122/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700123static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000124 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700125}
126
127/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700128static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800129 if (ftr->keymaster_blob_size) {
130 SLOGI("Already have key");
131 return 0;
132 }
133
Paul Crowley14c8c072018-09-18 13:30:21 -0700134 int rc = keymaster_create_key_for_cryptfs_scrypt(
135 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
136 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000137 if (rc) {
138 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800139 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000140 ftr->keymaster_blob_size = 0;
141 }
142 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700143 return -1;
144 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000145 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700146}
147
Shawn Willdene17a9c42014-09-08 13:04:08 -0600148/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700149static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
150 const size_t object_size, unsigned char** signature,
151 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600152 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600153 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600154 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600155
Shawn Willdene17a9c42014-09-08 13:04:08 -0600156 // To sign a message with RSA, the message must satisfy two
157 // constraints:
158 //
159 // 1. The message, when interpreted as a big-endian numeric value, must
160 // be strictly less than the public modulus of the RSA key. Note
161 // that because the most significant bit of the public modulus is
162 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
163 // key), an n-bit message with most significant bit 0 always
164 // satisfies this requirement.
165 //
166 // 2. The message must have the same length in bits as the public
167 // modulus of the RSA key. This requirement isn't mathematically
168 // necessary, but is necessary to ensure consistency in
169 // implementations.
170 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600171 case KDF_SCRYPT_KEYMASTER:
172 // This ensures the most significant byte of the signed message
173 // is zero. We could have zero-padded to the left instead, but
174 // this approach is slightly more robust against changes in
175 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600176 // so) because we really should be using a proper deterministic
177 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800178 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600179 SLOGI("Signing safely-padded object");
180 break;
181 default:
182 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000183 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600184 }
Paul Crowley73473332017-11-21 15:43:51 -0800185 for (;;) {
186 auto result = keymaster_sign_object_for_cryptfs_scrypt(
187 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
188 to_sign_size, signature, signature_size);
189 switch (result) {
190 case KeymasterSignResult::ok:
191 return 0;
192 case KeymasterSignResult::upgrade:
193 break;
194 default:
195 return -1;
196 }
197 SLOGD("Upgrading key");
198 if (keymaster_upgrade_key_for_cryptfs_scrypt(
199 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
200 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
201 &ftr->keymaster_blob_size) != 0) {
202 SLOGE("Failed to upgrade key");
203 return -1;
204 }
205 if (put_crypt_ftr_and_key(ftr) != 0) {
206 SLOGE("Failed to write upgraded key to disk");
207 }
208 SLOGD("Key upgraded successfully");
209 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600210}
211
Paul Lawrence399317e2014-03-10 13:20:50 -0700212/* Store password when userdata is successfully decrypted and mounted.
213 * Cleared by cryptfs_clear_password
214 *
215 * To avoid a double prompt at boot, we need to store the CryptKeeper
216 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
217 * Since the entire framework is torn down and rebuilt after encryption,
218 * we have to use a daemon or similar to store the password. Since vold
219 * is secured against IPC except from system processes, it seems a reasonable
220 * place to store this.
221 *
222 * password should be cleared once it has been used.
223 *
224 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800225 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700226static char* password = 0;
227static int password_expiry_time = 0;
228static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800229
Paul Crowley14c8c072018-09-18 13:30:21 -0700230enum class RebootType { reboot, recovery, shutdown };
231static void cryptfs_reboot(RebootType rt) {
232 switch (rt) {
233 case RebootType::reboot:
234 property_set(ANDROID_RB_PROPERTY, "reboot");
235 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800236
Paul Crowley14c8c072018-09-18 13:30:21 -0700237 case RebootType::recovery:
238 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
239 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800240
Paul Crowley14c8c072018-09-18 13:30:21 -0700241 case RebootType::shutdown:
242 property_set(ANDROID_RB_PROPERTY, "shutdown");
243 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700244 }
Paul Lawrence87999172014-02-20 12:21:31 -0800245
Ken Sumralladfba362013-06-04 16:37:52 -0700246 sleep(20);
247
248 /* Shouldn't get here, reboot should happen before sleep times out */
249 return;
250}
251
Paul Crowley14c8c072018-09-18 13:30:21 -0700252static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800253 memset(io, 0, dataSize);
254 io->data_size = dataSize;
255 io->data_start = sizeof(struct dm_ioctl);
256 io->version[0] = 4;
257 io->version[1] = 0;
258 io->version[2] = 0;
259 io->flags = flags;
260 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100261 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800262 }
263}
264
Greg Kaiser38723f22018-02-16 13:35:35 -0800265namespace {
266
267struct CryptoType;
268
269// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700270const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800271
272struct CryptoType {
273 // We should only be constructing CryptoTypes as part of
274 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
275 // which isn't pure or fully protected as a concession to being able to
276 // do it all at compile time. Add new CryptoTypes in
277 // supported_crypto_types[] below.
278 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
279 constexpr CryptoType set_keysize(uint32_t size) const {
280 return CryptoType(this->property_name, this->crypto_name, size);
281 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700282 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800283 return CryptoType(property, this->crypto_name, this->keysize);
284 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700285 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800286 return CryptoType(this->property_name, crypto, this->keysize);
287 }
288
Paul Crowley14c8c072018-09-18 13:30:21 -0700289 constexpr const char* get_property_name() const { return property_name; }
290 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800291 constexpr uint32_t get_keysize() const { return keysize; }
292
Paul Crowley14c8c072018-09-18 13:30:21 -0700293 private:
294 const char* property_name;
295 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800296 uint32_t keysize;
297
Paul Crowley14c8c072018-09-18 13:30:21 -0700298 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800299 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700300 friend const CryptoType& get_crypto_type();
301 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800302};
303
304// We only want to parse this read-only property once. But we need to wait
305// until the system is initialized before we can read it. So we use a static
306// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700307const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800308 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
309 return crypto_type;
310}
311
312constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700313 .set_property_name("AES-128-CBC")
314 .set_crypto_name("aes-cbc-essiv:sha256")
315 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800316
317constexpr CryptoType supported_crypto_types[] = {
318 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800319 CryptoType()
320 .set_property_name("adiantum")
321 .set_crypto_name("xchacha12,aes-adiantum-plain64")
322 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800323 // Add new CryptoTypes here. Order is not important.
324};
325
Greg Kaiser38723f22018-02-16 13:35:35 -0800326// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
327// We confirm all supported_crypto_types have a small enough keysize and
328// had both set_property_name() and set_crypto_name() called.
329
330template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700331constexpr size_t array_length(T (&)[N]) {
332 return N;
333}
Greg Kaiser38723f22018-02-16 13:35:35 -0800334
335constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
336 return (index >= array_length(supported_crypto_types));
337}
338
Paul Crowley14c8c072018-09-18 13:30:21 -0700339constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800340 return ((crypto_type.get_property_name() != nullptr) &&
341 (crypto_type.get_crypto_name() != nullptr) &&
342 (crypto_type.get_keysize() <= MAX_KEY_LEN));
343}
344
345// Note in C++11 that constexpr functions can only have a single line.
346// So our code is a bit convoluted (using recursion instead of a loop),
347// but it's asserting at compile time that all of our key lengths are valid.
348constexpr bool validateSupportedCryptoTypes(size_t index) {
349 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700350 (isValidCryptoType(supported_crypto_types[index]) &&
351 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800352}
353
354static_assert(validateSupportedCryptoTypes(0),
355 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
356 "incompletely constructed.");
357// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
358
Greg Kaiser38723f22018-02-16 13:35:35 -0800359// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700360const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800361 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
362 char paramstr[PROPERTY_VALUE_MAX];
363
Paul Crowley14c8c072018-09-18 13:30:21 -0700364 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
365 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800366 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
367 return ctype;
368 }
369 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700370 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
371 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800372 return default_crypto_type;
373}
374
375} // namespace
376
Kenny Rootc4c70f12013-06-14 12:11:38 -0700377/**
378 * Gets the default device scrypt parameters for key derivation time tuning.
379 * The parameters should lead to about one second derivation time for the
380 * given device.
381 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700382static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700383 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000384 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700385
Paul Crowley63c18d32016-02-10 14:02:47 +0000386 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
387 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
388 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
389 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700390 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000391 ftr->N_factor = Nf;
392 ftr->r_factor = rf;
393 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700394}
395
Greg Kaiser57f9af62018-02-16 13:13:58 -0800396uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800397 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800398}
399
Paul Crowley14c8c072018-09-18 13:30:21 -0700400const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800401 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800402}
403
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200404static uint64_t get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800405 int fd, block_size;
406 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200407 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800408
Paul Crowley14c8c072018-09-18 13:30:21 -0700409 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800410 SLOGE("Cannot open device to get filesystem size ");
411 return 0;
412 }
413
414 if (lseek64(fd, 1024, SEEK_SET) < 0) {
415 SLOGE("Cannot seek to superblock");
416 return 0;
417 }
418
419 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
420 SLOGE("Cannot read superblock");
421 return 0;
422 }
423
424 close(fd);
425
Daniel Rosenberge82df162014-08-15 22:19:23 +0000426 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
427 SLOGE("Not a valid ext4 superblock");
428 return 0;
429 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800430 block_size = 1024 << sb.s_log_block_size;
431 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200432 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800433
434 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200435 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800436}
437
Paul Crowley14c8c072018-09-18 13:30:21 -0700438static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
439 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200440 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700441 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700442 char key_loc[PROPERTY_VALUE_MAX];
443 char real_blkdev[PROPERTY_VALUE_MAX];
444 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700445
Paul Crowley14c8c072018-09-18 13:30:21 -0700446 if (!cached_data) {
447 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700448
Paul Crowley14c8c072018-09-18 13:30:21 -0700449 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200450 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700451 /* 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));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200456 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700457 cached_data = 1;
458 } else {
459 SLOGE("Cannot get size of block device %s\n", real_blkdev);
460 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700461 } else {
462 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
463 cached_off = 0;
464 cached_data = 1;
465 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700466 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700467
Paul Crowley14c8c072018-09-18 13:30:21 -0700468 if (cached_data) {
469 if (metadata_fname) {
470 *metadata_fname = cached_metadata_fname;
471 }
472 if (off) {
473 *off = cached_off;
474 }
475 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700476 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700477
Paul Crowley14c8c072018-09-18 13:30:21 -0700478 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700479}
480
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800481/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700482static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800483 SHA256_CTX c;
484 SHA256_Init(&c);
485 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
486 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
487 SHA256_Final(crypt_ftr->sha256, &c);
488}
489
Ken Sumralle8744072011-01-18 22:01:55 -0800490/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800491 * update the failed mount count but not change the key.
492 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700493static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
494 int fd;
495 unsigned int cnt;
496 /* starting_off is set to the SEEK_SET offset
497 * where the crypto structure starts
498 */
499 off64_t starting_off;
500 int rc = -1;
501 char* fname = NULL;
502 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800503
Paul Crowley14c8c072018-09-18 13:30:21 -0700504 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800505
Paul Crowley14c8c072018-09-18 13:30:21 -0700506 if (get_crypt_ftr_info(&fname, &starting_off)) {
507 SLOGE("Unable to get crypt_ftr_info\n");
508 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800509 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700510 if (fname[0] != '/') {
511 SLOGE("Unexpected value for crypto key location\n");
512 return -1;
513 }
514 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
515 SLOGE("Cannot open footer file %s for put\n", fname);
516 return -1;
517 }
Ken Sumralle8744072011-01-18 22:01:55 -0800518
Paul Crowley14c8c072018-09-18 13:30:21 -0700519 /* Seek to the start of the crypt footer */
520 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
521 SLOGE("Cannot seek to real block device footer\n");
522 goto errout;
523 }
524
525 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
526 SLOGE("Cannot write real block device footer\n");
527 goto errout;
528 }
529
530 fstat(fd, &statbuf);
531 /* If the keys are kept on a raw block device, do not try to truncate it. */
532 if (S_ISREG(statbuf.st_mode)) {
533 if (ftruncate(fd, 0x4000)) {
534 SLOGE("Cannot set footer file size\n");
535 goto errout;
536 }
537 }
538
539 /* Success! */
540 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800541
542errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700543 close(fd);
544 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800545}
546
Paul Crowley14c8c072018-09-18 13:30:21 -0700547static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800548 struct crypt_mnt_ftr copy;
549 memcpy(&copy, crypt_ftr, sizeof(copy));
550 set_ftr_sha(&copy);
551 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
552}
553
Paul Crowley14c8c072018-09-18 13:30:21 -0700554static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700555 return TEMP_FAILURE_RETRY(read(fd, buff, len));
556}
557
Paul Crowley14c8c072018-09-18 13:30:21 -0700558static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700559 return TEMP_FAILURE_RETRY(write(fd, buff, len));
560}
561
Paul Crowley14c8c072018-09-18 13:30:21 -0700562static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700563 memset(pdata, 0, len);
564 pdata->persist_magic = PERSIST_DATA_MAGIC;
565 pdata->persist_valid_entries = 0;
566}
567
568/* A routine to update the passed in crypt_ftr to the lastest version.
569 * fd is open read/write on the device that holds the crypto footer and persistent
570 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
571 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
572 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700573static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700574 int orig_major = crypt_ftr->major_version;
575 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700576
Kenny Root7434b312013-06-14 11:29:53 -0700577 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700578 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700579 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700580
Kenny Rootc4c70f12013-06-14 12:11:38 -0700581 SLOGW("upgrading crypto footer to 1.1");
582
Paul Crowley14c8c072018-09-18 13:30:21 -0700583 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700584 if (pdata == NULL) {
585 SLOGE("Cannot allocate persisent data\n");
586 return;
587 }
588 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
589
590 /* Need to initialize the persistent data area */
591 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
592 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100593 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700594 return;
595 }
596 /* Write all zeros to the first copy, making it invalid */
597 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
598
599 /* Write a valid but empty structure to the second copy */
600 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
601 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
602
603 /* Update the footer */
604 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
605 crypt_ftr->persist_data_offset[0] = pdata_offset;
606 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
607 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100608 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700609 }
610
Paul Lawrencef4faa572014-01-29 13:31:03 -0800611 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700612 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800613 /* But keep the old kdf_type.
614 * It will get updated later to KDF_SCRYPT after the password has been verified.
615 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700616 crypt_ftr->kdf_type = KDF_PBKDF2;
617 get_device_scrypt_params(crypt_ftr);
618 crypt_ftr->minor_version = 2;
619 }
620
Paul Lawrencef4faa572014-01-29 13:31:03 -0800621 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
622 SLOGW("upgrading crypto footer to 1.3");
623 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
624 crypt_ftr->minor_version = 3;
625 }
626
Kenny Root7434b312013-06-14 11:29:53 -0700627 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
628 if (lseek64(fd, offset, SEEK_SET) == -1) {
629 SLOGE("Cannot seek to crypt footer\n");
630 return;
631 }
632 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700633 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700634}
635
Paul Crowley14c8c072018-09-18 13:30:21 -0700636static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
637 int fd;
638 unsigned int cnt;
639 off64_t starting_off;
640 int rc = -1;
641 char* fname = NULL;
642 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700643
Paul Crowley14c8c072018-09-18 13:30:21 -0700644 if (get_crypt_ftr_info(&fname, &starting_off)) {
645 SLOGE("Unable to get crypt_ftr_info\n");
646 return -1;
647 }
648 if (fname[0] != '/') {
649 SLOGE("Unexpected value for crypto key location\n");
650 return -1;
651 }
652 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
653 SLOGE("Cannot open footer file %s for get\n", fname);
654 return -1;
655 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800656
Paul Crowley14c8c072018-09-18 13:30:21 -0700657 /* Make sure it's 16 Kbytes in length */
658 fstat(fd, &statbuf);
659 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
660 SLOGE("footer file %s is not the expected size!\n", fname);
661 goto errout;
662 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700663
Paul Crowley14c8c072018-09-18 13:30:21 -0700664 /* Seek to the start of the crypt footer */
665 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
666 SLOGE("Cannot seek to real block device footer\n");
667 goto errout;
668 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700669
Paul Crowley14c8c072018-09-18 13:30:21 -0700670 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
671 SLOGE("Cannot read real block device footer\n");
672 goto errout;
673 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800674
Paul Crowley14c8c072018-09-18 13:30:21 -0700675 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
676 SLOGE("Bad magic for real block device %s\n", fname);
677 goto errout;
678 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800679
Paul Crowley14c8c072018-09-18 13:30:21 -0700680 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
681 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
682 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
683 goto errout;
684 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800685
Paul Crowley14c8c072018-09-18 13:30:21 -0700686 // We risk buffer overflows with oversized keys, so we just reject them.
687 // 0-sized keys are problematic (essentially by-passing encryption), and
688 // AES-CBC key wrapping only works for multiples of 16 bytes.
689 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
690 (crypt_ftr->keysize > MAX_KEY_LEN)) {
691 SLOGE(
692 "Invalid keysize (%u) for block device %s; Must be non-zero, "
693 "divisible by 16, and <= %d\n",
694 crypt_ftr->keysize, fname, MAX_KEY_LEN);
695 goto errout;
696 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800697
Paul Crowley14c8c072018-09-18 13:30:21 -0700698 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
699 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
700 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
701 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800702
Paul Crowley14c8c072018-09-18 13:30:21 -0700703 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
704 * copy on disk before returning.
705 */
706 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
707 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
708 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800709
Paul Crowley14c8c072018-09-18 13:30:21 -0700710 /* Success! */
711 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800712
713errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700714 close(fd);
715 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800716}
717
Paul Crowley14c8c072018-09-18 13:30:21 -0700718static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700719 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
720 crypt_ftr->persist_data_offset[1]) {
721 SLOGE("Crypt_ftr persist data regions overlap");
722 return -1;
723 }
724
725 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
726 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
727 return -1;
728 }
729
730 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700731 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700732 CRYPT_FOOTER_OFFSET) {
733 SLOGE("Persistent data extends past crypto footer");
734 return -1;
735 }
736
737 return 0;
738}
739
Paul Crowley14c8c072018-09-18 13:30:21 -0700740static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700741 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700742 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700743 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700744 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700745 int found = 0;
746 int fd;
747 int ret;
748 int i;
749
750 if (persist_data) {
751 /* Nothing to do, we've already loaded or initialized it */
752 return 0;
753 }
754
Ken Sumrall160b4d62013-04-22 12:15:39 -0700755 /* If not encrypted, just allocate an empty table and initialize it */
756 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700757 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800758 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700759 if (pdata) {
760 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
761 persist_data = pdata;
762 return 0;
763 }
764 return -1;
765 }
766
Paul Crowley14c8c072018-09-18 13:30:21 -0700767 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700768 return -1;
769 }
770
Paul Crowley14c8c072018-09-18 13:30:21 -0700771 if ((crypt_ftr.major_version < 1) ||
772 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700773 SLOGE("Crypt_ftr version doesn't support persistent data");
774 return -1;
775 }
776
777 if (get_crypt_ftr_info(&fname, NULL)) {
778 return -1;
779 }
780
781 ret = validate_persistent_data_storage(&crypt_ftr);
782 if (ret) {
783 return -1;
784 }
785
Paul Crowley14c8c072018-09-18 13:30:21 -0700786 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700787 if (fd < 0) {
788 SLOGE("Cannot open %s metadata file", fname);
789 return -1;
790 }
791
Wei Wang4375f1b2017-02-24 17:43:01 -0800792 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800793 if (pdata == NULL) {
794 SLOGE("Cannot allocate memory for persistent data");
795 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700796 }
797
798 for (i = 0; i < 2; i++) {
799 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
800 SLOGE("Cannot seek to read persistent data on %s", fname);
801 goto err2;
802 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700803 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700804 SLOGE("Error reading persistent data on iteration %d", i);
805 goto err2;
806 }
807 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
808 found = 1;
809 break;
810 }
811 }
812
813 if (!found) {
814 SLOGI("Could not find valid persistent data, creating");
815 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
816 }
817
818 /* Success */
819 persist_data = pdata;
820 close(fd);
821 return 0;
822
823err2:
824 free(pdata);
825
826err:
827 close(fd);
828 return -1;
829}
830
Paul Crowley14c8c072018-09-18 13:30:21 -0700831static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700832 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700833 struct crypt_persist_data* pdata;
834 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700835 off64_t write_offset;
836 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700837 int fd;
838 int ret;
839
840 if (persist_data == NULL) {
841 SLOGE("No persistent data to save");
842 return -1;
843 }
844
Paul Crowley14c8c072018-09-18 13:30:21 -0700845 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700846 return -1;
847 }
848
Paul Crowley14c8c072018-09-18 13:30:21 -0700849 if ((crypt_ftr.major_version < 1) ||
850 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700851 SLOGE("Crypt_ftr version doesn't support persistent data");
852 return -1;
853 }
854
855 ret = validate_persistent_data_storage(&crypt_ftr);
856 if (ret) {
857 return -1;
858 }
859
860 if (get_crypt_ftr_info(&fname, NULL)) {
861 return -1;
862 }
863
Paul Crowley14c8c072018-09-18 13:30:21 -0700864 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700865 if (fd < 0) {
866 SLOGE("Cannot open %s metadata file", fname);
867 return -1;
868 }
869
Wei Wang4375f1b2017-02-24 17:43:01 -0800870 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700871 if (pdata == NULL) {
872 SLOGE("Cannot allocate persistant data");
873 goto err;
874 }
875
876 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
877 SLOGE("Cannot seek to read persistent data on %s", fname);
878 goto err2;
879 }
880
881 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700882 SLOGE("Error reading persistent data before save");
883 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700884 }
885
886 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
887 /* The first copy is the curent valid copy, so write to
888 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700889 write_offset = crypt_ftr.persist_data_offset[1];
890 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700891 } else {
892 /* The second copy must be the valid copy, so write to
893 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700894 write_offset = crypt_ftr.persist_data_offset[0];
895 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700896 }
897
898 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100899 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700900 SLOGE("Cannot seek to write persistent data");
901 goto err2;
902 }
903 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700904 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100905 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700906 SLOGE("Cannot seek to erase previous persistent data");
907 goto err2;
908 }
909 fsync(fd);
910 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -0700911 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700912 SLOGE("Cannot write to erase previous persistent data");
913 goto err2;
914 }
915 fsync(fd);
916 } else {
917 SLOGE("Cannot write to save persistent data");
918 goto err2;
919 }
920
921 /* Success */
922 free(pdata);
923 close(fd);
924 return 0;
925
926err2:
927 free(pdata);
928err:
929 close(fd);
930 return -1;
931}
932
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800933/* Convert a binary key of specified length into an ascii hex string equivalent,
934 * without the leading 0x and with null termination
935 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700936static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
937 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700938 unsigned int i, a;
939 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800940
Paul Crowley14c8c072018-09-18 13:30:21 -0700941 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700942 /* For each byte, write out two ascii hex digits */
943 nibble = (master_key[i] >> 4) & 0xf;
944 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800945
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700946 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -0700947 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700948 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800949
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700950 /* Add the null termination */
951 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800952}
953
Paul Crowley14c8c072018-09-18 13:30:21 -0700954static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
955 const unsigned char* master_key, const char* real_blk_name,
956 const char* name, int fd, const char* extra_params) {
957 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
958 struct dm_ioctl* io;
959 struct dm_target_spec* tgt;
960 char* crypt_params;
961 // We need two ASCII characters to represent each byte, and need space for
962 // the '\0' terminator.
963 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
964 size_t buff_offset;
965 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800966
Paul Crowley14c8c072018-09-18 13:30:21 -0700967 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800968
Paul Crowley14c8c072018-09-18 13:30:21 -0700969 /* Load the mapping table for this device */
970 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800971
Paul Crowley14c8c072018-09-18 13:30:21 -0700972 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
973 io->target_count = 1;
974 tgt->status = 0;
975 tgt->sector_start = 0;
976 tgt->length = crypt_ftr->fs_size;
977 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800978
Paul Crowley14c8c072018-09-18 13:30:21 -0700979 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
980 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800981
Paul Crowley14c8c072018-09-18 13:30:21 -0700982 buff_offset = crypt_params - buffer;
983 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
984 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
985 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
986 crypt_params += strlen(crypt_params) + 1;
987 crypt_params =
988 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
989 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800990
Paul Crowley14c8c072018-09-18 13:30:21 -0700991 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
992 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
993 break;
994 }
995 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800996 }
Ken Sumralldb5e0262013-02-05 17:39:48 -0800997
Paul Crowley14c8c072018-09-18 13:30:21 -0700998 if (i == TABLE_LOAD_RETRIES) {
999 /* We failed to load the table, return an error */
1000 return -1;
1001 } else {
1002 return i + 1;
1003 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001004}
1005
Paul Crowley14c8c072018-09-18 13:30:21 -07001006static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001007 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001008 struct dm_ioctl* io;
1009 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001010
Paul Crowley14c8c072018-09-18 13:30:21 -07001011 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001012
1013 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1014
1015 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1016 return -1;
1017 }
1018
1019 /* Iterate over the returned versions, looking for name of "crypt".
1020 * When found, get and return the version.
1021 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001022 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001023 while (v->next) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001024 if (!strcmp(v->name, "crypt")) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001025 /* We found the crypt driver, return the version, and get out */
1026 version[0] = v->version[0];
1027 version[1] = v->version[1];
1028 version[2] = v->version[2];
1029 return 0;
1030 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001031 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001032 }
1033
1034 return -1;
1035}
1036
Paul Crowley5afbc622017-11-27 09:42:17 -08001037static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1038 if (extra_params_vec.empty()) return "";
1039 std::string extra_params = std::to_string(extra_params_vec.size());
1040 for (const auto& p : extra_params_vec) {
1041 extra_params.append(" ");
1042 extra_params.append(p);
1043 }
1044 return extra_params;
1045}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001046
Paul Crowley5afbc622017-11-27 09:42:17 -08001047static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1048 const char* real_blk_name, char* crypto_blk_name, const char* name,
1049 uint32_t flags) {
1050 char buffer[DM_CRYPT_BUF_SIZE];
1051 struct dm_ioctl* io;
1052 unsigned int minor;
1053 int fd = 0;
1054 int err;
1055 int retval = -1;
1056 int version[3];
1057 int load_count;
1058 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001059
Paul Crowley5afbc622017-11-27 09:42:17 -08001060 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1061 SLOGE("Cannot open device-mapper\n");
1062 goto errout;
1063 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001064
Paul Crowley5afbc622017-11-27 09:42:17 -08001065 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001066
Paul Crowley5afbc622017-11-27 09:42:17 -08001067 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1068 err = ioctl(fd, DM_DEV_CREATE, io);
1069 if (err) {
1070 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1071 goto errout;
1072 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001073
Paul Crowley5afbc622017-11-27 09:42:17 -08001074 /* Get the device status, in particular, the name of it's device file */
1075 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1076 if (ioctl(fd, DM_DEV_STATUS, io)) {
1077 SLOGE("Cannot retrieve dm-crypt device status\n");
1078 goto errout;
1079 }
1080 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1081 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001082
Paul Crowley5afbc622017-11-27 09:42:17 -08001083 if (!get_dm_crypt_version(fd, name, version)) {
1084 /* Support for allow_discards was added in version 1.11.0 */
1085 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1086 extra_params_vec.emplace_back("allow_discards");
1087 }
1088 }
1089 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1090 extra_params_vec.emplace_back("allow_encrypt_override");
1091 }
1092 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1093 extra_params_as_string(extra_params_vec).c_str());
1094 if (load_count < 0) {
1095 SLOGE("Cannot load dm-crypt mapping table.\n");
1096 goto errout;
1097 } else if (load_count > 1) {
1098 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1099 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001100
Paul Crowley5afbc622017-11-27 09:42:17 -08001101 /* Resume this device to activate it */
1102 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001103
Paul Crowley5afbc622017-11-27 09:42:17 -08001104 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1105 SLOGE("Cannot resume the dm-crypt device\n");
1106 goto errout;
1107 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001108
Paul Crowleycfe39722018-10-30 15:59:24 -07001109 /* Ensure the dm device has been created before returning. */
1110 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1111 // WaitForFile generates a suitable log message
1112 goto errout;
1113 }
1114
Paul Crowley5afbc622017-11-27 09:42:17 -08001115 /* We made it here with no errors. Woot! */
1116 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117
1118errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001119 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 -08001120
Paul Crowley14c8c072018-09-18 13:30:21 -07001121 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001122}
1123
Paul Crowley14c8c072018-09-18 13:30:21 -07001124static int delete_crypto_blk_dev(const char* name) {
1125 int fd;
1126 char buffer[DM_CRYPT_BUF_SIZE];
1127 struct dm_ioctl* io;
1128 int retval = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001129
Paul Crowley14c8c072018-09-18 13:30:21 -07001130 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1131 SLOGE("Cannot open device-mapper\n");
1132 goto errout;
1133 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001134
Paul Crowley14c8c072018-09-18 13:30:21 -07001135 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001136
Paul Crowley14c8c072018-09-18 13:30:21 -07001137 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1138 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1139 SLOGE("Cannot remove dm-crypt device\n");
1140 goto errout;
1141 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001142
Paul Crowley14c8c072018-09-18 13:30:21 -07001143 /* We made it here with no errors. Woot! */
1144 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001145
1146errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001147 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 -08001148
Paul Crowley14c8c072018-09-18 13:30:21 -07001149 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001150}
1151
Paul Crowley14c8c072018-09-18 13:30:21 -07001152static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1153 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001154 SLOGI("Using pbkdf2 for cryptfs KDF");
1155
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001157 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1158 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001159}
1160
Paul Crowley14c8c072018-09-18 13:30:21 -07001161static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001162 SLOGI("Using scrypt for cryptfs KDF");
1163
Paul Crowley14c8c072018-09-18 13:30:21 -07001164 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001165
1166 int N = 1 << ftr->N_factor;
1167 int r = 1 << ftr->r_factor;
1168 int p = 1 << ftr->p_factor;
1169
1170 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001171 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001172 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001173
Paul Crowley14c8c072018-09-18 13:30:21 -07001174 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001175}
1176
Paul Crowley14c8c072018-09-18 13:30:21 -07001177static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1178 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001179 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1180
1181 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001182 size_t signature_size;
1183 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001184 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001185
1186 int N = 1 << ftr->N_factor;
1187 int r = 1 << ftr->r_factor;
1188 int p = 1 << ftr->p_factor;
1189
Paul Crowley14c8c072018-09-18 13:30:21 -07001190 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001191 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001192
1193 if (rc) {
1194 SLOGE("scrypt failed");
1195 return -1;
1196 }
1197
Paul Crowley14c8c072018-09-18 13:30:21 -07001198 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001199 SLOGE("Signing failed");
1200 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001201 }
1202
Paul Crowley14c8c072018-09-18 13:30:21 -07001203 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1204 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001205 free(signature);
1206
1207 if (rc) {
1208 SLOGE("scrypt failed");
1209 return -1;
1210 }
1211
1212 return 0;
1213}
1214
Paul Crowley14c8c072018-09-18 13:30:21 -07001215static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1216 const unsigned char* decrypted_master_key,
1217 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1218 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001219 EVP_CIPHER_CTX e_ctx;
1220 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001221 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001222
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001223 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001224 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001225
1226 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001227 case KDF_SCRYPT_KEYMASTER:
1228 if (keymaster_create_key(crypt_ftr)) {
1229 SLOGE("keymaster_create_key failed");
1230 return -1;
1231 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001232
Paul Crowley14c8c072018-09-18 13:30:21 -07001233 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1234 SLOGE("scrypt failed");
1235 return -1;
1236 }
1237 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001238
Paul Crowley14c8c072018-09-18 13:30:21 -07001239 case KDF_SCRYPT:
1240 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1241 SLOGE("scrypt failed");
1242 return -1;
1243 }
1244 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001245
Paul Crowley14c8c072018-09-18 13:30:21 -07001246 default:
1247 SLOGE("Invalid kdf_type");
1248 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001249 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001250
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001252 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001253 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1254 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001255 SLOGE("EVP_EncryptInit failed\n");
1256 return -1;
1257 }
1258 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001259
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001261 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1262 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001263 SLOGE("EVP_EncryptUpdate failed\n");
1264 return -1;
1265 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001266 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001267 SLOGE("EVP_EncryptFinal failed\n");
1268 return -1;
1269 }
1270
Greg Kaiser59ad0182018-02-16 13:01:36 -08001271 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001272 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1273 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001274 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001275
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001276 /* Store the scrypt of the intermediate key, so we can validate if it's a
1277 password error or mount error when things go wrong.
1278 Note there's no need to check for errors, since if this is incorrect, we
1279 simply won't wipe userdata, which is the correct default behavior
1280 */
1281 int N = 1 << crypt_ftr->N_factor;
1282 int r = 1 << crypt_ftr->r_factor;
1283 int p = 1 << crypt_ftr->p_factor;
1284
Paul Crowley14c8c072018-09-18 13:30:21 -07001285 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1286 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001287 sizeof(crypt_ftr->scrypted_intermediate_key));
1288
1289 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001290 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001291 }
1292
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001293 EVP_CIPHER_CTX_cleanup(&e_ctx);
1294
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001295 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001296}
1297
Paul Crowley14c8c072018-09-18 13:30:21 -07001298static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1299 const unsigned char* encrypted_master_key, size_t keysize,
1300 unsigned char* decrypted_master_key, kdf_func kdf,
1301 void* kdf_params, unsigned char** intermediate_key,
1302 size_t* intermediate_key_size) {
1303 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1304 EVP_CIPHER_CTX d_ctx;
1305 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001306
Paul Crowley14c8c072018-09-18 13:30:21 -07001307 /* Turn the password into an intermediate key and IV that can decrypt the
1308 master key */
1309 if (kdf(passwd, salt, ikey, kdf_params)) {
1310 SLOGE("kdf failed");
1311 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001312 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001313
Paul Crowley14c8c072018-09-18 13:30:21 -07001314 /* Initialize the decryption engine */
1315 EVP_CIPHER_CTX_init(&d_ctx);
1316 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1317 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1318 return -1;
1319 }
1320 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1321 /* Decrypt the master key */
1322 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1323 keysize)) {
1324 return -1;
1325 }
1326 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1327 return -1;
1328 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001329
Paul Crowley14c8c072018-09-18 13:30:21 -07001330 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1331 return -1;
1332 }
1333
1334 /* Copy intermediate key if needed by params */
1335 if (intermediate_key && intermediate_key_size) {
1336 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1337 if (*intermediate_key) {
1338 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1339 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1340 }
1341 }
1342
1343 EVP_CIPHER_CTX_cleanup(&d_ctx);
1344
1345 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001346}
1347
Paul Crowley14c8c072018-09-18 13:30:21 -07001348static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001349 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001350 *kdf = scrypt_keymaster;
1351 *kdf_params = ftr;
1352 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001353 *kdf = scrypt;
1354 *kdf_params = ftr;
1355 } else {
1356 *kdf = pbkdf2;
1357 *kdf_params = NULL;
1358 }
1359}
1360
Paul Crowley14c8c072018-09-18 13:30:21 -07001361static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1362 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1363 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001364 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001365 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001366 int ret;
1367
1368 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001369 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1370 decrypted_master_key, kdf, kdf_params, intermediate_key,
1371 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001372 if (ret != 0) {
1373 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001374 }
1375
1376 return ret;
1377}
1378
Paul Crowley14c8c072018-09-18 13:30:21 -07001379static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1380 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001381 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001382 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001383
1384 /* Get some random bits for a key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001385 fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001386 read(fd, key_buf, sizeof(key_buf));
1387 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001388 close(fd);
1389
1390 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001391 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001392}
1393
Paul Crowley14c8c072018-09-18 13:30:21 -07001394int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001395 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001396#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001397
1398 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001399 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001400 if (umount(mountpoint) == 0) {
1401 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001402 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001403
1404 if (errno == EINVAL) {
1405 /* EINVAL is returned if the directory is not a mountpoint,
1406 * i.e. there is no filesystem mounted there. So just get out.
1407 */
1408 break;
1409 }
1410
1411 err = errno;
1412
1413 /* If allowed, be increasingly aggressive before the last two retries */
1414 if (kill) {
1415 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1416 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001417 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001418 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1419 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001420 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001421 }
1422 }
1423
1424 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001425 }
1426
1427 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001428 SLOGD("unmounting %s succeeded\n", mountpoint);
1429 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001431 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1432 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1433 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001434 }
1435
1436 return rc;
1437}
1438
Paul Crowley14c8c072018-09-18 13:30:21 -07001439static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001440 // NOTE: post_fs_data results in init calling back around to vold, so all
1441 // callers to this method must be async
1442
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001443 /* Do the prep of the /data filesystem */
1444 property_set("vold.post_fs_data_done", "0");
1445 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001446 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001447
Ken Sumrallc5872692013-05-14 15:26:31 -07001448 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001449 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001450 /* We timed out to prep /data in time. Continue wait. */
1451 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001452 }
Wei Wang42e38102017-06-07 10:46:12 -07001453 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001454}
1455
Paul Crowley14c8c072018-09-18 13:30:21 -07001456static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001457 // Mark the footer as bad
1458 struct crypt_mnt_ftr crypt_ftr;
1459 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1460 SLOGE("Failed to get crypto footer - panic");
1461 return;
1462 }
1463
1464 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1465 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1466 SLOGE("Failed to set crypto footer - panic");
1467 return;
1468 }
1469}
1470
Paul Crowley14c8c072018-09-18 13:30:21 -07001471static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001472 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001473 SLOGE("Failed to mount tmpfs on data - panic");
1474 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001475 }
1476
1477 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1478 SLOGE("Failed to trigger post fs data - panic");
1479 return;
1480 }
1481
1482 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1483 SLOGE("Failed to trigger restart min framework - panic");
1484 return;
1485 }
1486}
1487
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001488/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001489static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001490 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001491 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001492 static int restart_successful = 0;
1493
1494 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001495 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001496 SLOGE("Encrypted filesystem not validated, aborting");
1497 return -1;
1498 }
1499
1500 if (restart_successful) {
1501 SLOGE("System already restarted with encrypted disk, aborting");
1502 return -1;
1503 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001504
Paul Lawrencef4faa572014-01-29 13:31:03 -08001505 if (restart_main) {
1506 /* Here is where we shut down the framework. The init scripts
1507 * start all services in one of three classes: core, main or late_start.
1508 * On boot, we start core and main. Now, we stop main, but not core,
1509 * as core includes vold and a few other really important things that
1510 * we need to keep running. Once main has stopped, we should be able
1511 * to umount the tmpfs /data, then mount the encrypted /data.
1512 * We then restart the class main, and also the class late_start.
1513 * At the moment, I've only put a few things in late_start that I know
1514 * are not needed to bring up the framework, and that also cause problems
1515 * with unmounting the tmpfs /data, but I hope to add add more services
1516 * to the late_start class as we optimize this to decrease the delay
1517 * till the user is asked for the password to the filesystem.
1518 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001519
Paul Lawrencef4faa572014-01-29 13:31:03 -08001520 /* The init files are setup to stop the class main when vold.decrypt is
1521 * set to trigger_reset_main.
1522 */
1523 property_set("vold.decrypt", "trigger_reset_main");
1524 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001525
Paul Lawrencef4faa572014-01-29 13:31:03 -08001526 /* Ugh, shutting down the framework is not synchronous, so until it
1527 * can be fixed, this horrible hack will wait a moment for it all to
1528 * shut down before proceeding. Without it, some devices cannot
1529 * restart the graphics services.
1530 */
1531 sleep(2);
1532 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001533
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001534 /* Now that the framework is shutdown, we should be able to umount()
1535 * the tmpfs filesystem, and mount the real one.
1536 */
1537
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001538 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1539 if (strlen(crypto_blkdev) == 0) {
1540 SLOGE("fs_crypto_blkdev not set\n");
1541 return -1;
1542 }
1543
Paul Crowley14c8c072018-09-18 13:30:21 -07001544 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001545 /* If ro.crypto.readonly is set to 1, mount the decrypted
1546 * filesystem readonly. This is used when /data is mounted by
1547 * recovery mode.
1548 */
1549 char ro_prop[PROPERTY_VALUE_MAX];
1550 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001551 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001552 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001553 if (rec) {
1554 rec->flags |= MS_RDONLY;
1555 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001556 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001557
Ken Sumralle5032c42012-04-01 23:58:44 -07001558 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001559 int retries = RETRY_MOUNT_ATTEMPTS;
1560 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001561
1562 /*
1563 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1564 * partitions in the fsck domain.
1565 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001566 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001567 SLOGE("Failed to setexeccon");
1568 return -1;
1569 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001570 bool needs_cp = android::vold::cp_needsCheckpoint();
1571 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1572 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001573 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1574 /* TODO: invoke something similar to
1575 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1576 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001577 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001578 if (--retries) {
1579 sleep(RETRY_MOUNT_DELAY_SECONDS);
1580 } else {
1581 /* Let's hope that a reboot clears away whatever is keeping
1582 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001583 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001584 }
1585 } else {
1586 SLOGE("Failed to mount decrypted data");
1587 cryptfs_set_corrupt();
1588 cryptfs_trigger_restart_min_framework();
1589 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001590 if (setexeccon(NULL)) {
1591 SLOGE("Failed to setexeccon");
1592 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001593 return -1;
1594 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001595 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001596 if (setexeccon(NULL)) {
1597 SLOGE("Failed to setexeccon");
1598 return -1;
1599 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001600
Ken Sumralle5032c42012-04-01 23:58:44 -07001601 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001602 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001603 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001604
1605 /* startup service classes main and late_start */
1606 property_set("vold.decrypt", "trigger_restart_framework");
1607 SLOGD("Just triggered restart_framework\n");
1608
1609 /* Give it a few moments to get started */
1610 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001611 }
1612
Ken Sumrall0cc16632011-01-18 20:32:26 -08001613 if (rc == 0) {
1614 restart_successful = 1;
1615 }
1616
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001617 return rc;
1618}
1619
Paul Crowley14c8c072018-09-18 13:30:21 -07001620int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001621 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001622 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001623 SLOGE("cryptfs_restart not valid for file encryption:");
1624 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001625 }
1626
Paul Lawrencef4faa572014-01-29 13:31:03 -08001627 /* Call internal implementation forcing a restart of main service group */
1628 return cryptfs_restart_internal(1);
1629}
1630
Paul Crowley14c8c072018-09-18 13:30:21 -07001631static int do_crypto_complete(const char* mount_point) {
1632 struct crypt_mnt_ftr crypt_ftr;
1633 char encrypted_state[PROPERTY_VALUE_MAX];
1634 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001635
Paul Crowley14c8c072018-09-18 13:30:21 -07001636 property_get("ro.crypto.state", encrypted_state, "");
1637 if (strcmp(encrypted_state, "encrypted")) {
1638 SLOGE("not running with encryption, aborting");
1639 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001640 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001641
Paul Crowley14c8c072018-09-18 13:30:21 -07001642 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001643 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001644 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1645 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001646
Paul Crowley14c8c072018-09-18 13:30:21 -07001647 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1648 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001649
Paul Crowley14c8c072018-09-18 13:30:21 -07001650 /*
1651 * Only report this error if key_loc is a file and it exists.
1652 * If the device was never encrypted, and /data is not mountable for
1653 * some reason, returning 1 should prevent the UI from presenting the
1654 * a "enter password" screen, or worse, a "press button to wipe the
1655 * device" screen.
1656 */
1657 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1658 SLOGE("master key file does not exist, aborting");
1659 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1660 } else {
1661 SLOGE("Error getting crypt footer and key\n");
1662 return CRYPTO_COMPLETE_BAD_METADATA;
1663 }
1664 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001665
Paul Crowley14c8c072018-09-18 13:30:21 -07001666 // Test for possible error flags
1667 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1668 SLOGE("Encryption process is partway completed\n");
1669 return CRYPTO_COMPLETE_PARTIAL;
1670 }
1671
1672 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1673 SLOGE("Encryption process was interrupted but cannot continue\n");
1674 return CRYPTO_COMPLETE_INCONSISTENT;
1675 }
1676
1677 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1678 SLOGE("Encryption is successful but data is corrupt\n");
1679 return CRYPTO_COMPLETE_CORRUPT;
1680 }
1681
1682 /* We passed the test! We shall diminish, and return to the west */
1683 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001684}
1685
Paul Crowley14c8c072018-09-18 13:30:21 -07001686static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1687 const char* mount_point, const char* label) {
1688 unsigned char decrypted_master_key[MAX_KEY_LEN];
1689 char crypto_blkdev[MAXPATHLEN];
1690 char real_blkdev[MAXPATHLEN];
1691 char tmp_mount_point[64];
1692 unsigned int orig_failed_decrypt_count;
1693 int rc;
1694 int use_keymaster = 0;
1695 int upgrade = 0;
1696 unsigned char* intermediate_key = 0;
1697 size_t intermediate_key_size = 0;
1698 int N = 1 << crypt_ftr->N_factor;
1699 int r = 1 << crypt_ftr->r_factor;
1700 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001701
Paul Crowley14c8c072018-09-18 13:30:21 -07001702 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1703 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001704
Paul Crowley14c8c072018-09-18 13:30:21 -07001705 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1706 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1707 &intermediate_key_size)) {
1708 SLOGE("Failed to decrypt master key\n");
1709 rc = -1;
1710 goto errout;
1711 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001712 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713
Paul Crowley14c8c072018-09-18 13:30:21 -07001714 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001715
Paul Crowley14c8c072018-09-18 13:30:21 -07001716 // Create crypto block device - all (non fatal) code paths
1717 // need it
1718 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
1719 0)) {
1720 SLOGE("Error creating decrypted block device\n");
1721 rc = -1;
1722 goto errout;
1723 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724
Paul Crowley14c8c072018-09-18 13:30:21 -07001725 /* Work out if the problem is the password or the data */
1726 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001727
Paul Crowley14c8c072018-09-18 13:30:21 -07001728 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1729 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1730 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001731
Paul Crowley14c8c072018-09-18 13:30:21 -07001732 // Does the key match the crypto footer?
1733 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1734 sizeof(scrypted_intermediate_key)) == 0) {
1735 SLOGI("Password matches");
1736 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001737 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001738 /* Try mounting the file system anyway, just in case the problem's with
1739 * the footer, not the key. */
1740 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1741 mkdir(tmp_mount_point, 0755);
1742 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1743 SLOGE("Error temp mounting decrypted block device\n");
1744 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001745
Paul Crowley14c8c072018-09-18 13:30:21 -07001746 rc = ++crypt_ftr->failed_decrypt_count;
1747 put_crypt_ftr_and_key(crypt_ftr);
1748 } else {
1749 /* Success! */
1750 SLOGI("Password did not match but decrypted drive mounted - continue");
1751 umount(tmp_mount_point);
1752 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001753 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001754 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001755
Paul Crowley14c8c072018-09-18 13:30:21 -07001756 if (rc == 0) {
1757 crypt_ftr->failed_decrypt_count = 0;
1758 if (orig_failed_decrypt_count != 0) {
1759 put_crypt_ftr_and_key(crypt_ftr);
1760 }
1761
1762 /* Save the name of the crypto block device
1763 * so we can mount it when restarting the framework. */
1764 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1765
1766 /* Also save a the master key so we can reencrypted the key
1767 * the key when we want to change the password on it. */
1768 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1769 saved_mount_point = strdup(mount_point);
1770 master_key_saved = 1;
1771 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1772 rc = 0;
1773
1774 // Upgrade if we're not using the latest KDF.
1775 use_keymaster = keymaster_check_compatibility();
1776 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1777 // Don't allow downgrade
1778 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1779 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1780 upgrade = 1;
1781 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1782 crypt_ftr->kdf_type = KDF_SCRYPT;
1783 upgrade = 1;
1784 }
1785
1786 if (upgrade) {
1787 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1788 crypt_ftr->master_key, crypt_ftr);
1789 if (!rc) {
1790 rc = put_crypt_ftr_and_key(crypt_ftr);
1791 }
1792 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1793
1794 // Do not fail even if upgrade failed - machine is bootable
1795 // Note that if this code is ever hit, there is a *serious* problem
1796 // since KDFs should never fail. You *must* fix the kdf before
1797 // proceeding!
1798 if (rc) {
1799 SLOGW(
1800 "Upgrade failed with error %d,"
1801 " but continuing with previous state",
1802 rc);
1803 rc = 0;
1804 }
1805 }
1806 }
1807
1808errout:
1809 if (intermediate_key) {
1810 memset(intermediate_key, 0, intermediate_key_size);
1811 free(intermediate_key);
1812 }
1813 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001814}
1815
Ken Sumrall29d8da82011-05-18 17:20:07 -07001816/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001817 * Called by vold when it's asked to mount an encrypted external
1818 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001819 * as any metadata is been stored in a separate, small partition. We
1820 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001821 *
1822 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001823 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001824int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1825 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001826 uint64_t nr_sec = 0;
1827 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001828 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001829 return -1;
1830 }
1831
Jeff Sharkey9c484982015-03-31 10:35:33 -07001832 struct crypt_mnt_ftr ext_crypt_ftr;
1833 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1834 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001835 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001836 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001837 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001838 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001839 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001840 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1841 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001842
Paul Crowley385cb8c2018-03-29 13:27:23 -07001843 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001844}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001845
Jeff Sharkey9c484982015-03-31 10:35:33 -07001846/*
1847 * Called by vold when it's asked to unmount an encrypted external
1848 * storage volume.
1849 */
1850int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001851 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001852}
1853
Paul Crowley14c8c072018-09-18 13:30:21 -07001854int cryptfs_crypto_complete(void) {
1855 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001856}
1857
Paul Crowley14c8c072018-09-18 13:30:21 -07001858int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001859 char encrypted_state[PROPERTY_VALUE_MAX];
1860 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001861 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1862 SLOGE(
1863 "encrypted fs already validated or not running with encryption,"
1864 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001865 return -1;
1866 }
1867
1868 if (get_crypt_ftr_and_key(crypt_ftr)) {
1869 SLOGE("Error getting crypt footer and key");
1870 return -1;
1871 }
1872
1873 return 0;
1874}
1875
Paul Crowley14c8c072018-09-18 13:30:21 -07001876int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001877 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001878 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001879 SLOGE("cryptfs_check_passwd not valid for file encryption");
1880 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001881 }
1882
Paul Lawrencef4faa572014-01-29 13:31:03 -08001883 struct crypt_mnt_ftr crypt_ftr;
1884 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001885
Paul Lawrencef4faa572014-01-29 13:31:03 -08001886 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001887 if (rc) {
1888 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001889 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001890 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001891
Paul Crowley14c8c072018-09-18 13:30:21 -07001892 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001893 if (rc) {
1894 SLOGE("Password did not match");
1895 return rc;
1896 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001897
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001898 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1899 // Here we have a default actual password but a real password
1900 // we must test against the scrypted value
1901 // First, we must delete the crypto block device that
1902 // test_mount_encrypted_fs leaves behind as a side effect
1903 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001904 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1905 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001906 if (rc) {
1907 SLOGE("Default password did not match on reboot encryption");
1908 return rc;
1909 }
1910
1911 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1912 put_crypt_ftr_and_key(&crypt_ftr);
1913 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1914 if (rc) {
1915 SLOGE("Could not change password on reboot encryption");
1916 return rc;
1917 }
1918 }
1919
1920 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001921 cryptfs_clear_password();
1922 password = strdup(passwd);
1923 struct timespec now;
1924 clock_gettime(CLOCK_BOOTTIME, &now);
1925 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001926 }
1927
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001928 return rc;
1929}
1930
Paul Crowley14c8c072018-09-18 13:30:21 -07001931int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001932 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001933 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001934 char encrypted_state[PROPERTY_VALUE_MAX];
1935 int rc;
1936
1937 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001938 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001939 SLOGE("device not encrypted, aborting");
1940 return -2;
1941 }
1942
1943 if (!master_key_saved) {
1944 SLOGE("encrypted fs not yet mounted, aborting");
1945 return -1;
1946 }
1947
1948 if (!saved_mount_point) {
1949 SLOGE("encrypted fs failed to save mount point, aborting");
1950 return -1;
1951 }
1952
Ken Sumrall160b4d62013-04-22 12:15:39 -07001953 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001954 SLOGE("Error getting crypt footer and key\n");
1955 return -1;
1956 }
1957
1958 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1959 /* If the device has no password, then just say the password is valid */
1960 rc = 0;
1961 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001962 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001963 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1964 /* They match, the password is correct */
1965 rc = 0;
1966 } else {
1967 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1968 sleep(1);
1969 rc = 1;
1970 }
1971 }
1972
1973 return rc;
1974}
1975
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001976/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08001977 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001978 * Presumably, at a minimum, the caller will update the
1979 * filesystem size and crypto_type_name after calling this function.
1980 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001981static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001982 off64_t off;
1983
1984 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001985 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001986 ftr->major_version = CURRENT_MAJOR_VERSION;
1987 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001988 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08001989 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07001990
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001991 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001992 case 1:
1993 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1994 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001995
Paul Crowley14c8c072018-09-18 13:30:21 -07001996 case 0:
1997 ftr->kdf_type = KDF_SCRYPT;
1998 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001999
Paul Crowley14c8c072018-09-18 13:30:21 -07002000 default:
2001 SLOGE("keymaster_check_compatibility failed");
2002 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002003 }
2004
Kenny Rootc4c70f12013-06-14 12:11:38 -07002005 get_device_scrypt_params(ftr);
2006
Ken Sumrall160b4d62013-04-22 12:15:39 -07002007 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2008 if (get_crypt_ftr_info(NULL, &off) == 0) {
2009 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002010 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002011 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002012
2013 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002014}
2015
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002016#define FRAMEWORK_BOOT_WAIT 60
2017
Paul Crowley14c8c072018-09-18 13:30:21 -07002018static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2019 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002020 if (fd == -1) {
2021 SLOGE("Error opening file %s", filename);
2022 return -1;
2023 }
2024
2025 char block[CRYPT_INPLACE_BUFSIZE];
2026 memset(block, 0, sizeof(block));
2027 if (unix_read(fd, block, sizeof(block)) < 0) {
2028 SLOGE("Error reading file %s", filename);
2029 close(fd);
2030 return -1;
2031 }
2032
2033 close(fd);
2034
2035 SHA256_CTX c;
2036 SHA256_Init(&c);
2037 SHA256_Update(&c, block, sizeof(block));
2038 SHA256_Final(buf, &c);
2039
2040 return 0;
2041}
2042
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002043static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2044 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002045 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002046 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002047
Paul Lawrence87999172014-02-20 12:21:31 -08002048 /* The size of the userdata partition, and add in the vold volumes below */
2049 tot_encryption_size = crypt_ftr->fs_size;
2050
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002051 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002052 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002053
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002054 if (rc == ENABLE_INPLACE_ERR_DEV) {
2055 /* Hack for b/17898962 */
2056 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2057 cryptfs_reboot(RebootType::reboot);
2058 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002059
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002060 if (!rc) {
2061 crypt_ftr->encrypted_upto = cur_encryption_done;
2062 }
Paul Lawrence87999172014-02-20 12:21:31 -08002063
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002064 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2065 /* The inplace routine never actually sets the progress to 100% due
2066 * to the round down nature of integer division, so set it here */
2067 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002068 }
2069
2070 return rc;
2071}
2072
Paul Crowleyb64933a2017-10-31 08:25:55 -07002073static int vold_unmountAll(void) {
2074 VolumeManager* vm = VolumeManager::Instance();
2075 return vm->unmountAll();
2076}
2077
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002078int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002079 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002080 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002081 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002082 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002083 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002084 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002085 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002086 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002087 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002088 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002089 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002090 bool onlyCreateHeader = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002091
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002092 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002093 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2094 /* An encryption was underway and was interrupted */
2095 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2096 crypt_ftr.encrypted_upto = 0;
2097 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002098
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002099 /* At this point, we are in an inconsistent state. Until we successfully
2100 complete encryption, a reboot will leave us broken. So mark the
2101 encryption failed in case that happens.
2102 On successfully completing encryption, remove this flag */
2103 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002104
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002105 put_crypt_ftr_and_key(&crypt_ftr);
2106 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2107 if (!check_ftr_sha(&crypt_ftr)) {
2108 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2109 put_crypt_ftr_and_key(&crypt_ftr);
2110 goto error_unencrypted;
2111 }
2112
2113 /* Doing a reboot-encryption*/
2114 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2115 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2116 rebootEncryption = true;
2117 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002118 } else {
2119 // We don't want to accidentally reference invalid data.
2120 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002121 }
2122
2123 property_get("ro.crypto.state", encrypted_state, "");
2124 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2125 SLOGE("Device is already running encrypted, aborting");
2126 goto error_unencrypted;
2127 }
2128
2129 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002130 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2131 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002132
Ken Sumrall3ed82362011-01-28 23:31:16 -08002133 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002134 uint64_t nr_sec;
2135 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002136 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2137 goto error_unencrypted;
2138 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002139
2140 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002141 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002142 uint64_t fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002143 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002144 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002145
Paul Lawrence87999172014-02-20 12:21:31 -08002146 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002147
2148 if (fs_size_sec > max_fs_size_sec) {
2149 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2150 goto error_unencrypted;
2151 }
2152 }
2153
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002154 /* Get a wakelock as this may take a while, and we don't want the
2155 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2156 * wants to keep the screen on, it can grab a full wakelock.
2157 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002158 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002159 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2160
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002161 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002162 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002163 */
2164 property_set("vold.decrypt", "trigger_shutdown_framework");
2165 SLOGD("Just asked init to shut down class main\n");
2166
Jeff Sharkey9c484982015-03-31 10:35:33 -07002167 /* Ask vold to unmount all devices that it manages */
2168 if (vold_unmountAll()) {
2169 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002170 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002171
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002172 /* no_ui means we are being called from init, not settings.
2173 Now we always reboot from settings, so !no_ui means reboot
2174 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002175 if (!no_ui) {
2176 /* Try fallback, which is to reboot and try there */
2177 onlyCreateHeader = true;
2178 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2179 if (breadcrumb == 0) {
2180 SLOGE("Failed to create breadcrumb file");
2181 goto error_shutting_down;
2182 }
2183 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002184 }
2185
2186 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002187 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002188 /* Now that /data is unmounted, we need to mount a tmpfs
2189 * /data, set a property saying we're doing inplace encryption,
2190 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002191 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002192 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002193 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002194 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002195 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002196 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002197
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002198 /* restart the framework. */
2199 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002200 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002201
Ken Sumrall92736ef2012-10-17 20:57:14 -07002202 /* Ugh, shutting down the framework is not synchronous, so until it
2203 * can be fixed, this horrible hack will wait a moment for it all to
2204 * shut down before proceeding. Without it, some devices cannot
2205 * restart the graphics services.
2206 */
2207 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002208 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002209
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002210 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002211 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002212 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002213 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2214 goto error_shutting_down;
2215 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002216
Paul Lawrence87999172014-02-20 12:21:31 -08002217 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002218 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002219 } else {
2220 crypt_ftr.fs_size = nr_sec;
2221 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002222 /* At this point, we are in an inconsistent state. Until we successfully
2223 complete encryption, a reboot will leave us broken. So mark the
2224 encryption failed in case that happens.
2225 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002226 if (onlyCreateHeader) {
2227 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2228 } else {
2229 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2230 }
Paul Lawrence87999172014-02-20 12:21:31 -08002231 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002232 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2233 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002234
Paul Lawrence87999172014-02-20 12:21:31 -08002235 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002236 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2237 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002238 SLOGE("Cannot create encrypted master key\n");
2239 goto error_shutting_down;
2240 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002241
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002242 /* Replace scrypted intermediate key if we are preparing for a reboot */
2243 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002244 unsigned char fake_master_key[MAX_KEY_LEN];
2245 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002246 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002247 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2248 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002249 }
2250
Paul Lawrence87999172014-02-20 12:21:31 -08002251 /* Write the key to the end of the partition */
2252 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002253
Paul Lawrence87999172014-02-20 12:21:31 -08002254 /* If any persistent data has been remembered, save it.
2255 * If none, create a valid empty table and save that.
2256 */
2257 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002258 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2259 if (pdata) {
2260 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2261 persist_data = pdata;
2262 }
Paul Lawrence87999172014-02-20 12:21:31 -08002263 }
2264 if (persist_data) {
2265 save_persistent_data();
2266 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002267 }
2268
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002269 if (onlyCreateHeader) {
2270 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002271 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002272 }
2273
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002274 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002275 /* startup service classes main and late_start */
2276 property_set("vold.decrypt", "trigger_restart_min_framework");
2277 SLOGD("Just triggered restart_min_framework\n");
2278
2279 /* OK, the framework is restarted and will soon be showing a
2280 * progress bar. Time to setup an encrypted mapping, and
2281 * either write a new filesystem, or encrypt in place updating
2282 * the progress bar as we work.
2283 */
2284 }
2285
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002286 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002287 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002288 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002289
Paul Lawrence87999172014-02-20 12:21:31 -08002290 /* If we are continuing, check checksums match */
2291 rc = 0;
2292 if (previously_encrypted_upto) {
2293 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2294 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002295
Paul Crowley14c8c072018-09-18 13:30:21 -07002296 if (!rc &&
2297 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002298 SLOGE("Checksums do not match - trigger wipe");
2299 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002300 }
2301 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002302
Paul Lawrence87999172014-02-20 12:21:31 -08002303 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002304 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002305 previously_encrypted_upto);
2306 }
2307
2308 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002309 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002310 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002311 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002312 SLOGE("Error calculating checksum for continuing encryption");
2313 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002314 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002315 }
2316
2317 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002318 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002319
Paul Crowley14c8c072018-09-18 13:30:21 -07002320 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002321 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002322 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002323
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002324 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002325 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2326 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002327 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002328 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002329
Paul Lawrence6bfed202014-07-28 12:47:22 -07002330 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002331
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002332 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2333 char value[PROPERTY_VALUE_MAX];
2334 property_get("ro.crypto.state", value, "");
2335 if (!strcmp(value, "")) {
2336 /* default encryption - continue first boot sequence */
2337 property_set("ro.crypto.state", "encrypted");
2338 property_set("ro.crypto.type", "block");
2339 release_wake_lock(lockid);
2340 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2341 // Bring up cryptkeeper that will check the password and set it
2342 property_set("vold.decrypt", "trigger_shutdown_framework");
2343 sleep(2);
2344 property_set("vold.encrypt_progress", "");
2345 cryptfs_trigger_restart_min_framework();
2346 } else {
2347 cryptfs_check_passwd(DEFAULT_PASSWORD);
2348 cryptfs_restart_internal(1);
2349 }
2350 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002351 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002352 sleep(2); /* Give the UI a chance to show 100% progress */
2353 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002354 }
Paul Lawrence87999172014-02-20 12:21:31 -08002355 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002356 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002357 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002358 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002359 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002360 char value[PROPERTY_VALUE_MAX];
2361
Ken Sumrall319369a2012-06-27 16:30:18 -07002362 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002363 if (!strcmp(value, "1")) {
2364 /* wipe data if encryption failed */
2365 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002366 std::string err;
2367 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002368 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002369 if (!write_bootloader_message(options, &err)) {
2370 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002371 }
Josh Gaofec44372017-08-28 13:22:55 -07002372 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002373 } else {
2374 /* set property to trigger dialog */
2375 property_set("vold.encrypt_progress", "error_partially_encrypted");
2376 release_wake_lock(lockid);
2377 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002378 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002379 }
2380
Ken Sumrall3ed82362011-01-28 23:31:16 -08002381 /* hrm, the encrypt step claims success, but the reboot failed.
2382 * This should not happen.
2383 * Set the property and return. Hope the framework can deal with it.
2384 */
2385 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002386 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002387 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002388
2389error_unencrypted:
2390 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002391 if (lockid[0]) {
2392 release_wake_lock(lockid);
2393 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002394 return -1;
2395
2396error_shutting_down:
2397 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2398 * but the framework is stopped and not restarted to show the error, so it's up to
2399 * vold to restart the system.
2400 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002401 SLOGE(
2402 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2403 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002404 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002405
2406 /* shouldn't get here */
2407 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002408 if (lockid[0]) {
2409 release_wake_lock(lockid);
2410 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002411 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002412}
2413
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002414int cryptfs_enable(int type, const char* passwd, int no_ui) {
2415 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002416}
2417
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002418int cryptfs_enable_default(int no_ui) {
2419 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002420}
2421
Paul Crowley14c8c072018-09-18 13:30:21 -07002422int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002423 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002424 SLOGE("cryptfs_changepw not valid for file encryption");
2425 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002426 }
2427
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002428 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002429 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002430
2431 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002432 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002433 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002434 return -1;
2435 }
2436
Paul Lawrencef4faa572014-01-29 13:31:03 -08002437 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2438 SLOGE("Invalid crypt_type %d", crypt_type);
2439 return -1;
2440 }
2441
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002442 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002443 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002444 SLOGE("Error getting crypt footer and key");
2445 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002446 }
2447
Paul Lawrencef4faa572014-01-29 13:31:03 -08002448 crypt_ftr.crypt_type = crypt_type;
2449
Paul Crowley14c8c072018-09-18 13:30:21 -07002450 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2451 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002452 if (rc) {
2453 SLOGE("Encrypt master key failed: %d", rc);
2454 return -1;
2455 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002456 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002457 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002458
2459 return 0;
2460}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002461
Rubin Xu85c01f92014-10-13 12:49:54 +01002462static unsigned int persist_get_max_entries(int encrypted) {
2463 struct crypt_mnt_ftr crypt_ftr;
2464 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002465
2466 /* If encrypted, use the values from the crypt_ftr, otherwise
2467 * use the values for the current spec.
2468 */
2469 if (encrypted) {
2470 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002471 /* Something is wrong, assume no space for entries */
2472 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002473 }
2474 dsize = crypt_ftr.persist_data_size;
2475 } else {
2476 dsize = CRYPT_PERSIST_DATA_SIZE;
2477 }
2478
Rubin Xuf83cc612018-10-09 16:13:38 +01002479 if (dsize > sizeof(struct crypt_persist_data)) {
2480 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2481 } else {
2482 return 0;
2483 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002484}
2485
Paul Crowley14c8c072018-09-18 13:30:21 -07002486static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002487 unsigned int i;
2488
2489 if (persist_data == NULL) {
2490 return -1;
2491 }
2492 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2493 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2494 /* We found it! */
2495 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2496 return 0;
2497 }
2498 }
2499
2500 return -1;
2501}
2502
Paul Crowley14c8c072018-09-18 13:30:21 -07002503static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002504 unsigned int i;
2505 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002506 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002507
2508 if (persist_data == NULL) {
2509 return -1;
2510 }
2511
Rubin Xu85c01f92014-10-13 12:49:54 +01002512 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002513
2514 num = persist_data->persist_valid_entries;
2515
2516 for (i = 0; i < num; i++) {
2517 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2518 /* We found an existing entry, update it! */
2519 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2520 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2521 return 0;
2522 }
2523 }
2524
2525 /* We didn't find it, add it to the end, if there is room */
2526 if (persist_data->persist_valid_entries < max_persistent_entries) {
2527 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2528 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2529 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2530 persist_data->persist_valid_entries++;
2531 return 0;
2532 }
2533
2534 return -1;
2535}
2536
Rubin Xu85c01f92014-10-13 12:49:54 +01002537/**
2538 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2539 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2540 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002541int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002542 std::string key_ = key;
2543 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002544
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002545 std::string parsed_field;
2546 unsigned parsed_index;
2547
2548 std::string::size_type split = key_.find_last_of('_');
2549 if (split == std::string::npos) {
2550 parsed_field = key_;
2551 parsed_index = 0;
2552 } else {
2553 parsed_field = key_.substr(0, split);
2554 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002555 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002556
2557 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002558}
2559
2560/*
2561 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2562 * remaining entries starting from index will be deleted.
2563 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2564 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2565 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2566 *
2567 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002568static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002569 unsigned int i;
2570 unsigned int j;
2571 unsigned int num;
2572
2573 if (persist_data == NULL) {
2574 return PERSIST_DEL_KEY_ERROR_OTHER;
2575 }
2576
2577 num = persist_data->persist_valid_entries;
2578
Paul Crowley14c8c072018-09-18 13:30:21 -07002579 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002580 // Filter out to-be-deleted entries in place.
2581 for (i = 0; i < num; i++) {
2582 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2583 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2584 j++;
2585 }
2586 }
2587
2588 if (j < num) {
2589 persist_data->persist_valid_entries = j;
2590 // Zeroise the remaining entries
2591 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2592 return PERSIST_DEL_KEY_OK;
2593 } else {
2594 // Did not find an entry matching the given fieldname
2595 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2596 }
2597}
2598
Paul Crowley14c8c072018-09-18 13:30:21 -07002599static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002600 unsigned int i;
2601 unsigned int count;
2602
2603 if (persist_data == NULL) {
2604 return -1;
2605 }
2606
2607 count = 0;
2608 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2609 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2610 count++;
2611 }
2612 }
2613
2614 return count;
2615}
2616
Ken Sumrall160b4d62013-04-22 12:15:39 -07002617/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002618int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002619 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002620 SLOGE("Cannot get field when file encrypted");
2621 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002622 }
2623
Ken Sumrall160b4d62013-04-22 12:15:39 -07002624 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002625 /* CRYPTO_GETFIELD_OK is success,
2626 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2627 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2628 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002629 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002630 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2631 int i;
2632 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002633
2634 if (persist_data == NULL) {
2635 load_persistent_data();
2636 if (persist_data == NULL) {
2637 SLOGE("Getfield error, cannot load persistent data");
2638 goto out;
2639 }
2640 }
2641
Rubin Xu85c01f92014-10-13 12:49:54 +01002642 // Read value from persistent entries. If the original value is split into multiple entries,
2643 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002644 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002645 // 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 -07002646 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002647 // value too small
2648 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2649 goto out;
2650 }
2651 rc = CRYPTO_GETFIELD_OK;
2652
2653 for (i = 1; /* break explicitly */; i++) {
2654 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002655 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002656 // If the fieldname is very long, we stop as soon as it begins to overflow the
2657 // maximum field length. At this point we have in fact fully read out the original
2658 // value because cryptfs_setfield would not allow fields with longer names to be
2659 // written in the first place.
2660 break;
2661 }
2662 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002663 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2664 // value too small.
2665 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2666 goto out;
2667 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002668 } else {
2669 // Exhaust all entries.
2670 break;
2671 }
2672 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002673 } else {
2674 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002675 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002676 }
2677
2678out:
2679 return rc;
2680}
2681
2682/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002683int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002684 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002685 SLOGE("Cannot set field when file encrypted");
2686 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002687 }
2688
Ken Sumrall160b4d62013-04-22 12:15:39 -07002689 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002690 /* 0 is success, negative values are error */
2691 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002692 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002693 unsigned int field_id;
2694 char temp_field[PROPERTY_KEY_MAX];
2695 unsigned int num_entries;
2696 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002697
2698 if (persist_data == NULL) {
2699 load_persistent_data();
2700 if (persist_data == NULL) {
2701 SLOGE("Setfield error, cannot load persistent data");
2702 goto out;
2703 }
2704 }
2705
2706 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002707 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002708 encrypted = 1;
2709 }
2710
Rubin Xu85c01f92014-10-13 12:49:54 +01002711 // Compute the number of entries required to store value, each entry can store up to
2712 // (PROPERTY_VALUE_MAX - 1) chars
2713 if (strlen(value) == 0) {
2714 // Empty value also needs one entry to store.
2715 num_entries = 1;
2716 } else {
2717 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2718 }
2719
2720 max_keylen = strlen(fieldname);
2721 if (num_entries > 1) {
2722 // Need an extra "_%d" suffix.
2723 max_keylen += 1 + log10(num_entries);
2724 }
2725 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2726 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002727 goto out;
2728 }
2729
Rubin Xu85c01f92014-10-13 12:49:54 +01002730 // Make sure we have enough space to write the new value
2731 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2732 persist_get_max_entries(encrypted)) {
2733 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2734 goto out;
2735 }
2736
2737 // Now that we know persist_data has enough space for value, let's delete the old field first
2738 // to make up space.
2739 persist_del_keys(fieldname, 0);
2740
2741 if (persist_set_key(fieldname, value, encrypted)) {
2742 // fail to set key, should not happen as we have already checked the available space
2743 SLOGE("persist_set_key() error during setfield()");
2744 goto out;
2745 }
2746
2747 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002748 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002749
2750 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), 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
Ken Sumrall160b4d62013-04-22 12:15:39 -07002757 /* If we are running encrypted, save the persistent data now */
2758 if (encrypted) {
2759 if (save_persistent_data()) {
2760 SLOGE("Setfield error, cannot save persistent data");
2761 goto out;
2762 }
2763 }
2764
Rubin Xu85c01f92014-10-13 12:49:54 +01002765 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002766
2767out:
2768 return rc;
2769}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002770
2771/* Checks userdata. Attempt to mount the volume if default-
2772 * encrypted.
2773 * On success trigger next init phase and return 0.
2774 * Currently do not handle failure - see TODO below.
2775 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002776int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002777 int crypt_type = cryptfs_get_password_type();
2778 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2779 SLOGE("Bad crypt type - error");
2780 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002781 SLOGD(
2782 "Password is not default - "
2783 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002784 property_set("vold.decrypt", "trigger_restart_min_framework");
2785 return 0;
2786 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2787 SLOGD("Password is default - restarting filesystem");
2788 cryptfs_restart_internal(0);
2789 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002790 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002791 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002792 }
2793
Paul Lawrence6bfed202014-07-28 12:47:22 -07002794 /** Corrupt. Allow us to boot into framework, which will detect bad
2795 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002796 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002797 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002798 return 0;
2799}
2800
2801/* Returns type of the password, default, pattern, pin or password.
2802 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002803int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002804 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002805 SLOGE("cryptfs_get_password_type not valid for file encryption");
2806 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002807 }
2808
Paul Lawrencef4faa572014-01-29 13:31:03 -08002809 struct crypt_mnt_ftr crypt_ftr;
2810
2811 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2812 SLOGE("Error getting crypt footer and key\n");
2813 return -1;
2814 }
2815
Paul Lawrence6bfed202014-07-28 12:47:22 -07002816 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2817 return -1;
2818 }
2819
Paul Lawrencef4faa572014-01-29 13:31:03 -08002820 return crypt_ftr.crypt_type;
2821}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002822
Paul Crowley14c8c072018-09-18 13:30:21 -07002823const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002824 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002825 SLOGE("cryptfs_get_password not valid for file encryption");
2826 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002827 }
2828
Paul Lawrence399317e2014-03-10 13:20:50 -07002829 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002830 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002831 if (now.tv_sec < password_expiry_time) {
2832 return password;
2833 } else {
2834 cryptfs_clear_password();
2835 return 0;
2836 }
2837}
2838
Paul Crowley14c8c072018-09-18 13:30:21 -07002839void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002840 if (password) {
2841 size_t len = strlen(password);
2842 memset(password, 0, len);
2843 free(password);
2844 password = 0;
2845 password_expiry_time = 0;
2846 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002847}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002848
Paul Crowley14c8c072018-09-18 13:30:21 -07002849int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002850 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07002851 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07002852}