blob: ce01f1fbf30d8f0559a9e4ce1ea0e57ba68a0cc9 [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>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080039#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080040#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070043#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070045#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070046#include <fscrypt/fscrypt.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080047#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080048#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080049#include <logwrap/logwrap.h>
50#include <openssl/evp.h>
51#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080052#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080053
54#include <ctype.h>
55#include <errno.h>
56#include <fcntl.h>
57#include <inttypes.h>
58#include <libgen.h>
59#include <linux/dm-ioctl.h>
60#include <linux/kdev_t.h>
61#include <math.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <sys/ioctl.h>
66#include <sys/mount.h>
67#include <sys/param.h>
68#include <sys/stat.h>
69#include <sys/types.h>
70#include <sys/wait.h>
71#include <time.h>
72#include <unistd.h>
73
Wei Wang4375f1b2017-02-24 17:43:01 -080074extern "C" {
75#include <crypto_scrypt.h>
76}
Mark Salyzyn3e971272014-01-21 13:27:04 -080077
Greg Kaiserab1e84a2018-12-11 12:40:51 -080078using android::base::StringPrintf;
Paul Crowleycfe39722018-10-30 15:59:24 -070079using namespace std::chrono_literals;
80
Mark Salyzyn5eecc442014-02-12 14:16:14 -080081#define UNUSED __attribute__((unused))
82
Ken Sumrall8f869aa2010-12-03 03:47:09 -080083#define DM_CRYPT_BUF_SIZE 4096
84
Jason parks70a4b3f2011-01-28 10:10:47 -060085#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080086
87constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
88constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070089constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080090
91// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070092static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060093
Paul Crowley14c8c072018-09-18 13:30:21 -070094#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -070095
Paul Lawrence3bd36d52015-06-09 13:37:44 -070096#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080097
Paul Lawrence3d99eba2015-11-20 07:07:19 -080098#define CRYPTO_BLOCK_DEVICE "userdata"
99
100#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
101
Ken Sumrall29d8da82011-05-18 17:20:07 -0700102#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700103#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700104
Ken Sumralle919efe2012-09-29 17:07:41 -0700105#define TABLE_LOAD_RETRIES 10
106
Shawn Willden47ba10d2014-09-03 17:07:06 -0600107#define RSA_KEY_SIZE 2048
108#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
109#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600110#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700111
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700112#define RETRY_MOUNT_ATTEMPTS 10
113#define RETRY_MOUNT_DELAY_SECONDS 1
114
Paul Crowley5afbc622017-11-27 09:42:17 -0800115#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
116
Paul Crowley73473332017-11-21 15:43:51 -0800117static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
118
Greg Kaiser59ad0182018-02-16 13:01:36 -0800119static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700120static char* saved_mount_point;
121static int master_key_saved = 0;
122static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800123
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700124/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700125static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000126 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700127}
128
129/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700130static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800131 if (ftr->keymaster_blob_size) {
132 SLOGI("Already have key");
133 return 0;
134 }
135
Paul Crowley14c8c072018-09-18 13:30:21 -0700136 int rc = keymaster_create_key_for_cryptfs_scrypt(
137 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
138 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000139 if (rc) {
140 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800141 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000142 ftr->keymaster_blob_size = 0;
143 }
144 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700145 return -1;
146 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000147 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700148}
149
Shawn Willdene17a9c42014-09-08 13:04:08 -0600150/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700151static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
152 const size_t object_size, unsigned char** signature,
153 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600154 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600155 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600156 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600157
Shawn Willdene17a9c42014-09-08 13:04:08 -0600158 // To sign a message with RSA, the message must satisfy two
159 // constraints:
160 //
161 // 1. The message, when interpreted as a big-endian numeric value, must
162 // be strictly less than the public modulus of the RSA key. Note
163 // that because the most significant bit of the public modulus is
164 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
165 // key), an n-bit message with most significant bit 0 always
166 // satisfies this requirement.
167 //
168 // 2. The message must have the same length in bits as the public
169 // modulus of the RSA key. This requirement isn't mathematically
170 // necessary, but is necessary to ensure consistency in
171 // implementations.
172 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600173 case KDF_SCRYPT_KEYMASTER:
174 // This ensures the most significant byte of the signed message
175 // is zero. We could have zero-padded to the left instead, but
176 // this approach is slightly more robust against changes in
177 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600178 // so) because we really should be using a proper deterministic
179 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800180 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600181 SLOGI("Signing safely-padded object");
182 break;
183 default:
184 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000185 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600186 }
Paul Crowley73473332017-11-21 15:43:51 -0800187 for (;;) {
188 auto result = keymaster_sign_object_for_cryptfs_scrypt(
189 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
190 to_sign_size, signature, signature_size);
191 switch (result) {
192 case KeymasterSignResult::ok:
193 return 0;
194 case KeymasterSignResult::upgrade:
195 break;
196 default:
197 return -1;
198 }
199 SLOGD("Upgrading key");
200 if (keymaster_upgrade_key_for_cryptfs_scrypt(
201 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
202 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
203 &ftr->keymaster_blob_size) != 0) {
204 SLOGE("Failed to upgrade key");
205 return -1;
206 }
207 if (put_crypt_ftr_and_key(ftr) != 0) {
208 SLOGE("Failed to write upgraded key to disk");
209 }
210 SLOGD("Key upgraded successfully");
211 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600212}
213
Paul Lawrence399317e2014-03-10 13:20:50 -0700214/* Store password when userdata is successfully decrypted and mounted.
215 * Cleared by cryptfs_clear_password
216 *
217 * To avoid a double prompt at boot, we need to store the CryptKeeper
218 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
219 * Since the entire framework is torn down and rebuilt after encryption,
220 * we have to use a daemon or similar to store the password. Since vold
221 * is secured against IPC except from system processes, it seems a reasonable
222 * place to store this.
223 *
224 * password should be cleared once it has been used.
225 *
226 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800227 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700228static char* password = 0;
229static int password_expiry_time = 0;
230static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800231
Paul Crowley14c8c072018-09-18 13:30:21 -0700232enum class RebootType { reboot, recovery, shutdown };
233static void cryptfs_reboot(RebootType rt) {
234 switch (rt) {
235 case RebootType::reboot:
236 property_set(ANDROID_RB_PROPERTY, "reboot");
237 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800238
Paul Crowley14c8c072018-09-18 13:30:21 -0700239 case RebootType::recovery:
240 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
241 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800242
Paul Crowley14c8c072018-09-18 13:30:21 -0700243 case RebootType::shutdown:
244 property_set(ANDROID_RB_PROPERTY, "shutdown");
245 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700246 }
Paul Lawrence87999172014-02-20 12:21:31 -0800247
Ken Sumralladfba362013-06-04 16:37:52 -0700248 sleep(20);
249
250 /* Shouldn't get here, reboot should happen before sleep times out */
251 return;
252}
253
Paul Crowley14c8c072018-09-18 13:30:21 -0700254static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800255 memset(io, 0, dataSize);
256 io->data_size = dataSize;
257 io->data_start = sizeof(struct dm_ioctl);
258 io->version[0] = 4;
259 io->version[1] = 0;
260 io->version[2] = 0;
261 io->flags = flags;
262 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100263 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800264 }
265}
266
Greg Kaiser38723f22018-02-16 13:35:35 -0800267namespace {
268
269struct CryptoType;
270
271// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700272const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800273
274struct CryptoType {
275 // We should only be constructing CryptoTypes as part of
276 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
277 // which isn't pure or fully protected as a concession to being able to
278 // do it all at compile time. Add new CryptoTypes in
279 // supported_crypto_types[] below.
280 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
281 constexpr CryptoType set_keysize(uint32_t size) const {
282 return CryptoType(this->property_name, this->crypto_name, size);
283 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700284 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800285 return CryptoType(property, this->crypto_name, this->keysize);
286 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700287 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800288 return CryptoType(this->property_name, crypto, this->keysize);
289 }
290
Paul Crowley14c8c072018-09-18 13:30:21 -0700291 constexpr const char* get_property_name() const { return property_name; }
292 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800293 constexpr uint32_t get_keysize() const { return keysize; }
294
Paul Crowley14c8c072018-09-18 13:30:21 -0700295 private:
296 const char* property_name;
297 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800298 uint32_t keysize;
299
Paul Crowley14c8c072018-09-18 13:30:21 -0700300 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800301 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700302 friend const CryptoType& get_crypto_type();
303 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800304};
305
306// We only want to parse this read-only property once. But we need to wait
307// until the system is initialized before we can read it. So we use a static
308// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700309const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800310 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
311 return crypto_type;
312}
313
314constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700315 .set_property_name("AES-128-CBC")
316 .set_crypto_name("aes-cbc-essiv:sha256")
317 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800318
319constexpr CryptoType supported_crypto_types[] = {
320 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800321 CryptoType()
322 .set_property_name("adiantum")
323 .set_crypto_name("xchacha12,aes-adiantum-plain64")
324 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800325 // Add new CryptoTypes here. Order is not important.
326};
327
Greg Kaiser38723f22018-02-16 13:35:35 -0800328// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
329// We confirm all supported_crypto_types have a small enough keysize and
330// had both set_property_name() and set_crypto_name() called.
331
332template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700333constexpr size_t array_length(T (&)[N]) {
334 return N;
335}
Greg Kaiser38723f22018-02-16 13:35:35 -0800336
337constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
338 return (index >= array_length(supported_crypto_types));
339}
340
Paul Crowley14c8c072018-09-18 13:30:21 -0700341constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800342 return ((crypto_type.get_property_name() != nullptr) &&
343 (crypto_type.get_crypto_name() != nullptr) &&
344 (crypto_type.get_keysize() <= MAX_KEY_LEN));
345}
346
347// Note in C++11 that constexpr functions can only have a single line.
348// So our code is a bit convoluted (using recursion instead of a loop),
349// but it's asserting at compile time that all of our key lengths are valid.
350constexpr bool validateSupportedCryptoTypes(size_t index) {
351 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700352 (isValidCryptoType(supported_crypto_types[index]) &&
353 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800354}
355
356static_assert(validateSupportedCryptoTypes(0),
357 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
358 "incompletely constructed.");
359// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
360
Greg Kaiser38723f22018-02-16 13:35:35 -0800361// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700362const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800363 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
364 char paramstr[PROPERTY_VALUE_MAX];
365
Paul Crowley14c8c072018-09-18 13:30:21 -0700366 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
367 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800368 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
369 return ctype;
370 }
371 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700372 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
373 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800374 return default_crypto_type;
375}
376
377} // namespace
378
Kenny Rootc4c70f12013-06-14 12:11:38 -0700379/**
380 * Gets the default device scrypt parameters for key derivation time tuning.
381 * The parameters should lead to about one second derivation time for the
382 * given device.
383 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700384static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700385 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000386 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700387
Paul Crowley63c18d32016-02-10 14:02:47 +0000388 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
389 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
390 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
391 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700392 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000393 ftr->N_factor = Nf;
394 ftr->r_factor = rf;
395 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700396}
397
Greg Kaiser57f9af62018-02-16 13:13:58 -0800398uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800399 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800400}
401
Paul Crowley14c8c072018-09-18 13:30:21 -0700402const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800403 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800404}
405
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200406static uint64_t get_fs_size(char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800407 int fd, block_size;
408 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200409 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800410
Paul Crowley14c8c072018-09-18 13:30:21 -0700411 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800412 SLOGE("Cannot open device to get filesystem size ");
413 return 0;
414 }
415
416 if (lseek64(fd, 1024, SEEK_SET) < 0) {
417 SLOGE("Cannot seek to superblock");
418 return 0;
419 }
420
421 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
422 SLOGE("Cannot read superblock");
423 return 0;
424 }
425
426 close(fd);
427
Daniel Rosenberge82df162014-08-15 22:19:23 +0000428 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
429 SLOGE("Not a valid ext4 superblock");
430 return 0;
431 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800432 block_size = 1024 << sb.s_log_block_size;
433 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200434 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800435
436 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200437 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800438}
439
Paul Crowley14c8c072018-09-18 13:30:21 -0700440static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
441 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200442 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700443 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700444 char key_loc[PROPERTY_VALUE_MAX];
445 char real_blkdev[PROPERTY_VALUE_MAX];
446 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700447
Paul Crowley14c8c072018-09-18 13:30:21 -0700448 if (!cached_data) {
449 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700450
Paul Crowley14c8c072018-09-18 13:30:21 -0700451 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200452 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700453 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
454 * encryption info footer and key, and plenty of bytes to spare for future
455 * growth.
456 */
457 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200458 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700459 cached_data = 1;
460 } else {
461 SLOGE("Cannot get size of block device %s\n", real_blkdev);
462 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700463 } else {
464 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
465 cached_off = 0;
466 cached_data = 1;
467 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700468 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700469
Paul Crowley14c8c072018-09-18 13:30:21 -0700470 if (cached_data) {
471 if (metadata_fname) {
472 *metadata_fname = cached_metadata_fname;
473 }
474 if (off) {
475 *off = cached_off;
476 }
477 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700478 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700479
Paul Crowley14c8c072018-09-18 13:30:21 -0700480 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700481}
482
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800483/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700484static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800485 SHA256_CTX c;
486 SHA256_Init(&c);
487 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
488 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
489 SHA256_Final(crypt_ftr->sha256, &c);
490}
491
Ken Sumralle8744072011-01-18 22:01:55 -0800492/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800493 * update the failed mount count but not change the key.
494 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700495static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
496 int fd;
497 unsigned int cnt;
498 /* starting_off is set to the SEEK_SET offset
499 * where the crypto structure starts
500 */
501 off64_t starting_off;
502 int rc = -1;
503 char* fname = NULL;
504 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800505
Paul Crowley14c8c072018-09-18 13:30:21 -0700506 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800507
Paul Crowley14c8c072018-09-18 13:30:21 -0700508 if (get_crypt_ftr_info(&fname, &starting_off)) {
509 SLOGE("Unable to get crypt_ftr_info\n");
510 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800511 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700512 if (fname[0] != '/') {
513 SLOGE("Unexpected value for crypto key location\n");
514 return -1;
515 }
516 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
517 SLOGE("Cannot open footer file %s for put\n", fname);
518 return -1;
519 }
Ken Sumralle8744072011-01-18 22:01:55 -0800520
Paul Crowley14c8c072018-09-18 13:30:21 -0700521 /* Seek to the start of the crypt footer */
522 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
523 SLOGE("Cannot seek to real block device footer\n");
524 goto errout;
525 }
526
527 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
528 SLOGE("Cannot write real block device footer\n");
529 goto errout;
530 }
531
532 fstat(fd, &statbuf);
533 /* If the keys are kept on a raw block device, do not try to truncate it. */
534 if (S_ISREG(statbuf.st_mode)) {
535 if (ftruncate(fd, 0x4000)) {
536 SLOGE("Cannot set footer file size\n");
537 goto errout;
538 }
539 }
540
541 /* Success! */
542 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800543
544errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700545 close(fd);
546 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800547}
548
Paul Crowley14c8c072018-09-18 13:30:21 -0700549static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800550 struct crypt_mnt_ftr copy;
551 memcpy(&copy, crypt_ftr, sizeof(copy));
552 set_ftr_sha(&copy);
553 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
554}
555
Paul Crowley14c8c072018-09-18 13:30:21 -0700556static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700557 return TEMP_FAILURE_RETRY(read(fd, buff, len));
558}
559
Paul Crowley14c8c072018-09-18 13:30:21 -0700560static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700561 return TEMP_FAILURE_RETRY(write(fd, buff, len));
562}
563
Paul Crowley14c8c072018-09-18 13:30:21 -0700564static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700565 memset(pdata, 0, len);
566 pdata->persist_magic = PERSIST_DATA_MAGIC;
567 pdata->persist_valid_entries = 0;
568}
569
570/* A routine to update the passed in crypt_ftr to the lastest version.
571 * fd is open read/write on the device that holds the crypto footer and persistent
572 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
573 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
574 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700575static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700576 int orig_major = crypt_ftr->major_version;
577 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700578
Kenny Root7434b312013-06-14 11:29:53 -0700579 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700580 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700581 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700582
Kenny Rootc4c70f12013-06-14 12:11:38 -0700583 SLOGW("upgrading crypto footer to 1.1");
584
Paul Crowley14c8c072018-09-18 13:30:21 -0700585 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700586 if (pdata == NULL) {
587 SLOGE("Cannot allocate persisent data\n");
588 return;
589 }
590 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
591
592 /* Need to initialize the persistent data area */
593 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
594 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100595 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700596 return;
597 }
598 /* Write all zeros to the first copy, making it invalid */
599 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
600
601 /* Write a valid but empty structure to the second copy */
602 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
603 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
604
605 /* Update the footer */
606 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
607 crypt_ftr->persist_data_offset[0] = pdata_offset;
608 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
609 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100610 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700611 }
612
Paul Lawrencef4faa572014-01-29 13:31:03 -0800613 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700614 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800615 /* But keep the old kdf_type.
616 * It will get updated later to KDF_SCRYPT after the password has been verified.
617 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700618 crypt_ftr->kdf_type = KDF_PBKDF2;
619 get_device_scrypt_params(crypt_ftr);
620 crypt_ftr->minor_version = 2;
621 }
622
Paul Lawrencef4faa572014-01-29 13:31:03 -0800623 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
624 SLOGW("upgrading crypto footer to 1.3");
625 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
626 crypt_ftr->minor_version = 3;
627 }
628
Kenny Root7434b312013-06-14 11:29:53 -0700629 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
630 if (lseek64(fd, offset, SEEK_SET) == -1) {
631 SLOGE("Cannot seek to crypt footer\n");
632 return;
633 }
634 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700635 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700636}
637
Paul Crowley14c8c072018-09-18 13:30:21 -0700638static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
639 int fd;
640 unsigned int cnt;
641 off64_t starting_off;
642 int rc = -1;
643 char* fname = NULL;
644 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700645
Paul Crowley14c8c072018-09-18 13:30:21 -0700646 if (get_crypt_ftr_info(&fname, &starting_off)) {
647 SLOGE("Unable to get crypt_ftr_info\n");
648 return -1;
649 }
650 if (fname[0] != '/') {
651 SLOGE("Unexpected value for crypto key location\n");
652 return -1;
653 }
654 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
655 SLOGE("Cannot open footer file %s for get\n", fname);
656 return -1;
657 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800658
Paul Crowley14c8c072018-09-18 13:30:21 -0700659 /* Make sure it's 16 Kbytes in length */
660 fstat(fd, &statbuf);
661 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
662 SLOGE("footer file %s is not the expected size!\n", fname);
663 goto errout;
664 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700665
Paul Crowley14c8c072018-09-18 13:30:21 -0700666 /* Seek to the start of the crypt footer */
667 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
668 SLOGE("Cannot seek to real block device footer\n");
669 goto errout;
670 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700671
Paul Crowley14c8c072018-09-18 13:30:21 -0700672 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
673 SLOGE("Cannot read real block device footer\n");
674 goto errout;
675 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800676
Paul Crowley14c8c072018-09-18 13:30:21 -0700677 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
678 SLOGE("Bad magic for real block device %s\n", fname);
679 goto errout;
680 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800681
Paul Crowley14c8c072018-09-18 13:30:21 -0700682 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
683 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
684 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
685 goto errout;
686 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800687
Paul Crowley14c8c072018-09-18 13:30:21 -0700688 // We risk buffer overflows with oversized keys, so we just reject them.
689 // 0-sized keys are problematic (essentially by-passing encryption), and
690 // AES-CBC key wrapping only works for multiples of 16 bytes.
691 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
692 (crypt_ftr->keysize > MAX_KEY_LEN)) {
693 SLOGE(
694 "Invalid keysize (%u) for block device %s; Must be non-zero, "
695 "divisible by 16, and <= %d\n",
696 crypt_ftr->keysize, fname, MAX_KEY_LEN);
697 goto errout;
698 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800699
Paul Crowley14c8c072018-09-18 13:30:21 -0700700 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
701 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
702 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
703 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800704
Paul Crowley14c8c072018-09-18 13:30:21 -0700705 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
706 * copy on disk before returning.
707 */
708 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
709 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
710 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800711
Paul Crowley14c8c072018-09-18 13:30:21 -0700712 /* Success! */
713 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800714
715errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700716 close(fd);
717 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800718}
719
Paul Crowley14c8c072018-09-18 13:30:21 -0700720static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700721 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
722 crypt_ftr->persist_data_offset[1]) {
723 SLOGE("Crypt_ftr persist data regions overlap");
724 return -1;
725 }
726
727 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
728 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
729 return -1;
730 }
731
732 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700733 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700734 CRYPT_FOOTER_OFFSET) {
735 SLOGE("Persistent data extends past crypto footer");
736 return -1;
737 }
738
739 return 0;
740}
741
Paul Crowley14c8c072018-09-18 13:30:21 -0700742static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700743 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700744 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700745 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700746 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700747 int found = 0;
748 int fd;
749 int ret;
750 int i;
751
752 if (persist_data) {
753 /* Nothing to do, we've already loaded or initialized it */
754 return 0;
755 }
756
Ken Sumrall160b4d62013-04-22 12:15:39 -0700757 /* If not encrypted, just allocate an empty table and initialize it */
758 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700759 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800760 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700761 if (pdata) {
762 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
763 persist_data = pdata;
764 return 0;
765 }
766 return -1;
767 }
768
Paul Crowley14c8c072018-09-18 13:30:21 -0700769 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700770 return -1;
771 }
772
Paul Crowley14c8c072018-09-18 13:30:21 -0700773 if ((crypt_ftr.major_version < 1) ||
774 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700775 SLOGE("Crypt_ftr version doesn't support persistent data");
776 return -1;
777 }
778
779 if (get_crypt_ftr_info(&fname, NULL)) {
780 return -1;
781 }
782
783 ret = validate_persistent_data_storage(&crypt_ftr);
784 if (ret) {
785 return -1;
786 }
787
Paul Crowley14c8c072018-09-18 13:30:21 -0700788 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700789 if (fd < 0) {
790 SLOGE("Cannot open %s metadata file", fname);
791 return -1;
792 }
793
Wei Wang4375f1b2017-02-24 17:43:01 -0800794 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800795 if (pdata == NULL) {
796 SLOGE("Cannot allocate memory for persistent data");
797 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700798 }
799
800 for (i = 0; i < 2; i++) {
801 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
802 SLOGE("Cannot seek to read persistent data on %s", fname);
803 goto err2;
804 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700805 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700806 SLOGE("Error reading persistent data on iteration %d", i);
807 goto err2;
808 }
809 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
810 found = 1;
811 break;
812 }
813 }
814
815 if (!found) {
816 SLOGI("Could not find valid persistent data, creating");
817 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
818 }
819
820 /* Success */
821 persist_data = pdata;
822 close(fd);
823 return 0;
824
825err2:
826 free(pdata);
827
828err:
829 close(fd);
830 return -1;
831}
832
Paul Crowley14c8c072018-09-18 13:30:21 -0700833static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700834 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700835 struct crypt_persist_data* pdata;
836 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700837 off64_t write_offset;
838 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700839 int fd;
840 int ret;
841
842 if (persist_data == NULL) {
843 SLOGE("No persistent data to save");
844 return -1;
845 }
846
Paul Crowley14c8c072018-09-18 13:30:21 -0700847 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700848 return -1;
849 }
850
Paul Crowley14c8c072018-09-18 13:30:21 -0700851 if ((crypt_ftr.major_version < 1) ||
852 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700853 SLOGE("Crypt_ftr version doesn't support persistent data");
854 return -1;
855 }
856
857 ret = validate_persistent_data_storage(&crypt_ftr);
858 if (ret) {
859 return -1;
860 }
861
862 if (get_crypt_ftr_info(&fname, NULL)) {
863 return -1;
864 }
865
Paul Crowley14c8c072018-09-18 13:30:21 -0700866 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700867 if (fd < 0) {
868 SLOGE("Cannot open %s metadata file", fname);
869 return -1;
870 }
871
Wei Wang4375f1b2017-02-24 17:43:01 -0800872 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700873 if (pdata == NULL) {
874 SLOGE("Cannot allocate persistant data");
875 goto err;
876 }
877
878 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
879 SLOGE("Cannot seek to read persistent data on %s", fname);
880 goto err2;
881 }
882
883 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700884 SLOGE("Error reading persistent data before save");
885 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700886 }
887
888 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
889 /* The first copy is the curent valid copy, so write to
890 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700891 write_offset = crypt_ftr.persist_data_offset[1];
892 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700893 } else {
894 /* The second copy must be the valid copy, so write to
895 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700896 write_offset = crypt_ftr.persist_data_offset[0];
897 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700898 }
899
900 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100901 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700902 SLOGE("Cannot seek to write persistent data");
903 goto err2;
904 }
905 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700906 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100907 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700908 SLOGE("Cannot seek to erase previous persistent data");
909 goto err2;
910 }
911 fsync(fd);
912 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -0700913 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700914 SLOGE("Cannot write to erase previous persistent data");
915 goto err2;
916 }
917 fsync(fd);
918 } else {
919 SLOGE("Cannot write to save persistent data");
920 goto err2;
921 }
922
923 /* Success */
924 free(pdata);
925 close(fd);
926 return 0;
927
928err2:
929 free(pdata);
930err:
931 close(fd);
932 return -1;
933}
934
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800935/* Convert a binary key of specified length into an ascii hex string equivalent,
936 * without the leading 0x and with null termination
937 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700938static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
939 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700940 unsigned int i, a;
941 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800942
Paul Crowley14c8c072018-09-18 13:30:21 -0700943 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700944 /* For each byte, write out two ascii hex digits */
945 nibble = (master_key[i] >> 4) & 0xf;
946 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800947
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700948 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -0700949 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700950 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800951
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700952 /* Add the null termination */
953 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800954}
955
Paul Crowley14c8c072018-09-18 13:30:21 -0700956static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
957 const unsigned char* master_key, const char* real_blk_name,
958 const char* name, int fd, const char* extra_params) {
959 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
960 struct dm_ioctl* io;
961 struct dm_target_spec* tgt;
962 char* crypt_params;
963 // We need two ASCII characters to represent each byte, and need space for
964 // the '\0' terminator.
965 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
966 size_t buff_offset;
967 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800968
Paul Crowley14c8c072018-09-18 13:30:21 -0700969 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800970
Paul Crowley14c8c072018-09-18 13:30:21 -0700971 /* Load the mapping table for this device */
972 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800973
Paul Crowley14c8c072018-09-18 13:30:21 -0700974 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
975 io->target_count = 1;
976 tgt->status = 0;
977 tgt->sector_start = 0;
978 tgt->length = crypt_ftr->fs_size;
979 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800980
Paul Crowley14c8c072018-09-18 13:30:21 -0700981 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
982 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800983
Paul Crowley14c8c072018-09-18 13:30:21 -0700984 buff_offset = crypt_params - buffer;
985 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
986 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
987 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
988 crypt_params += strlen(crypt_params) + 1;
989 crypt_params =
990 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
991 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800992
Paul Crowley14c8c072018-09-18 13:30:21 -0700993 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
994 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
995 break;
996 }
997 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800998 }
Ken Sumralldb5e0262013-02-05 17:39:48 -0800999
Paul Crowley14c8c072018-09-18 13:30:21 -07001000 if (i == TABLE_LOAD_RETRIES) {
1001 /* We failed to load the table, return an error */
1002 return -1;
1003 } else {
1004 return i + 1;
1005 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001006}
1007
Paul Crowley14c8c072018-09-18 13:30:21 -07001008static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001009 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001010 struct dm_ioctl* io;
1011 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001012
Paul Crowley14c8c072018-09-18 13:30:21 -07001013 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001014
1015 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1016
1017 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1018 return -1;
1019 }
1020
1021 /* Iterate over the returned versions, looking for name of "crypt".
1022 * When found, get and return the version.
1023 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001024 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001025 while (v->next) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001026 if (!strcmp(v->name, "crypt")) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001027 /* We found the crypt driver, return the version, and get out */
1028 version[0] = v->version[0];
1029 version[1] = v->version[1];
1030 version[2] = v->version[2];
1031 return 0;
1032 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001033 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001034 }
1035
1036 return -1;
1037}
1038
Paul Crowley5afbc622017-11-27 09:42:17 -08001039static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1040 if (extra_params_vec.empty()) return "";
1041 std::string extra_params = std::to_string(extra_params_vec.size());
1042 for (const auto& p : extra_params_vec) {
1043 extra_params.append(" ");
1044 extra_params.append(p);
1045 }
1046 return extra_params;
1047}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001048
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001049// Only adds parameters if the property is set.
1050static void add_sector_size_param(std::vector<std::string>* extra_params_vec) {
1051 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
1052 char sector_size[PROPERTY_VALUE_MAX];
1053
1054 if (property_get(DM_CRYPT_SECTOR_SIZE, sector_size, "") > 0) {
1055 std::string param = StringPrintf("sector_size:%s", sector_size);
1056 extra_params_vec->push_back(std::move(param));
1057
1058 // With this option, IVs will match the sector numbering, instead
1059 // of being hard-coded to being based on 512-byte sectors.
1060 extra_params_vec->emplace_back("iv_large_sectors");
1061 }
1062}
1063
Paul Crowley5afbc622017-11-27 09:42:17 -08001064static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1065 const char* real_blk_name, char* crypto_blk_name, const char* name,
1066 uint32_t flags) {
1067 char buffer[DM_CRYPT_BUF_SIZE];
1068 struct dm_ioctl* io;
1069 unsigned int minor;
1070 int fd = 0;
1071 int err;
1072 int retval = -1;
1073 int version[3];
1074 int load_count;
1075 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001076
Paul Crowley5afbc622017-11-27 09:42:17 -08001077 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1078 SLOGE("Cannot open device-mapper\n");
1079 goto errout;
1080 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001081
Paul Crowley5afbc622017-11-27 09:42:17 -08001082 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001083
Paul Crowley5afbc622017-11-27 09:42:17 -08001084 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1085 err = ioctl(fd, DM_DEV_CREATE, io);
1086 if (err) {
1087 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1088 goto errout;
1089 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001090
Paul Crowley5afbc622017-11-27 09:42:17 -08001091 /* Get the device status, in particular, the name of it's device file */
1092 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1093 if (ioctl(fd, DM_DEV_STATUS, io)) {
1094 SLOGE("Cannot retrieve dm-crypt device status\n");
1095 goto errout;
1096 }
1097 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1098 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001099
Paul Crowley5afbc622017-11-27 09:42:17 -08001100 if (!get_dm_crypt_version(fd, name, version)) {
1101 /* Support for allow_discards was added in version 1.11.0 */
1102 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1103 extra_params_vec.emplace_back("allow_discards");
1104 }
1105 }
1106 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1107 extra_params_vec.emplace_back("allow_encrypt_override");
1108 }
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001109 add_sector_size_param(&extra_params_vec);
Paul Crowley5afbc622017-11-27 09:42:17 -08001110 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1111 extra_params_as_string(extra_params_vec).c_str());
1112 if (load_count < 0) {
1113 SLOGE("Cannot load dm-crypt mapping table.\n");
1114 goto errout;
1115 } else if (load_count > 1) {
1116 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1117 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001118
Paul Crowley5afbc622017-11-27 09:42:17 -08001119 /* Resume this device to activate it */
1120 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121
Paul Crowley5afbc622017-11-27 09:42:17 -08001122 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1123 SLOGE("Cannot resume the dm-crypt device\n");
1124 goto errout;
1125 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126
Paul Crowleycfe39722018-10-30 15:59:24 -07001127 /* Ensure the dm device has been created before returning. */
1128 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1129 // WaitForFile generates a suitable log message
1130 goto errout;
1131 }
1132
Paul Crowley5afbc622017-11-27 09:42:17 -08001133 /* We made it here with no errors. Woot! */
1134 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001135
1136errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001137 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 -08001138
Paul Crowley14c8c072018-09-18 13:30:21 -07001139 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001140}
1141
Paul Crowley14c8c072018-09-18 13:30:21 -07001142static int delete_crypto_blk_dev(const char* name) {
1143 int fd;
1144 char buffer[DM_CRYPT_BUF_SIZE];
1145 struct dm_ioctl* io;
1146 int retval = -1;
Yue Hu9d6cc182018-12-17 17:09:55 +08001147 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001148
Paul Crowley14c8c072018-09-18 13:30:21 -07001149 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1150 SLOGE("Cannot open device-mapper\n");
1151 goto errout;
1152 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001153
Paul Crowley14c8c072018-09-18 13:30:21 -07001154 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001155
Paul Crowley14c8c072018-09-18 13:30:21 -07001156 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Yue Hu9d6cc182018-12-17 17:09:55 +08001157 err = ioctl(fd, DM_DEV_REMOVE, io);
1158 if (err) {
1159 SLOGE("Cannot remove dm-crypt device %s: %s\n", name, strerror(errno));
Paul Crowley14c8c072018-09-18 13:30:21 -07001160 goto errout;
1161 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001162
Paul Crowley14c8c072018-09-18 13:30:21 -07001163 /* We made it here with no errors. Woot! */
1164 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165
1166errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001167 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 -08001168
Paul Crowley14c8c072018-09-18 13:30:21 -07001169 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001170}
1171
Paul Crowley14c8c072018-09-18 13:30:21 -07001172static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1173 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001174 SLOGI("Using pbkdf2 for cryptfs KDF");
1175
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001176 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001177 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1178 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001179}
1180
Paul Crowley14c8c072018-09-18 13:30:21 -07001181static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001182 SLOGI("Using scrypt for cryptfs KDF");
1183
Paul Crowley14c8c072018-09-18 13:30:21 -07001184 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001185
1186 int N = 1 << ftr->N_factor;
1187 int r = 1 << ftr->r_factor;
1188 int p = 1 << ftr->p_factor;
1189
1190 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001191 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001192 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001193
Paul Crowley14c8c072018-09-18 13:30:21 -07001194 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001195}
1196
Paul Crowley14c8c072018-09-18 13:30:21 -07001197static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1198 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001199 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1200
1201 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001202 size_t signature_size;
1203 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001204 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001205
1206 int N = 1 << ftr->N_factor;
1207 int r = 1 << ftr->r_factor;
1208 int p = 1 << ftr->p_factor;
1209
Paul Crowley14c8c072018-09-18 13:30:21 -07001210 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001211 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001212
1213 if (rc) {
1214 SLOGE("scrypt failed");
1215 return -1;
1216 }
1217
Paul Crowley14c8c072018-09-18 13:30:21 -07001218 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001219 SLOGE("Signing failed");
1220 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001221 }
1222
Paul Crowley14c8c072018-09-18 13:30:21 -07001223 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1224 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001225 free(signature);
1226
1227 if (rc) {
1228 SLOGE("scrypt failed");
1229 return -1;
1230 }
1231
1232 return 0;
1233}
1234
Paul Crowley14c8c072018-09-18 13:30:21 -07001235static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1236 const unsigned char* decrypted_master_key,
1237 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1238 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001239 EVP_CIPHER_CTX e_ctx;
1240 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001241 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001242
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001243 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001244 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001245
1246 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001247 case KDF_SCRYPT_KEYMASTER:
1248 if (keymaster_create_key(crypt_ftr)) {
1249 SLOGE("keymaster_create_key failed");
1250 return -1;
1251 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001252
Paul Crowley14c8c072018-09-18 13:30:21 -07001253 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1254 SLOGE("scrypt failed");
1255 return -1;
1256 }
1257 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001258
Paul Crowley14c8c072018-09-18 13:30:21 -07001259 case KDF_SCRYPT:
1260 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1261 SLOGE("scrypt failed");
1262 return -1;
1263 }
1264 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001265
Paul Crowley14c8c072018-09-18 13:30:21 -07001266 default:
1267 SLOGE("Invalid kdf_type");
1268 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001269 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001270
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001271 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001272 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001273 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1274 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001275 SLOGE("EVP_EncryptInit failed\n");
1276 return -1;
1277 }
1278 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001279
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001280 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001281 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1282 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001283 SLOGE("EVP_EncryptUpdate failed\n");
1284 return -1;
1285 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001286 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001287 SLOGE("EVP_EncryptFinal failed\n");
1288 return -1;
1289 }
1290
Greg Kaiser59ad0182018-02-16 13:01:36 -08001291 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001292 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1293 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001295
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001296 /* Store the scrypt of the intermediate key, so we can validate if it's a
1297 password error or mount error when things go wrong.
1298 Note there's no need to check for errors, since if this is incorrect, we
1299 simply won't wipe userdata, which is the correct default behavior
1300 */
1301 int N = 1 << crypt_ftr->N_factor;
1302 int r = 1 << crypt_ftr->r_factor;
1303 int p = 1 << crypt_ftr->p_factor;
1304
Paul Crowley14c8c072018-09-18 13:30:21 -07001305 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1306 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001307 sizeof(crypt_ftr->scrypted_intermediate_key));
1308
1309 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001310 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001311 }
1312
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001313 EVP_CIPHER_CTX_cleanup(&e_ctx);
1314
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001315 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001316}
1317
Paul Crowley14c8c072018-09-18 13:30:21 -07001318static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1319 const unsigned char* encrypted_master_key, size_t keysize,
1320 unsigned char* decrypted_master_key, kdf_func kdf,
1321 void* kdf_params, unsigned char** intermediate_key,
1322 size_t* intermediate_key_size) {
1323 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1324 EVP_CIPHER_CTX d_ctx;
1325 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001326
Paul Crowley14c8c072018-09-18 13:30:21 -07001327 /* Turn the password into an intermediate key and IV that can decrypt the
1328 master key */
1329 if (kdf(passwd, salt, ikey, kdf_params)) {
1330 SLOGE("kdf failed");
1331 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001332 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001333
Paul Crowley14c8c072018-09-18 13:30:21 -07001334 /* Initialize the decryption engine */
1335 EVP_CIPHER_CTX_init(&d_ctx);
1336 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1337 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1338 return -1;
1339 }
1340 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1341 /* Decrypt the master key */
1342 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1343 keysize)) {
1344 return -1;
1345 }
1346 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1347 return -1;
1348 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001349
Paul Crowley14c8c072018-09-18 13:30:21 -07001350 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1351 return -1;
1352 }
1353
1354 /* Copy intermediate key if needed by params */
1355 if (intermediate_key && intermediate_key_size) {
1356 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1357 if (*intermediate_key) {
1358 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1359 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1360 }
1361 }
1362
1363 EVP_CIPHER_CTX_cleanup(&d_ctx);
1364
1365 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001366}
1367
Paul Crowley14c8c072018-09-18 13:30:21 -07001368static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001369 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001370 *kdf = scrypt_keymaster;
1371 *kdf_params = ftr;
1372 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001373 *kdf = scrypt;
1374 *kdf_params = ftr;
1375 } else {
1376 *kdf = pbkdf2;
1377 *kdf_params = NULL;
1378 }
1379}
1380
Paul Crowley14c8c072018-09-18 13:30:21 -07001381static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1382 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1383 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001384 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001385 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001386 int ret;
1387
1388 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001389 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1390 decrypted_master_key, kdf, kdf_params, intermediate_key,
1391 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001392 if (ret != 0) {
1393 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001394 }
1395
1396 return ret;
1397}
1398
Paul Crowley14c8c072018-09-18 13:30:21 -07001399static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1400 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001401 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001402
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001403 /* Get some random bits for a key and salt */
1404 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1405 return -1;
1406 }
1407 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1408 return -1;
1409 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001410
1411 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001412 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001413}
1414
Paul Crowley14c8c072018-09-18 13:30:21 -07001415int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001416 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001417#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001418
1419 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001420 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001421 if (umount(mountpoint) == 0) {
1422 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001423 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001424
1425 if (errno == EINVAL) {
1426 /* EINVAL is returned if the directory is not a mountpoint,
1427 * i.e. there is no filesystem mounted there. So just get out.
1428 */
1429 break;
1430 }
1431
1432 err = errno;
1433
1434 /* If allowed, be increasingly aggressive before the last two retries */
1435 if (kill) {
1436 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1437 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001438 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001439 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1440 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001441 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001442 }
1443 }
1444
1445 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001446 }
1447
1448 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001449 SLOGD("unmounting %s succeeded\n", mountpoint);
1450 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001451 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001452 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1453 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1454 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001455 }
1456
1457 return rc;
1458}
1459
Paul Crowley14c8c072018-09-18 13:30:21 -07001460static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001461 // NOTE: post_fs_data results in init calling back around to vold, so all
1462 // callers to this method must be async
1463
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001464 /* Do the prep of the /data filesystem */
1465 property_set("vold.post_fs_data_done", "0");
1466 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001467 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001468
Ken Sumrallc5872692013-05-14 15:26:31 -07001469 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001470 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001471 /* We timed out to prep /data in time. Continue wait. */
1472 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001473 }
Wei Wang42e38102017-06-07 10:46:12 -07001474 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001475}
1476
Paul Crowley14c8c072018-09-18 13:30:21 -07001477static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001478 // Mark the footer as bad
1479 struct crypt_mnt_ftr crypt_ftr;
1480 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1481 SLOGE("Failed to get crypto footer - panic");
1482 return;
1483 }
1484
1485 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1486 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1487 SLOGE("Failed to set crypto footer - panic");
1488 return;
1489 }
1490}
1491
Paul Crowley14c8c072018-09-18 13:30:21 -07001492static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001493 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001494 SLOGE("Failed to mount tmpfs on data - panic");
1495 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001496 }
1497
1498 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1499 SLOGE("Failed to trigger post fs data - panic");
1500 return;
1501 }
1502
1503 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1504 SLOGE("Failed to trigger restart min framework - panic");
1505 return;
1506 }
1507}
1508
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001509/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001510static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001511 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001512 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001513 static int restart_successful = 0;
1514
1515 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001516 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001517 SLOGE("Encrypted filesystem not validated, aborting");
1518 return -1;
1519 }
1520
1521 if (restart_successful) {
1522 SLOGE("System already restarted with encrypted disk, aborting");
1523 return -1;
1524 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001525
Paul Lawrencef4faa572014-01-29 13:31:03 -08001526 if (restart_main) {
1527 /* Here is where we shut down the framework. The init scripts
1528 * start all services in one of three classes: core, main or late_start.
1529 * On boot, we start core and main. Now, we stop main, but not core,
1530 * as core includes vold and a few other really important things that
1531 * we need to keep running. Once main has stopped, we should be able
1532 * to umount the tmpfs /data, then mount the encrypted /data.
1533 * We then restart the class main, and also the class late_start.
1534 * At the moment, I've only put a few things in late_start that I know
1535 * are not needed to bring up the framework, and that also cause problems
1536 * with unmounting the tmpfs /data, but I hope to add add more services
1537 * to the late_start class as we optimize this to decrease the delay
1538 * till the user is asked for the password to the filesystem.
1539 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001540
Paul Lawrencef4faa572014-01-29 13:31:03 -08001541 /* The init files are setup to stop the class main when vold.decrypt is
1542 * set to trigger_reset_main.
1543 */
1544 property_set("vold.decrypt", "trigger_reset_main");
1545 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001546
Paul Lawrencef4faa572014-01-29 13:31:03 -08001547 /* Ugh, shutting down the framework is not synchronous, so until it
1548 * can be fixed, this horrible hack will wait a moment for it all to
1549 * shut down before proceeding. Without it, some devices cannot
1550 * restart the graphics services.
1551 */
1552 sleep(2);
1553 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001554
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001555 /* Now that the framework is shutdown, we should be able to umount()
1556 * the tmpfs filesystem, and mount the real one.
1557 */
1558
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001559 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1560 if (strlen(crypto_blkdev) == 0) {
1561 SLOGE("fs_crypto_blkdev not set\n");
1562 return -1;
1563 }
1564
Paul Crowley14c8c072018-09-18 13:30:21 -07001565 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001566 /* If ro.crypto.readonly is set to 1, mount the decrypted
1567 * filesystem readonly. This is used when /data is mounted by
1568 * recovery mode.
1569 */
1570 char ro_prop[PROPERTY_VALUE_MAX];
1571 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001572 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001573 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001574 if (rec) {
1575 rec->flags |= MS_RDONLY;
1576 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001577 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001578
Ken Sumralle5032c42012-04-01 23:58:44 -07001579 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001580 int retries = RETRY_MOUNT_ATTEMPTS;
1581 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001582
1583 /*
1584 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1585 * partitions in the fsck domain.
1586 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001587 if (setexeccon(secontextFsck())) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001588 SLOGE("Failed to setexeccon");
1589 return -1;
1590 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001591 bool needs_cp = android::vold::cp_needsCheckpoint();
1592 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1593 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001594 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1595 /* TODO: invoke something similar to
1596 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1597 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001598 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001599 if (--retries) {
1600 sleep(RETRY_MOUNT_DELAY_SECONDS);
1601 } else {
1602 /* Let's hope that a reboot clears away whatever is keeping
1603 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001604 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001605 }
1606 } else {
1607 SLOGE("Failed to mount decrypted data");
1608 cryptfs_set_corrupt();
1609 cryptfs_trigger_restart_min_framework();
1610 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001611 if (setexeccon(NULL)) {
1612 SLOGE("Failed to setexeccon");
1613 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001614 return -1;
1615 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001616 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001617 if (setexeccon(NULL)) {
1618 SLOGE("Failed to setexeccon");
1619 return -1;
1620 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001621
Ken Sumralle5032c42012-04-01 23:58:44 -07001622 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001623 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001624 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001625
1626 /* startup service classes main and late_start */
1627 property_set("vold.decrypt", "trigger_restart_framework");
1628 SLOGD("Just triggered restart_framework\n");
1629
1630 /* Give it a few moments to get started */
1631 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001632 }
1633
Ken Sumrall0cc16632011-01-18 20:32:26 -08001634 if (rc == 0) {
1635 restart_successful = 1;
1636 }
1637
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001638 return rc;
1639}
1640
Paul Crowley14c8c072018-09-18 13:30:21 -07001641int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001642 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001643 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001644 SLOGE("cryptfs_restart not valid for file encryption:");
1645 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001646 }
1647
Paul Lawrencef4faa572014-01-29 13:31:03 -08001648 /* Call internal implementation forcing a restart of main service group */
1649 return cryptfs_restart_internal(1);
1650}
1651
Paul Crowley14c8c072018-09-18 13:30:21 -07001652static int do_crypto_complete(const char* mount_point) {
1653 struct crypt_mnt_ftr crypt_ftr;
1654 char encrypted_state[PROPERTY_VALUE_MAX];
1655 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001656
Paul Crowley14c8c072018-09-18 13:30:21 -07001657 property_get("ro.crypto.state", encrypted_state, "");
1658 if (strcmp(encrypted_state, "encrypted")) {
1659 SLOGE("not running with encryption, aborting");
1660 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001661 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001662
Paul Crowley14c8c072018-09-18 13:30:21 -07001663 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001664 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001665 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1666 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001667
Paul Crowley14c8c072018-09-18 13:30:21 -07001668 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1669 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Paul Lawrence74f29f12014-08-28 15:54:10 -07001670
Paul Crowley14c8c072018-09-18 13:30:21 -07001671 /*
1672 * Only report this error if key_loc is a file and it exists.
1673 * If the device was never encrypted, and /data is not mountable for
1674 * some reason, returning 1 should prevent the UI from presenting the
1675 * a "enter password" screen, or worse, a "press button to wipe the
1676 * device" screen.
1677 */
1678 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1679 SLOGE("master key file does not exist, aborting");
1680 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1681 } else {
1682 SLOGE("Error getting crypt footer and key\n");
1683 return CRYPTO_COMPLETE_BAD_METADATA;
1684 }
1685 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001686
Paul Crowley14c8c072018-09-18 13:30:21 -07001687 // Test for possible error flags
1688 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1689 SLOGE("Encryption process is partway completed\n");
1690 return CRYPTO_COMPLETE_PARTIAL;
1691 }
1692
1693 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1694 SLOGE("Encryption process was interrupted but cannot continue\n");
1695 return CRYPTO_COMPLETE_INCONSISTENT;
1696 }
1697
1698 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1699 SLOGE("Encryption is successful but data is corrupt\n");
1700 return CRYPTO_COMPLETE_CORRUPT;
1701 }
1702
1703 /* We passed the test! We shall diminish, and return to the west */
1704 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001705}
1706
Paul Crowley14c8c072018-09-18 13:30:21 -07001707static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1708 const char* mount_point, const char* label) {
1709 unsigned char decrypted_master_key[MAX_KEY_LEN];
1710 char crypto_blkdev[MAXPATHLEN];
1711 char real_blkdev[MAXPATHLEN];
1712 char tmp_mount_point[64];
1713 unsigned int orig_failed_decrypt_count;
1714 int rc;
1715 int use_keymaster = 0;
1716 int upgrade = 0;
1717 unsigned char* intermediate_key = 0;
1718 size_t intermediate_key_size = 0;
1719 int N = 1 << crypt_ftr->N_factor;
1720 int r = 1 << crypt_ftr->r_factor;
1721 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001722
Paul Crowley14c8c072018-09-18 13:30:21 -07001723 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1724 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001725
Paul Crowley14c8c072018-09-18 13:30:21 -07001726 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1727 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1728 &intermediate_key_size)) {
1729 SLOGE("Failed to decrypt master key\n");
1730 rc = -1;
1731 goto errout;
1732 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001733 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001734
Paul Crowley14c8c072018-09-18 13:30:21 -07001735 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001736
Paul Crowley14c8c072018-09-18 13:30:21 -07001737 // Create crypto block device - all (non fatal) code paths
1738 // need it
1739 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
1740 0)) {
1741 SLOGE("Error creating decrypted block device\n");
1742 rc = -1;
1743 goto errout;
1744 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001745
Paul Crowley14c8c072018-09-18 13:30:21 -07001746 /* Work out if the problem is the password or the data */
1747 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001748
Paul Crowley14c8c072018-09-18 13:30:21 -07001749 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1750 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1751 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001752
Paul Crowley14c8c072018-09-18 13:30:21 -07001753 // Does the key match the crypto footer?
1754 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1755 sizeof(scrypted_intermediate_key)) == 0) {
1756 SLOGI("Password matches");
1757 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001758 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001759 /* Try mounting the file system anyway, just in case the problem's with
1760 * the footer, not the key. */
1761 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1762 mkdir(tmp_mount_point, 0755);
1763 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1764 SLOGE("Error temp mounting decrypted block device\n");
1765 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001766
Paul Crowley14c8c072018-09-18 13:30:21 -07001767 rc = ++crypt_ftr->failed_decrypt_count;
1768 put_crypt_ftr_and_key(crypt_ftr);
1769 } else {
1770 /* Success! */
1771 SLOGI("Password did not match but decrypted drive mounted - continue");
1772 umount(tmp_mount_point);
1773 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001774 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001775 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001776
Paul Crowley14c8c072018-09-18 13:30:21 -07001777 if (rc == 0) {
1778 crypt_ftr->failed_decrypt_count = 0;
1779 if (orig_failed_decrypt_count != 0) {
1780 put_crypt_ftr_and_key(crypt_ftr);
1781 }
1782
1783 /* Save the name of the crypto block device
1784 * so we can mount it when restarting the framework. */
1785 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1786
1787 /* Also save a the master key so we can reencrypted the key
1788 * the key when we want to change the password on it. */
1789 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1790 saved_mount_point = strdup(mount_point);
1791 master_key_saved = 1;
1792 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1793 rc = 0;
1794
1795 // Upgrade if we're not using the latest KDF.
1796 use_keymaster = keymaster_check_compatibility();
1797 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1798 // Don't allow downgrade
1799 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1800 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1801 upgrade = 1;
1802 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1803 crypt_ftr->kdf_type = KDF_SCRYPT;
1804 upgrade = 1;
1805 }
1806
1807 if (upgrade) {
1808 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1809 crypt_ftr->master_key, crypt_ftr);
1810 if (!rc) {
1811 rc = put_crypt_ftr_and_key(crypt_ftr);
1812 }
1813 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1814
1815 // Do not fail even if upgrade failed - machine is bootable
1816 // Note that if this code is ever hit, there is a *serious* problem
1817 // since KDFs should never fail. You *must* fix the kdf before
1818 // proceeding!
1819 if (rc) {
1820 SLOGW(
1821 "Upgrade failed with error %d,"
1822 " but continuing with previous state",
1823 rc);
1824 rc = 0;
1825 }
1826 }
1827 }
1828
1829errout:
1830 if (intermediate_key) {
1831 memset(intermediate_key, 0, intermediate_key_size);
1832 free(intermediate_key);
1833 }
1834 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001835}
1836
Ken Sumrall29d8da82011-05-18 17:20:07 -07001837/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001838 * Called by vold when it's asked to mount an encrypted external
1839 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001840 * as any metadata is been stored in a separate, small partition. We
1841 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001842 *
1843 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001844 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001845int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1846 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001847 uint64_t nr_sec = 0;
1848 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001849 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001850 return -1;
1851 }
1852
Jeff Sharkey9c484982015-03-31 10:35:33 -07001853 struct crypt_mnt_ftr ext_crypt_ftr;
1854 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1855 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001856 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001857 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001858 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001859 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001860 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001861 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1862 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001863
Paul Crowley385cb8c2018-03-29 13:27:23 -07001864 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001865}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001866
Jeff Sharkey9c484982015-03-31 10:35:33 -07001867/*
1868 * Called by vold when it's asked to unmount an encrypted external
1869 * storage volume.
1870 */
1871int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001872 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001873}
1874
Paul Crowley14c8c072018-09-18 13:30:21 -07001875int cryptfs_crypto_complete(void) {
1876 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001877}
1878
Paul Crowley14c8c072018-09-18 13:30:21 -07001879int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001880 char encrypted_state[PROPERTY_VALUE_MAX];
1881 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001882 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1883 SLOGE(
1884 "encrypted fs already validated or not running with encryption,"
1885 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001886 return -1;
1887 }
1888
1889 if (get_crypt_ftr_and_key(crypt_ftr)) {
1890 SLOGE("Error getting crypt footer and key");
1891 return -1;
1892 }
1893
1894 return 0;
1895}
1896
Paul Crowley14c8c072018-09-18 13:30:21 -07001897int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001898 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001899 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001900 SLOGE("cryptfs_check_passwd not valid for file encryption");
1901 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001902 }
1903
Paul Lawrencef4faa572014-01-29 13:31:03 -08001904 struct crypt_mnt_ftr crypt_ftr;
1905 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001906
Paul Lawrencef4faa572014-01-29 13:31:03 -08001907 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001908 if (rc) {
1909 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001910 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001911 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001912
Paul Crowley14c8c072018-09-18 13:30:21 -07001913 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001914 if (rc) {
1915 SLOGE("Password did not match");
1916 return rc;
1917 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001918
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001919 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1920 // Here we have a default actual password but a real password
1921 // we must test against the scrypted value
1922 // First, we must delete the crypto block device that
1923 // test_mount_encrypted_fs leaves behind as a side effect
1924 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001925 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1926 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001927 if (rc) {
1928 SLOGE("Default password did not match on reboot encryption");
1929 return rc;
1930 }
1931
1932 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1933 put_crypt_ftr_and_key(&crypt_ftr);
1934 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1935 if (rc) {
1936 SLOGE("Could not change password on reboot encryption");
1937 return rc;
1938 }
1939 }
1940
1941 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001942 cryptfs_clear_password();
1943 password = strdup(passwd);
1944 struct timespec now;
1945 clock_gettime(CLOCK_BOOTTIME, &now);
1946 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001947 }
1948
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001949 return rc;
1950}
1951
Paul Crowley14c8c072018-09-18 13:30:21 -07001952int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001953 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001954 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001955 char encrypted_state[PROPERTY_VALUE_MAX];
1956 int rc;
1957
1958 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001959 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001960 SLOGE("device not encrypted, aborting");
1961 return -2;
1962 }
1963
1964 if (!master_key_saved) {
1965 SLOGE("encrypted fs not yet mounted, aborting");
1966 return -1;
1967 }
1968
1969 if (!saved_mount_point) {
1970 SLOGE("encrypted fs failed to save mount point, aborting");
1971 return -1;
1972 }
1973
Ken Sumrall160b4d62013-04-22 12:15:39 -07001974 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001975 SLOGE("Error getting crypt footer and key\n");
1976 return -1;
1977 }
1978
1979 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1980 /* If the device has no password, then just say the password is valid */
1981 rc = 0;
1982 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001983 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001984 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1985 /* They match, the password is correct */
1986 rc = 0;
1987 } else {
1988 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1989 sleep(1);
1990 rc = 1;
1991 }
1992 }
1993
1994 return rc;
1995}
1996
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001997/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08001998 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001999 * Presumably, at a minimum, the caller will update the
2000 * filesystem size and crypto_type_name after calling this function.
2001 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002002static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002003 off64_t off;
2004
2005 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002006 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002007 ftr->major_version = CURRENT_MAJOR_VERSION;
2008 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002009 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002010 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002011
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002012 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002013 case 1:
2014 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2015 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002016
Paul Crowley14c8c072018-09-18 13:30:21 -07002017 case 0:
2018 ftr->kdf_type = KDF_SCRYPT;
2019 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002020
Paul Crowley14c8c072018-09-18 13:30:21 -07002021 default:
2022 SLOGE("keymaster_check_compatibility failed");
2023 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002024 }
2025
Kenny Rootc4c70f12013-06-14 12:11:38 -07002026 get_device_scrypt_params(ftr);
2027
Ken Sumrall160b4d62013-04-22 12:15:39 -07002028 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2029 if (get_crypt_ftr_info(NULL, &off) == 0) {
2030 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002031 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002032 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002033
2034 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002035}
2036
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002037#define FRAMEWORK_BOOT_WAIT 60
2038
Paul Crowley14c8c072018-09-18 13:30:21 -07002039static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2040 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002041 if (fd == -1) {
2042 SLOGE("Error opening file %s", filename);
2043 return -1;
2044 }
2045
2046 char block[CRYPT_INPLACE_BUFSIZE];
2047 memset(block, 0, sizeof(block));
2048 if (unix_read(fd, block, sizeof(block)) < 0) {
2049 SLOGE("Error reading file %s", filename);
2050 close(fd);
2051 return -1;
2052 }
2053
2054 close(fd);
2055
2056 SHA256_CTX c;
2057 SHA256_Init(&c);
2058 SHA256_Update(&c, block, sizeof(block));
2059 SHA256_Final(buf, &c);
2060
2061 return 0;
2062}
2063
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002064static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2065 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002066 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002067 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002068
Paul Lawrence87999172014-02-20 12:21:31 -08002069 /* The size of the userdata partition, and add in the vold volumes below */
2070 tot_encryption_size = crypt_ftr->fs_size;
2071
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002072 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002073 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002074
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002075 if (rc == ENABLE_INPLACE_ERR_DEV) {
2076 /* Hack for b/17898962 */
2077 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2078 cryptfs_reboot(RebootType::reboot);
2079 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002080
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002081 if (!rc) {
2082 crypt_ftr->encrypted_upto = cur_encryption_done;
2083 }
Paul Lawrence87999172014-02-20 12:21:31 -08002084
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002085 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2086 /* The inplace routine never actually sets the progress to 100% due
2087 * to the round down nature of integer division, so set it here */
2088 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002089 }
2090
2091 return rc;
2092}
2093
Paul Crowleyb64933a2017-10-31 08:25:55 -07002094static int vold_unmountAll(void) {
2095 VolumeManager* vm = VolumeManager::Instance();
2096 return vm->unmountAll();
2097}
2098
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002099int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002100 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002101 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002102 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002103 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002104 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002105 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002106 char lockid[32] = {0};
Ken Sumrall29d8da82011-05-18 17:20:07 -07002107 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002108 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002109 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002110 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002111 bool onlyCreateHeader = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002112
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002113 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002114 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2115 /* An encryption was underway and was interrupted */
2116 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2117 crypt_ftr.encrypted_upto = 0;
2118 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002119
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002120 /* At this point, we are in an inconsistent state. Until we successfully
2121 complete encryption, a reboot will leave us broken. So mark the
2122 encryption failed in case that happens.
2123 On successfully completing encryption, remove this flag */
2124 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002125
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002126 put_crypt_ftr_and_key(&crypt_ftr);
2127 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2128 if (!check_ftr_sha(&crypt_ftr)) {
2129 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2130 put_crypt_ftr_and_key(&crypt_ftr);
2131 goto error_unencrypted;
2132 }
2133
2134 /* Doing a reboot-encryption*/
2135 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2136 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2137 rebootEncryption = true;
2138 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002139 } else {
2140 // We don't want to accidentally reference invalid data.
2141 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002142 }
2143
2144 property_get("ro.crypto.state", encrypted_state, "");
2145 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2146 SLOGE("Device is already running encrypted, aborting");
2147 goto error_unencrypted;
2148 }
2149
2150 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002151 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2152 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002153
Ken Sumrall3ed82362011-01-28 23:31:16 -08002154 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002155 uint64_t nr_sec;
2156 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002157 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2158 goto error_unencrypted;
2159 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002160
2161 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002162 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002163 uint64_t fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002164 fs_size_sec = get_fs_size(real_blkdev);
Paul Crowley14c8c072018-09-18 13:30:21 -07002165 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002166
Paul Lawrence87999172014-02-20 12:21:31 -08002167 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002168
2169 if (fs_size_sec > max_fs_size_sec) {
2170 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2171 goto error_unencrypted;
2172 }
2173 }
2174
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002175 /* Get a wakelock as this may take a while, and we don't want the
2176 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2177 * wants to keep the screen on, it can grab a full wakelock.
2178 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002179 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002180 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2181
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002182 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002183 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002184 */
2185 property_set("vold.decrypt", "trigger_shutdown_framework");
2186 SLOGD("Just asked init to shut down class main\n");
2187
Jeff Sharkey9c484982015-03-31 10:35:33 -07002188 /* Ask vold to unmount all devices that it manages */
2189 if (vold_unmountAll()) {
2190 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002191 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002192
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002193 /* no_ui means we are being called from init, not settings.
2194 Now we always reboot from settings, so !no_ui means reboot
2195 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002196 if (!no_ui) {
2197 /* Try fallback, which is to reboot and try there */
2198 onlyCreateHeader = true;
2199 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2200 if (breadcrumb == 0) {
2201 SLOGE("Failed to create breadcrumb file");
2202 goto error_shutting_down;
2203 }
2204 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002205 }
2206
2207 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002208 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002209 /* Now that /data is unmounted, we need to mount a tmpfs
2210 * /data, set a property saying we're doing inplace encryption,
2211 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002212 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002213 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002214 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002215 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002216 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002217 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002218
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002219 /* restart the framework. */
2220 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002221 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002222
Ken Sumrall92736ef2012-10-17 20:57:14 -07002223 /* Ugh, shutting down the framework is not synchronous, so until it
2224 * can be fixed, this horrible hack will wait a moment for it all to
2225 * shut down before proceeding. Without it, some devices cannot
2226 * restart the graphics services.
2227 */
2228 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002229 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002230
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002231 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002232 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002233 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002234 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2235 goto error_shutting_down;
2236 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002237
Paul Lawrence87999172014-02-20 12:21:31 -08002238 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002239 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002240 } else {
2241 crypt_ftr.fs_size = nr_sec;
2242 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002243 /* At this point, we are in an inconsistent state. Until we successfully
2244 complete encryption, a reboot will leave us broken. So mark the
2245 encryption failed in case that happens.
2246 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002247 if (onlyCreateHeader) {
2248 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2249 } else {
2250 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2251 }
Paul Lawrence87999172014-02-20 12:21:31 -08002252 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002253 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2254 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002255
Paul Lawrence87999172014-02-20 12:21:31 -08002256 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002257 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2258 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002259 SLOGE("Cannot create encrypted master key\n");
2260 goto error_shutting_down;
2261 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002262
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002263 /* Replace scrypted intermediate key if we are preparing for a reboot */
2264 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002265 unsigned char fake_master_key[MAX_KEY_LEN];
2266 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002267 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002268 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2269 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002270 }
2271
Paul Lawrence87999172014-02-20 12:21:31 -08002272 /* Write the key to the end of the partition */
2273 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002274
Paul Lawrence87999172014-02-20 12:21:31 -08002275 /* If any persistent data has been remembered, save it.
2276 * If none, create a valid empty table and save that.
2277 */
2278 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002279 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2280 if (pdata) {
2281 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2282 persist_data = pdata;
2283 }
Paul Lawrence87999172014-02-20 12:21:31 -08002284 }
2285 if (persist_data) {
2286 save_persistent_data();
2287 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002288 }
2289
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002290 if (onlyCreateHeader) {
2291 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002292 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002293 }
2294
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002295 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002296 /* startup service classes main and late_start */
2297 property_set("vold.decrypt", "trigger_restart_min_framework");
2298 SLOGD("Just triggered restart_min_framework\n");
2299
2300 /* OK, the framework is restarted and will soon be showing a
2301 * progress bar. Time to setup an encrypted mapping, and
2302 * either write a new filesystem, or encrypt in place updating
2303 * the progress bar as we work.
2304 */
2305 }
2306
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002307 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002308 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002309 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002310
Paul Lawrence87999172014-02-20 12:21:31 -08002311 /* If we are continuing, check checksums match */
2312 rc = 0;
2313 if (previously_encrypted_upto) {
2314 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2315 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002316
Paul Crowley14c8c072018-09-18 13:30:21 -07002317 if (!rc &&
2318 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002319 SLOGE("Checksums do not match - trigger wipe");
2320 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002321 }
2322 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002323
Paul Lawrence87999172014-02-20 12:21:31 -08002324 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002325 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002326 previously_encrypted_upto);
2327 }
2328
2329 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002330 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002331 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002332 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002333 SLOGE("Error calculating checksum for continuing encryption");
2334 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002335 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002336 }
2337
2338 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002339 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002340
Paul Crowley14c8c072018-09-18 13:30:21 -07002341 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002342 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002343 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002344
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002345 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002346 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2347 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002348 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002349 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002350
Paul Lawrence6bfed202014-07-28 12:47:22 -07002351 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002352
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002353 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2354 char value[PROPERTY_VALUE_MAX];
2355 property_get("ro.crypto.state", value, "");
2356 if (!strcmp(value, "")) {
2357 /* default encryption - continue first boot sequence */
2358 property_set("ro.crypto.state", "encrypted");
2359 property_set("ro.crypto.type", "block");
2360 release_wake_lock(lockid);
2361 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2362 // Bring up cryptkeeper that will check the password and set it
2363 property_set("vold.decrypt", "trigger_shutdown_framework");
2364 sleep(2);
2365 property_set("vold.encrypt_progress", "");
2366 cryptfs_trigger_restart_min_framework();
2367 } else {
2368 cryptfs_check_passwd(DEFAULT_PASSWORD);
2369 cryptfs_restart_internal(1);
2370 }
2371 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002372 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002373 sleep(2); /* Give the UI a chance to show 100% progress */
2374 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002375 }
Paul Lawrence87999172014-02-20 12:21:31 -08002376 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002377 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002378 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002379 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002380 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002381 char value[PROPERTY_VALUE_MAX];
2382
Ken Sumrall319369a2012-06-27 16:30:18 -07002383 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002384 if (!strcmp(value, "1")) {
2385 /* wipe data if encryption failed */
2386 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002387 std::string err;
2388 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002389 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002390 if (!write_bootloader_message(options, &err)) {
2391 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002392 }
Josh Gaofec44372017-08-28 13:22:55 -07002393 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002394 } else {
2395 /* set property to trigger dialog */
2396 property_set("vold.encrypt_progress", "error_partially_encrypted");
2397 release_wake_lock(lockid);
2398 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002399 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002400 }
2401
Ken Sumrall3ed82362011-01-28 23:31:16 -08002402 /* hrm, the encrypt step claims success, but the reboot failed.
2403 * This should not happen.
2404 * Set the property and return. Hope the framework can deal with it.
2405 */
2406 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002407 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002408 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002409
2410error_unencrypted:
2411 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002412 if (lockid[0]) {
2413 release_wake_lock(lockid);
2414 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002415 return -1;
2416
2417error_shutting_down:
2418 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2419 * but the framework is stopped and not restarted to show the error, so it's up to
2420 * vold to restart the system.
2421 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002422 SLOGE(
2423 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2424 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002425 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002426
2427 /* shouldn't get here */
2428 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002429 if (lockid[0]) {
2430 release_wake_lock(lockid);
2431 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002432 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002433}
2434
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002435int cryptfs_enable(int type, const char* passwd, int no_ui) {
2436 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002437}
2438
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002439int cryptfs_enable_default(int no_ui) {
2440 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002441}
2442
Paul Crowley14c8c072018-09-18 13:30:21 -07002443int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002444 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002445 SLOGE("cryptfs_changepw not valid for file encryption");
2446 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002447 }
2448
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002449 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002450 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002451
2452 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002453 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002454 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002455 return -1;
2456 }
2457
Paul Lawrencef4faa572014-01-29 13:31:03 -08002458 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2459 SLOGE("Invalid crypt_type %d", crypt_type);
2460 return -1;
2461 }
2462
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002463 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002464 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002465 SLOGE("Error getting crypt footer and key");
2466 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002467 }
2468
Paul Lawrencef4faa572014-01-29 13:31:03 -08002469 crypt_ftr.crypt_type = crypt_type;
2470
Paul Crowley14c8c072018-09-18 13:30:21 -07002471 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2472 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002473 if (rc) {
2474 SLOGE("Encrypt master key failed: %d", rc);
2475 return -1;
2476 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002477 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002478 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002479
2480 return 0;
2481}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002482
Rubin Xu85c01f92014-10-13 12:49:54 +01002483static unsigned int persist_get_max_entries(int encrypted) {
2484 struct crypt_mnt_ftr crypt_ftr;
2485 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002486
2487 /* If encrypted, use the values from the crypt_ftr, otherwise
2488 * use the values for the current spec.
2489 */
2490 if (encrypted) {
2491 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002492 /* Something is wrong, assume no space for entries */
2493 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002494 }
2495 dsize = crypt_ftr.persist_data_size;
2496 } else {
2497 dsize = CRYPT_PERSIST_DATA_SIZE;
2498 }
2499
Rubin Xuf83cc612018-10-09 16:13:38 +01002500 if (dsize > sizeof(struct crypt_persist_data)) {
2501 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2502 } else {
2503 return 0;
2504 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002505}
2506
Paul Crowley14c8c072018-09-18 13:30:21 -07002507static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002508 unsigned int i;
2509
2510 if (persist_data == NULL) {
2511 return -1;
2512 }
2513 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2514 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2515 /* We found it! */
2516 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2517 return 0;
2518 }
2519 }
2520
2521 return -1;
2522}
2523
Paul Crowley14c8c072018-09-18 13:30:21 -07002524static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002525 unsigned int i;
2526 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002527 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002528
2529 if (persist_data == NULL) {
2530 return -1;
2531 }
2532
Rubin Xu85c01f92014-10-13 12:49:54 +01002533 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002534
2535 num = persist_data->persist_valid_entries;
2536
2537 for (i = 0; i < num; i++) {
2538 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2539 /* We found an existing entry, update it! */
2540 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2541 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2542 return 0;
2543 }
2544 }
2545
2546 /* We didn't find it, add it to the end, if there is room */
2547 if (persist_data->persist_valid_entries < max_persistent_entries) {
2548 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2549 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2550 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2551 persist_data->persist_valid_entries++;
2552 return 0;
2553 }
2554
2555 return -1;
2556}
2557
Rubin Xu85c01f92014-10-13 12:49:54 +01002558/**
2559 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2560 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2561 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002562int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002563 std::string key_ = key;
2564 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002565
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002566 std::string parsed_field;
2567 unsigned parsed_index;
2568
2569 std::string::size_type split = key_.find_last_of('_');
2570 if (split == std::string::npos) {
2571 parsed_field = key_;
2572 parsed_index = 0;
2573 } else {
2574 parsed_field = key_.substr(0, split);
2575 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002576 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002577
2578 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002579}
2580
2581/*
2582 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2583 * remaining entries starting from index will be deleted.
2584 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2585 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2586 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2587 *
2588 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002589static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002590 unsigned int i;
2591 unsigned int j;
2592 unsigned int num;
2593
2594 if (persist_data == NULL) {
2595 return PERSIST_DEL_KEY_ERROR_OTHER;
2596 }
2597
2598 num = persist_data->persist_valid_entries;
2599
Paul Crowley14c8c072018-09-18 13:30:21 -07002600 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002601 // Filter out to-be-deleted entries in place.
2602 for (i = 0; i < num; i++) {
2603 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2604 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2605 j++;
2606 }
2607 }
2608
2609 if (j < num) {
2610 persist_data->persist_valid_entries = j;
2611 // Zeroise the remaining entries
2612 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2613 return PERSIST_DEL_KEY_OK;
2614 } else {
2615 // Did not find an entry matching the given fieldname
2616 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2617 }
2618}
2619
Paul Crowley14c8c072018-09-18 13:30:21 -07002620static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002621 unsigned int i;
2622 unsigned int count;
2623
2624 if (persist_data == NULL) {
2625 return -1;
2626 }
2627
2628 count = 0;
2629 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2630 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2631 count++;
2632 }
2633 }
2634
2635 return count;
2636}
2637
Ken Sumrall160b4d62013-04-22 12:15:39 -07002638/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002639int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002640 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002641 SLOGE("Cannot get field when file encrypted");
2642 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002643 }
2644
Ken Sumrall160b4d62013-04-22 12:15:39 -07002645 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002646 /* CRYPTO_GETFIELD_OK is success,
2647 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2648 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2649 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002650 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002651 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2652 int i;
2653 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002654
2655 if (persist_data == NULL) {
2656 load_persistent_data();
2657 if (persist_data == NULL) {
2658 SLOGE("Getfield error, cannot load persistent data");
2659 goto out;
2660 }
2661 }
2662
Rubin Xu85c01f92014-10-13 12:49:54 +01002663 // Read value from persistent entries. If the original value is split into multiple entries,
2664 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002665 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002666 // 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 -07002667 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002668 // value too small
2669 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2670 goto out;
2671 }
2672 rc = CRYPTO_GETFIELD_OK;
2673
2674 for (i = 1; /* break explicitly */; i++) {
2675 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002676 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002677 // If the fieldname is very long, we stop as soon as it begins to overflow the
2678 // maximum field length. At this point we have in fact fully read out the original
2679 // value because cryptfs_setfield would not allow fields with longer names to be
2680 // written in the first place.
2681 break;
2682 }
2683 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002684 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2685 // value too small.
2686 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2687 goto out;
2688 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002689 } else {
2690 // Exhaust all entries.
2691 break;
2692 }
2693 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002694 } else {
2695 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002696 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002697 }
2698
2699out:
2700 return rc;
2701}
2702
2703/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002704int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002705 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002706 SLOGE("Cannot set field when file encrypted");
2707 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002708 }
2709
Ken Sumrall160b4d62013-04-22 12:15:39 -07002710 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002711 /* 0 is success, negative values are error */
2712 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002713 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002714 unsigned int field_id;
2715 char temp_field[PROPERTY_KEY_MAX];
2716 unsigned int num_entries;
2717 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002718
2719 if (persist_data == NULL) {
2720 load_persistent_data();
2721 if (persist_data == NULL) {
2722 SLOGE("Setfield error, cannot load persistent data");
2723 goto out;
2724 }
2725 }
2726
2727 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002728 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002729 encrypted = 1;
2730 }
2731
Rubin Xu85c01f92014-10-13 12:49:54 +01002732 // Compute the number of entries required to store value, each entry can store up to
2733 // (PROPERTY_VALUE_MAX - 1) chars
2734 if (strlen(value) == 0) {
2735 // Empty value also needs one entry to store.
2736 num_entries = 1;
2737 } else {
2738 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2739 }
2740
2741 max_keylen = strlen(fieldname);
2742 if (num_entries > 1) {
2743 // Need an extra "_%d" suffix.
2744 max_keylen += 1 + log10(num_entries);
2745 }
2746 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2747 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002748 goto out;
2749 }
2750
Rubin Xu85c01f92014-10-13 12:49:54 +01002751 // Make sure we have enough space to write the new value
2752 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2753 persist_get_max_entries(encrypted)) {
2754 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2755 goto out;
2756 }
2757
2758 // Now that we know persist_data has enough space for value, let's delete the old field first
2759 // to make up space.
2760 persist_del_keys(fieldname, 0);
2761
2762 if (persist_set_key(fieldname, value, encrypted)) {
2763 // fail to set key, should not happen as we have already checked the available space
2764 SLOGE("persist_set_key() error during setfield()");
2765 goto out;
2766 }
2767
2768 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002769 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002770
2771 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2772 // fail to set key, should not happen as we have already checked the available space.
2773 SLOGE("persist_set_key() error during setfield()");
2774 goto out;
2775 }
2776 }
2777
Ken Sumrall160b4d62013-04-22 12:15:39 -07002778 /* If we are running encrypted, save the persistent data now */
2779 if (encrypted) {
2780 if (save_persistent_data()) {
2781 SLOGE("Setfield error, cannot save persistent data");
2782 goto out;
2783 }
2784 }
2785
Rubin Xu85c01f92014-10-13 12:49:54 +01002786 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002787
2788out:
2789 return rc;
2790}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002791
2792/* Checks userdata. Attempt to mount the volume if default-
2793 * encrypted.
2794 * On success trigger next init phase and return 0.
2795 * Currently do not handle failure - see TODO below.
2796 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002797int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002798 int crypt_type = cryptfs_get_password_type();
2799 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2800 SLOGE("Bad crypt type - error");
2801 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002802 SLOGD(
2803 "Password is not default - "
2804 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002805 property_set("vold.decrypt", "trigger_restart_min_framework");
2806 return 0;
2807 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2808 SLOGD("Password is default - restarting filesystem");
2809 cryptfs_restart_internal(0);
2810 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002811 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002812 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002813 }
2814
Paul Lawrence6bfed202014-07-28 12:47:22 -07002815 /** Corrupt. Allow us to boot into framework, which will detect bad
2816 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002817 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002818 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002819 return 0;
2820}
2821
2822/* Returns type of the password, default, pattern, pin or password.
2823 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002824int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002825 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002826 SLOGE("cryptfs_get_password_type not valid for file encryption");
2827 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002828 }
2829
Paul Lawrencef4faa572014-01-29 13:31:03 -08002830 struct crypt_mnt_ftr crypt_ftr;
2831
2832 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2833 SLOGE("Error getting crypt footer and key\n");
2834 return -1;
2835 }
2836
Paul Lawrence6bfed202014-07-28 12:47:22 -07002837 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2838 return -1;
2839 }
2840
Paul Lawrencef4faa572014-01-29 13:31:03 -08002841 return crypt_ftr.crypt_type;
2842}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002843
Paul Crowley14c8c072018-09-18 13:30:21 -07002844const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002845 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002846 SLOGE("cryptfs_get_password not valid for file encryption");
2847 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002848 }
2849
Paul Lawrence399317e2014-03-10 13:20:50 -07002850 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002851 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002852 if (now.tv_sec < password_expiry_time) {
2853 return password;
2854 } else {
2855 cryptfs_clear_password();
2856 return 0;
2857 }
2858}
2859
Paul Crowley14c8c072018-09-18 13:30:21 -07002860void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002861 if (password) {
2862 size_t len = strlen(password);
2863 memset(password, 0, len);
2864 free(password);
2865 password = 0;
2866 password_expiry_time = 0;
2867 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002868}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002869
Paul Crowley14c8c072018-09-18 13:30:21 -07002870int cryptfs_isConvertibleToFBE() {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002871 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07002872 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07002873}