blob: e3638354ebcaa512e8ce6570d6a530e6f5eb5281 [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
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Paul Crowley3b71fc52017-10-09 10:55:21 -070041#include <ext4_utils/ext4_crypt.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070042#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070058#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000059#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000060#include "f2fs_sparseblock.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070061#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080062#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000063#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080064#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070065#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080066extern "C" {
67#include <crypto_scrypt.h>
68}
Mark Salyzyn3e971272014-01-21 13:27:04 -080069
Mark Salyzyn5eecc442014-02-12 14:16:14 -080070#define UNUSED __attribute__((unused))
71
Ken Sumrall8f869aa2010-12-03 03:47:09 -080072#define DM_CRYPT_BUF_SIZE 4096
73
Jason parks70a4b3f2011-01-28 10:10:47 -060074#define HASH_COUNT 2000
75#define KEY_LEN_BYTES 16
76#define IV_LEN_BYTES 16
77
Ken Sumrall29d8da82011-05-18 17:20:07 -070078#define KEY_IN_FOOTER "footer"
79
Paul Lawrence3bd36d52015-06-09 13:37:44 -070080#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080081
Paul Lawrence3d99eba2015-11-20 07:07:19 -080082#define CRYPTO_BLOCK_DEVICE "userdata"
83
84#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
85
Ken Sumrall29d8da82011-05-18 17:20:07 -070086#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070087#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070088
Ken Sumralle919efe2012-09-29 17:07:41 -070089#define TABLE_LOAD_RETRIES 10
90
Shawn Willden47ba10d2014-09-03 17:07:06 -060091#define RSA_KEY_SIZE 2048
92#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
93#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060094#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070095
Paul Lawrence8e3f4512014-09-08 10:11:17 -070096#define RETRY_MOUNT_ATTEMPTS 10
97#define RETRY_MOUNT_DELAY_SECONDS 1
98
Paul Crowley5afbc622017-11-27 09:42:17 -080099#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
100
Paul Crowley73473332017-11-21 15:43:51 -0800101static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
102
Jason parks70a4b3f2011-01-28 10:10:47 -0600103static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700104static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600105static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700106static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800107
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700108/* Should we use keymaster? */
109static int keymaster_check_compatibility()
110{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000111 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700112}
113
114/* Create a new keymaster key and store it in this footer */
115static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
116{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800117 if (ftr->keymaster_blob_size) {
118 SLOGI("Already have key");
119 return 0;
120 }
121
Janis Danisevskis015ec302017-01-31 11:31:08 +0000122 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
123 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
124 &ftr->keymaster_blob_size);
125 if (rc) {
126 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800127 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000128 ftr->keymaster_blob_size = 0;
129 }
130 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700131 return -1;
132 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000133 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700134}
135
Shawn Willdene17a9c42014-09-08 13:04:08 -0600136/* This signs the given object using the keymaster key. */
137static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600138 const unsigned char *object,
139 const size_t object_size,
140 unsigned char **signature,
141 size_t *signature_size)
142{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600143 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600144 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600145 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600146
Shawn Willdene17a9c42014-09-08 13:04:08 -0600147 // To sign a message with RSA, the message must satisfy two
148 // constraints:
149 //
150 // 1. The message, when interpreted as a big-endian numeric value, must
151 // be strictly less than the public modulus of the RSA key. Note
152 // that because the most significant bit of the public modulus is
153 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
154 // key), an n-bit message with most significant bit 0 always
155 // satisfies this requirement.
156 //
157 // 2. The message must have the same length in bits as the public
158 // modulus of the RSA key. This requirement isn't mathematically
159 // necessary, but is necessary to ensure consistency in
160 // implementations.
161 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600162 case KDF_SCRYPT_KEYMASTER:
163 // This ensures the most significant byte of the signed message
164 // is zero. We could have zero-padded to the left instead, but
165 // this approach is slightly more robust against changes in
166 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600167 // so) because we really should be using a proper deterministic
168 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800169 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600170 SLOGI("Signing safely-padded object");
171 break;
172 default:
173 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000174 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600175 }
Paul Crowley73473332017-11-21 15:43:51 -0800176 for (;;) {
177 auto result = keymaster_sign_object_for_cryptfs_scrypt(
178 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
179 to_sign_size, signature, signature_size);
180 switch (result) {
181 case KeymasterSignResult::ok:
182 return 0;
183 case KeymasterSignResult::upgrade:
184 break;
185 default:
186 return -1;
187 }
188 SLOGD("Upgrading key");
189 if (keymaster_upgrade_key_for_cryptfs_scrypt(
190 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
191 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
192 &ftr->keymaster_blob_size) != 0) {
193 SLOGE("Failed to upgrade key");
194 return -1;
195 }
196 if (put_crypt_ftr_and_key(ftr) != 0) {
197 SLOGE("Failed to write upgraded key to disk");
198 }
199 SLOGD("Key upgraded successfully");
200 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600201}
202
Paul Lawrence399317e2014-03-10 13:20:50 -0700203/* Store password when userdata is successfully decrypted and mounted.
204 * Cleared by cryptfs_clear_password
205 *
206 * To avoid a double prompt at boot, we need to store the CryptKeeper
207 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
208 * Since the entire framework is torn down and rebuilt after encryption,
209 * we have to use a daemon or similar to store the password. Since vold
210 * is secured against IPC except from system processes, it seems a reasonable
211 * place to store this.
212 *
213 * password should be cleared once it has been used.
214 *
215 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800216 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700217static char* password = 0;
218static int password_expiry_time = 0;
219static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800220
Josh Gaofec44372017-08-28 13:22:55 -0700221enum class RebootType {reboot, recovery, shutdown};
222static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700223{
Josh Gaofec44372017-08-28 13:22:55 -0700224 switch (rt) {
225 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800226 property_set(ANDROID_RB_PROPERTY, "reboot");
227 break;
228
Josh Gaofec44372017-08-28 13:22:55 -0700229 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800230 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
231 break;
232
Josh Gaofec44372017-08-28 13:22:55 -0700233 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800234 property_set(ANDROID_RB_PROPERTY, "shutdown");
235 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700236 }
Paul Lawrence87999172014-02-20 12:21:31 -0800237
Ken Sumralladfba362013-06-04 16:37:52 -0700238 sleep(20);
239
240 /* Shouldn't get here, reboot should happen before sleep times out */
241 return;
242}
243
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800244static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
245{
246 memset(io, 0, dataSize);
247 io->data_size = dataSize;
248 io->data_start = sizeof(struct dm_ioctl);
249 io->version[0] = 4;
250 io->version[1] = 0;
251 io->version[2] = 0;
252 io->flags = flags;
253 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100254 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800255 }
256}
257
Kenny Rootc4c70f12013-06-14 12:11:38 -0700258/**
259 * Gets the default device scrypt parameters for key derivation time tuning.
260 * The parameters should lead to about one second derivation time for the
261 * given device.
262 */
263static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700264 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000265 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700266
Paul Crowley63c18d32016-02-10 14:02:47 +0000267 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
268 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
269 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
270 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700271 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000272 ftr->N_factor = Nf;
273 ftr->r_factor = rf;
274 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700275}
276
Ken Sumrall3ed82362011-01-28 23:31:16 -0800277static unsigned int get_fs_size(char *dev)
278{
279 int fd, block_size;
280 struct ext4_super_block sb;
281 off64_t len;
282
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700283 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800284 SLOGE("Cannot open device to get filesystem size ");
285 return 0;
286 }
287
288 if (lseek64(fd, 1024, SEEK_SET) < 0) {
289 SLOGE("Cannot seek to superblock");
290 return 0;
291 }
292
293 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
294 SLOGE("Cannot read superblock");
295 return 0;
296 }
297
298 close(fd);
299
Daniel Rosenberge82df162014-08-15 22:19:23 +0000300 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
301 SLOGE("Not a valid ext4 superblock");
302 return 0;
303 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800304 block_size = 1024 << sb.s_log_block_size;
305 /* compute length in bytes */
306 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
307
308 /* return length in sectors */
309 return (unsigned int) (len / 512);
310}
311
Ken Sumrall160b4d62013-04-22 12:15:39 -0700312static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
313{
314 static int cached_data = 0;
315 static off64_t cached_off = 0;
316 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
317 int fd;
318 char key_loc[PROPERTY_VALUE_MAX];
319 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700320 int rc = -1;
321
322 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700323 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700324
325 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700326 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700327 SLOGE("Cannot open real block device %s\n", real_blkdev);
328 return -1;
329 }
330
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900331 unsigned long nr_sec = 0;
332 get_blkdev_size(fd, &nr_sec);
333 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700334 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
335 * encryption info footer and key, and plenty of bytes to spare for future
336 * growth.
337 */
338 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
339 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
340 cached_data = 1;
341 } else {
342 SLOGE("Cannot get size of block device %s\n", real_blkdev);
343 }
344 close(fd);
345 } else {
346 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
347 cached_off = 0;
348 cached_data = 1;
349 }
350 }
351
352 if (cached_data) {
353 if (metadata_fname) {
354 *metadata_fname = cached_metadata_fname;
355 }
356 if (off) {
357 *off = cached_off;
358 }
359 rc = 0;
360 }
361
362 return rc;
363}
364
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800365/* Set sha256 checksum in structure */
366static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
367{
368 SHA256_CTX c;
369 SHA256_Init(&c);
370 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
371 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
372 SHA256_Final(crypt_ftr->sha256, &c);
373}
374
Ken Sumralle8744072011-01-18 22:01:55 -0800375/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800376 * update the failed mount count but not change the key.
377 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800379{
380 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800381 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700382 /* starting_off is set to the SEEK_SET offset
383 * where the crypto structure starts
384 */
385 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800386 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700387 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700388 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800389
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800390 set_ftr_sha(crypt_ftr);
391
Ken Sumrall160b4d62013-04-22 12:15:39 -0700392 if (get_crypt_ftr_info(&fname, &starting_off)) {
393 SLOGE("Unable to get crypt_ftr_info\n");
394 return -1;
395 }
396 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700397 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700398 return -1;
399 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700400 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700401 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700402 return -1;
403 }
404
405 /* Seek to the start of the crypt footer */
406 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
407 SLOGE("Cannot seek to real block device footer\n");
408 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800409 }
410
411 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
412 SLOGE("Cannot write real block device footer\n");
413 goto errout;
414 }
415
Ken Sumrall3be890f2011-09-14 16:53:46 -0700416 fstat(fd, &statbuf);
417 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700418 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700419 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800420 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800421 goto errout;
422 }
423 }
424
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800425 /* Success! */
426 rc = 0;
427
428errout:
429 close(fd);
430 return rc;
431
432}
433
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800434static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
435{
436 struct crypt_mnt_ftr copy;
437 memcpy(&copy, crypt_ftr, sizeof(copy));
438 set_ftr_sha(&copy);
439 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
440}
441
Ken Sumrall160b4d62013-04-22 12:15:39 -0700442static inline int unix_read(int fd, void* buff, int len)
443{
444 return TEMP_FAILURE_RETRY(read(fd, buff, len));
445}
446
447static inline int unix_write(int fd, const void* buff, int len)
448{
449 return TEMP_FAILURE_RETRY(write(fd, buff, len));
450}
451
452static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
453{
454 memset(pdata, 0, len);
455 pdata->persist_magic = PERSIST_DATA_MAGIC;
456 pdata->persist_valid_entries = 0;
457}
458
459/* A routine to update the passed in crypt_ftr to the lastest version.
460 * fd is open read/write on the device that holds the crypto footer and persistent
461 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
462 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
463 */
464static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
465{
Kenny Root7434b312013-06-14 11:29:53 -0700466 int orig_major = crypt_ftr->major_version;
467 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700468
Kenny Root7434b312013-06-14 11:29:53 -0700469 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
470 struct crypt_persist_data *pdata;
471 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700472
Kenny Rootc4c70f12013-06-14 12:11:38 -0700473 SLOGW("upgrading crypto footer to 1.1");
474
Wei Wang4375f1b2017-02-24 17:43:01 -0800475 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700476 if (pdata == NULL) {
477 SLOGE("Cannot allocate persisent data\n");
478 return;
479 }
480 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
481
482 /* Need to initialize the persistent data area */
483 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
484 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100485 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700486 return;
487 }
488 /* Write all zeros to the first copy, making it invalid */
489 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
490
491 /* Write a valid but empty structure to the second copy */
492 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
493 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
494
495 /* Update the footer */
496 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
497 crypt_ftr->persist_data_offset[0] = pdata_offset;
498 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
499 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100500 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700501 }
502
Paul Lawrencef4faa572014-01-29 13:31:03 -0800503 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700504 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800505 /* But keep the old kdf_type.
506 * It will get updated later to KDF_SCRYPT after the password has been verified.
507 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700508 crypt_ftr->kdf_type = KDF_PBKDF2;
509 get_device_scrypt_params(crypt_ftr);
510 crypt_ftr->minor_version = 2;
511 }
512
Paul Lawrencef4faa572014-01-29 13:31:03 -0800513 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
514 SLOGW("upgrading crypto footer to 1.3");
515 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
516 crypt_ftr->minor_version = 3;
517 }
518
Kenny Root7434b312013-06-14 11:29:53 -0700519 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
520 if (lseek64(fd, offset, SEEK_SET) == -1) {
521 SLOGE("Cannot seek to crypt footer\n");
522 return;
523 }
524 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700525 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700526}
527
528
529static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800530{
531 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800532 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800534 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700535 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700536 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800537
Ken Sumrall160b4d62013-04-22 12:15:39 -0700538 if (get_crypt_ftr_info(&fname, &starting_off)) {
539 SLOGE("Unable to get crypt_ftr_info\n");
540 return -1;
541 }
542 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700543 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700544 return -1;
545 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700546 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700547 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700548 return -1;
549 }
550
551 /* Make sure it's 16 Kbytes in length */
552 fstat(fd, &statbuf);
553 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
554 SLOGE("footer file %s is not the expected size!\n", fname);
555 goto errout;
556 }
557
558 /* Seek to the start of the crypt footer */
559 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
560 SLOGE("Cannot seek to real block device footer\n");
561 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800562 }
563
564 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
565 SLOGE("Cannot read real block device footer\n");
566 goto errout;
567 }
568
569 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700570 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800571 goto errout;
572 }
573
Kenny Rootc96a5f82013-06-14 12:08:28 -0700574 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
575 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
576 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800577 goto errout;
578 }
579
Kenny Rootc96a5f82013-06-14 12:08:28 -0700580 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
581 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
582 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800583 }
584
Ken Sumrall160b4d62013-04-22 12:15:39 -0700585 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
586 * copy on disk before returning.
587 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700588 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700589 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800590 }
591
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800592 /* Success! */
593 rc = 0;
594
595errout:
596 close(fd);
597 return rc;
598}
599
Ken Sumrall160b4d62013-04-22 12:15:39 -0700600static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
601{
602 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
603 crypt_ftr->persist_data_offset[1]) {
604 SLOGE("Crypt_ftr persist data regions overlap");
605 return -1;
606 }
607
608 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
609 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
610 return -1;
611 }
612
613 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
614 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
615 CRYPT_FOOTER_OFFSET) {
616 SLOGE("Persistent data extends past crypto footer");
617 return -1;
618 }
619
620 return 0;
621}
622
623static int load_persistent_data(void)
624{
625 struct crypt_mnt_ftr crypt_ftr;
626 struct crypt_persist_data *pdata = NULL;
627 char encrypted_state[PROPERTY_VALUE_MAX];
628 char *fname;
629 int found = 0;
630 int fd;
631 int ret;
632 int i;
633
634 if (persist_data) {
635 /* Nothing to do, we've already loaded or initialized it */
636 return 0;
637 }
638
639
640 /* If not encrypted, just allocate an empty table and initialize it */
641 property_get("ro.crypto.state", encrypted_state, "");
642 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800643 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700644 if (pdata) {
645 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
646 persist_data = pdata;
647 return 0;
648 }
649 return -1;
650 }
651
652 if(get_crypt_ftr_and_key(&crypt_ftr)) {
653 return -1;
654 }
655
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700656 if ((crypt_ftr.major_version < 1)
657 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700658 SLOGE("Crypt_ftr version doesn't support persistent data");
659 return -1;
660 }
661
662 if (get_crypt_ftr_info(&fname, NULL)) {
663 return -1;
664 }
665
666 ret = validate_persistent_data_storage(&crypt_ftr);
667 if (ret) {
668 return -1;
669 }
670
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700671 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700672 if (fd < 0) {
673 SLOGE("Cannot open %s metadata file", fname);
674 return -1;
675 }
676
Wei Wang4375f1b2017-02-24 17:43:01 -0800677 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800678 if (pdata == NULL) {
679 SLOGE("Cannot allocate memory for persistent data");
680 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700681 }
682
683 for (i = 0; i < 2; i++) {
684 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
685 SLOGE("Cannot seek to read persistent data on %s", fname);
686 goto err2;
687 }
688 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
689 SLOGE("Error reading persistent data on iteration %d", i);
690 goto err2;
691 }
692 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
693 found = 1;
694 break;
695 }
696 }
697
698 if (!found) {
699 SLOGI("Could not find valid persistent data, creating");
700 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
701 }
702
703 /* Success */
704 persist_data = pdata;
705 close(fd);
706 return 0;
707
708err2:
709 free(pdata);
710
711err:
712 close(fd);
713 return -1;
714}
715
716static int save_persistent_data(void)
717{
718 struct crypt_mnt_ftr crypt_ftr;
719 struct crypt_persist_data *pdata;
720 char *fname;
721 off64_t write_offset;
722 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700723 int fd;
724 int ret;
725
726 if (persist_data == NULL) {
727 SLOGE("No persistent data to save");
728 return -1;
729 }
730
731 if(get_crypt_ftr_and_key(&crypt_ftr)) {
732 return -1;
733 }
734
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700735 if ((crypt_ftr.major_version < 1)
736 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700737 SLOGE("Crypt_ftr version doesn't support persistent data");
738 return -1;
739 }
740
741 ret = validate_persistent_data_storage(&crypt_ftr);
742 if (ret) {
743 return -1;
744 }
745
746 if (get_crypt_ftr_info(&fname, NULL)) {
747 return -1;
748 }
749
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700750 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700751 if (fd < 0) {
752 SLOGE("Cannot open %s metadata file", fname);
753 return -1;
754 }
755
Wei Wang4375f1b2017-02-24 17:43:01 -0800756 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700757 if (pdata == NULL) {
758 SLOGE("Cannot allocate persistant data");
759 goto err;
760 }
761
762 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
763 SLOGE("Cannot seek to read persistent data on %s", fname);
764 goto err2;
765 }
766
767 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
768 SLOGE("Error reading persistent data before save");
769 goto err2;
770 }
771
772 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
773 /* The first copy is the curent valid copy, so write to
774 * the second copy and erase this one */
775 write_offset = crypt_ftr.persist_data_offset[1];
776 erase_offset = crypt_ftr.persist_data_offset[0];
777 } else {
778 /* The second copy must be the valid copy, so write to
779 * the first copy, and erase the second */
780 write_offset = crypt_ftr.persist_data_offset[0];
781 erase_offset = crypt_ftr.persist_data_offset[1];
782 }
783
784 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100785 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700786 SLOGE("Cannot seek to write persistent data");
787 goto err2;
788 }
789 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
790 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100791 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700792 SLOGE("Cannot seek to erase previous persistent data");
793 goto err2;
794 }
795 fsync(fd);
796 memset(pdata, 0, crypt_ftr.persist_data_size);
797 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
798 (int) crypt_ftr.persist_data_size) {
799 SLOGE("Cannot write to erase previous persistent data");
800 goto err2;
801 }
802 fsync(fd);
803 } else {
804 SLOGE("Cannot write to save persistent data");
805 goto err2;
806 }
807
808 /* Success */
809 free(pdata);
810 close(fd);
811 return 0;
812
813err2:
814 free(pdata);
815err:
816 close(fd);
817 return -1;
818}
819
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800820/* Convert a binary key of specified length into an ascii hex string equivalent,
821 * without the leading 0x and with null termination
822 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700823static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700824 unsigned int keysize, char *master_key_ascii) {
825 unsigned int i, a;
826 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800827
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700828 for (i=0, a=0; i<keysize; i++, a+=2) {
829 /* For each byte, write out two ascii hex digits */
830 nibble = (master_key[i] >> 4) & 0xf;
831 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800832
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700833 nibble = master_key[i] & 0xf;
834 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
835 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800836
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700837 /* Add the null termination */
838 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800839
840}
841
Jeff Sharkey9c484982015-03-31 10:35:33 -0700842static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
843 const unsigned char *master_key, const char *real_blk_name,
844 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800845 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800846 struct dm_ioctl *io;
847 struct dm_target_spec *tgt;
848 char *crypt_params;
849 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800850 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800851 int i;
852
853 io = (struct dm_ioctl *) buffer;
854
855 /* Load the mapping table for this device */
856 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
857
858 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
859 io->target_count = 1;
860 tgt->status = 0;
861 tgt->sector_start = 0;
862 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700863 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800864
865 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
866 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800867
868 buff_offset = crypt_params - buffer;
Paul Crowley5afbc622017-11-27 09:42:17 -0800869 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800870 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
871 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
872 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800873 crypt_params += strlen(crypt_params) + 1;
874 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
875 tgt->next = crypt_params - buffer;
876
877 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
878 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
879 break;
880 }
881 usleep(500000);
882 }
883
884 if (i == TABLE_LOAD_RETRIES) {
885 /* We failed to load the table, return an error */
886 return -1;
887 } else {
888 return i + 1;
889 }
890}
891
892
893static int get_dm_crypt_version(int fd, const char *name, int *version)
894{
895 char buffer[DM_CRYPT_BUF_SIZE];
896 struct dm_ioctl *io;
897 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800898
899 io = (struct dm_ioctl *) buffer;
900
901 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
902
903 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
904 return -1;
905 }
906
907 /* Iterate over the returned versions, looking for name of "crypt".
908 * When found, get and return the version.
909 */
910 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
911 while (v->next) {
912 if (! strcmp(v->name, "crypt")) {
913 /* We found the crypt driver, return the version, and get out */
914 version[0] = v->version[0];
915 version[1] = v->version[1];
916 version[2] = v->version[2];
917 return 0;
918 }
919 v = (struct dm_target_versions *)(((char *)v) + v->next);
920 }
921
922 return -1;
923}
924
Paul Crowley5afbc622017-11-27 09:42:17 -0800925static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
926 if (extra_params_vec.empty()) return "";
927 std::string extra_params = std::to_string(extra_params_vec.size());
928 for (const auto& p : extra_params_vec) {
929 extra_params.append(" ");
930 extra_params.append(p);
931 }
932 return extra_params;
933}
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800934
Paul Crowley5afbc622017-11-27 09:42:17 -0800935static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
936 const char* real_blk_name, char* crypto_blk_name, const char* name,
937 uint32_t flags) {
938 char buffer[DM_CRYPT_BUF_SIZE];
939 struct dm_ioctl* io;
940 unsigned int minor;
941 int fd = 0;
942 int err;
943 int retval = -1;
944 int version[3];
945 int load_count;
946 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800947
Paul Crowley5afbc622017-11-27 09:42:17 -0800948 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
949 SLOGE("Cannot open device-mapper\n");
950 goto errout;
951 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800952
Paul Crowley5afbc622017-11-27 09:42:17 -0800953 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800954
Paul Crowley5afbc622017-11-27 09:42:17 -0800955 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
956 err = ioctl(fd, DM_DEV_CREATE, io);
957 if (err) {
958 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
959 goto errout;
960 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800961
Paul Crowley5afbc622017-11-27 09:42:17 -0800962 /* Get the device status, in particular, the name of it's device file */
963 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
964 if (ioctl(fd, DM_DEV_STATUS, io)) {
965 SLOGE("Cannot retrieve dm-crypt device status\n");
966 goto errout;
967 }
968 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
969 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -0700970
Paul Crowley5afbc622017-11-27 09:42:17 -0800971 if (!get_dm_crypt_version(fd, name, version)) {
972 /* Support for allow_discards was added in version 1.11.0 */
973 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
974 extra_params_vec.emplace_back("allow_discards");
975 }
976 }
977 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
978 extra_params_vec.emplace_back("allow_encrypt_override");
979 }
980 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
981 extra_params_as_string(extra_params_vec).c_str());
982 if (load_count < 0) {
983 SLOGE("Cannot load dm-crypt mapping table.\n");
984 goto errout;
985 } else if (load_count > 1) {
986 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
987 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800988
Paul Crowley5afbc622017-11-27 09:42:17 -0800989 /* Resume this device to activate it */
990 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800991
Paul Crowley5afbc622017-11-27 09:42:17 -0800992 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
993 SLOGE("Cannot resume the dm-crypt device\n");
994 goto errout;
995 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800996
Paul Crowley5afbc622017-11-27 09:42:17 -0800997 /* We made it here with no errors. Woot! */
998 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800999
1000errout:
1001 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1002
1003 return retval;
1004}
1005
Wei Wang4375f1b2017-02-24 17:43:01 -08001006static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001007{
1008 int fd;
1009 char buffer[DM_CRYPT_BUF_SIZE];
1010 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001011 int retval = -1;
1012
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001013 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001014 SLOGE("Cannot open device-mapper\n");
1015 goto errout;
1016 }
1017
1018 io = (struct dm_ioctl *) buffer;
1019
1020 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1021 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1022 SLOGE("Cannot remove dm-crypt device\n");
1023 goto errout;
1024 }
1025
1026 /* We made it here with no errors. Woot! */
1027 retval = 0;
1028
1029errout:
1030 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1031
1032 return retval;
1033
1034}
1035
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001036static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001037 unsigned char *ikey, void *params UNUSED)
1038{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001039 SLOGI("Using pbkdf2 for cryptfs KDF");
1040
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001041 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001042 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1043 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1044 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001045}
1046
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001047static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001048 unsigned char *ikey, void *params)
1049{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001050 SLOGI("Using scrypt for cryptfs KDF");
1051
Kenny Rootc4c70f12013-06-14 12:11:38 -07001052 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1053
1054 int N = 1 << ftr->N_factor;
1055 int r = 1 << ftr->r_factor;
1056 int p = 1 << ftr->p_factor;
1057
1058 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001059 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001060 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1061 salt, SALT_LEN, N, r, p, ikey,
1062 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001063
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001064 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001065}
1066
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001067static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1068 unsigned char *ikey, void *params)
1069{
1070 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1071
1072 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001073 size_t signature_size;
1074 unsigned char* signature;
1075 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1076
1077 int N = 1 << ftr->N_factor;
1078 int r = 1 << ftr->r_factor;
1079 int p = 1 << ftr->p_factor;
1080
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001081 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1082 salt, SALT_LEN, N, r, p, ikey,
1083 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001084
1085 if (rc) {
1086 SLOGE("scrypt failed");
1087 return -1;
1088 }
1089
Shawn Willdene17a9c42014-09-08 13:04:08 -06001090 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1091 &signature, &signature_size)) {
1092 SLOGE("Signing failed");
1093 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001094 }
1095
1096 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1097 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1098 free(signature);
1099
1100 if (rc) {
1101 SLOGE("scrypt failed");
1102 return -1;
1103 }
1104
1105 return 0;
1106}
1107
1108static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1109 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001110 unsigned char *encrypted_master_key,
1111 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001112{
1113 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1114 EVP_CIPHER_CTX e_ctx;
1115 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001116 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001117
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001118 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001119 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001120
1121 switch (crypt_ftr->kdf_type) {
1122 case KDF_SCRYPT_KEYMASTER:
1123 if (keymaster_create_key(crypt_ftr)) {
1124 SLOGE("keymaster_create_key failed");
1125 return -1;
1126 }
1127
1128 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1129 SLOGE("scrypt failed");
1130 return -1;
1131 }
1132 break;
1133
1134 case KDF_SCRYPT:
1135 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1136 SLOGE("scrypt failed");
1137 return -1;
1138 }
1139 break;
1140
1141 default:
1142 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001143 return -1;
1144 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001145
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001146 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001147 EVP_CIPHER_CTX_init(&e_ctx);
1148 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149 SLOGE("EVP_EncryptInit failed\n");
1150 return -1;
1151 }
1152 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001153
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001154 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001155 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001156 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 SLOGE("EVP_EncryptUpdate failed\n");
1158 return -1;
1159 }
Adam Langley889c4f12014-09-03 14:23:13 -07001160 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 SLOGE("EVP_EncryptFinal failed\n");
1162 return -1;
1163 }
1164
1165 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1166 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1167 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001168 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001169
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001170 /* Store the scrypt of the intermediate key, so we can validate if it's a
1171 password error or mount error when things go wrong.
1172 Note there's no need to check for errors, since if this is incorrect, we
1173 simply won't wipe userdata, which is the correct default behavior
1174 */
1175 int N = 1 << crypt_ftr->N_factor;
1176 int r = 1 << crypt_ftr->r_factor;
1177 int p = 1 << crypt_ftr->p_factor;
1178
1179 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1180 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1181 crypt_ftr->scrypted_intermediate_key,
1182 sizeof(crypt_ftr->scrypted_intermediate_key));
1183
1184 if (rc) {
1185 SLOGE("encrypt_master_key: crypto_scrypt failed");
1186 }
1187
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001188 EVP_CIPHER_CTX_cleanup(&e_ctx);
1189
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001190 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001191}
1192
Paul Lawrence731a7a22015-04-28 22:14:15 +00001193static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001194 unsigned char *encrypted_master_key,
1195 unsigned char *decrypted_master_key,
1196 kdf_func kdf, void *kdf_params,
1197 unsigned char** intermediate_key,
1198 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001199{
1200 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001201 EVP_CIPHER_CTX d_ctx;
1202 int decrypted_len, final_len;
1203
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001204 /* Turn the password into an intermediate key and IV that can decrypt the
1205 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001206 if (kdf(passwd, salt, ikey, kdf_params)) {
1207 SLOGE("kdf failed");
1208 return -1;
1209 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001210
1211 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001212 EVP_CIPHER_CTX_init(&d_ctx);
1213 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001214 return -1;
1215 }
1216 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1217 /* Decrypt the master key */
1218 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1219 encrypted_master_key, KEY_LEN_BYTES)) {
1220 return -1;
1221 }
Adam Langley889c4f12014-09-03 14:23:13 -07001222 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223 return -1;
1224 }
1225
1226 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1227 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001228 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001229
1230 /* Copy intermediate key if needed by params */
1231 if (intermediate_key && intermediate_key_size) {
1232 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001233 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001234 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1235 *intermediate_key_size = KEY_LEN_BYTES;
1236 }
1237 }
1238
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001239 EVP_CIPHER_CTX_cleanup(&d_ctx);
1240
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001241 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001242}
1243
Kenny Rootc4c70f12013-06-14 12:11:38 -07001244static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001245{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001246 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001247 *kdf = scrypt_keymaster;
1248 *kdf_params = ftr;
1249 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001250 *kdf = scrypt;
1251 *kdf_params = ftr;
1252 } else {
1253 *kdf = pbkdf2;
1254 *kdf_params = NULL;
1255 }
1256}
1257
Paul Lawrence731a7a22015-04-28 22:14:15 +00001258static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001259 struct crypt_mnt_ftr *crypt_ftr,
1260 unsigned char** intermediate_key,
1261 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001262{
1263 kdf_func kdf;
1264 void *kdf_params;
1265 int ret;
1266
1267 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001268 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1269 decrypted_master_key, kdf, kdf_params,
1270 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001271 if (ret != 0) {
1272 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001273 }
1274
1275 return ret;
1276}
1277
Wei Wang4375f1b2017-02-24 17:43:01 -08001278static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001279 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001280 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001281 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001282
1283 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001284 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001285 read(fd, key_buf, sizeof(key_buf));
1286 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001287 close(fd);
1288
1289 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001290 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001291}
1292
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001293int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294{
Greg Hackmann955653e2014-09-24 14:55:20 -07001295 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001296#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001297
1298 /* Now umount the tmpfs filesystem */
1299 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001300 if (umount(mountpoint) == 0) {
1301 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001303
1304 if (errno == EINVAL) {
1305 /* EINVAL is returned if the directory is not a mountpoint,
1306 * i.e. there is no filesystem mounted there. So just get out.
1307 */
1308 break;
1309 }
1310
1311 err = errno;
1312
1313 /* If allowed, be increasingly aggressive before the last two retries */
1314 if (kill) {
1315 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1316 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001317 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001318 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1319 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001320 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001321 }
1322 }
1323
1324 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001325 }
1326
1327 if (i < WAIT_UNMOUNT_COUNT) {
1328 SLOGD("unmounting %s succeeded\n", mountpoint);
1329 rc = 0;
1330 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001331 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001332 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001333 rc = -1;
1334 }
1335
1336 return rc;
1337}
1338
Wei Wang42e38102017-06-07 10:46:12 -07001339static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001340{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001341 // NOTE: post_fs_data results in init calling back around to vold, so all
1342 // callers to this method must be async
1343
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001344 /* Do the prep of the /data filesystem */
1345 property_set("vold.post_fs_data_done", "0");
1346 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001347 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001348
Ken Sumrallc5872692013-05-14 15:26:31 -07001349 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001350 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001351 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001352 std::chrono::seconds(15))) {
1353 /* We timed out to prep /data in time. Continue wait. */
1354 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001355 }
Wei Wang42e38102017-06-07 10:46:12 -07001356 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001357}
1358
Paul Lawrence74f29f12014-08-28 15:54:10 -07001359static void cryptfs_set_corrupt()
1360{
1361 // Mark the footer as bad
1362 struct crypt_mnt_ftr crypt_ftr;
1363 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1364 SLOGE("Failed to get crypto footer - panic");
1365 return;
1366 }
1367
1368 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1369 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1370 SLOGE("Failed to set crypto footer - panic");
1371 return;
1372 }
1373}
1374
1375static void cryptfs_trigger_restart_min_framework()
1376{
1377 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1378 SLOGE("Failed to mount tmpfs on data - panic");
1379 return;
1380 }
1381
1382 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1383 SLOGE("Failed to trigger post fs data - panic");
1384 return;
1385 }
1386
1387 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1388 SLOGE("Failed to trigger restart min framework - panic");
1389 return;
1390 }
1391}
1392
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001393/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001394static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001395{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001396 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001397 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001398 static int restart_successful = 0;
1399
1400 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001401 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001402 SLOGE("Encrypted filesystem not validated, aborting");
1403 return -1;
1404 }
1405
1406 if (restart_successful) {
1407 SLOGE("System already restarted with encrypted disk, aborting");
1408 return -1;
1409 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001410
Paul Lawrencef4faa572014-01-29 13:31:03 -08001411 if (restart_main) {
1412 /* Here is where we shut down the framework. The init scripts
1413 * start all services in one of three classes: core, main or late_start.
1414 * On boot, we start core and main. Now, we stop main, but not core,
1415 * as core includes vold and a few other really important things that
1416 * we need to keep running. Once main has stopped, we should be able
1417 * to umount the tmpfs /data, then mount the encrypted /data.
1418 * We then restart the class main, and also the class late_start.
1419 * At the moment, I've only put a few things in late_start that I know
1420 * are not needed to bring up the framework, and that also cause problems
1421 * with unmounting the tmpfs /data, but I hope to add add more services
1422 * to the late_start class as we optimize this to decrease the delay
1423 * till the user is asked for the password to the filesystem.
1424 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001425
Paul Lawrencef4faa572014-01-29 13:31:03 -08001426 /* The init files are setup to stop the class main when vold.decrypt is
1427 * set to trigger_reset_main.
1428 */
1429 property_set("vold.decrypt", "trigger_reset_main");
1430 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001431
Paul Lawrencef4faa572014-01-29 13:31:03 -08001432 /* Ugh, shutting down the framework is not synchronous, so until it
1433 * can be fixed, this horrible hack will wait a moment for it all to
1434 * shut down before proceeding. Without it, some devices cannot
1435 * restart the graphics services.
1436 */
1437 sleep(2);
1438 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001439
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001440 /* Now that the framework is shutdown, we should be able to umount()
1441 * the tmpfs filesystem, and mount the real one.
1442 */
1443
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001444 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1445 if (strlen(crypto_blkdev) == 0) {
1446 SLOGE("fs_crypto_blkdev not set\n");
1447 return -1;
1448 }
1449
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001450 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001451 /* If ro.crypto.readonly is set to 1, mount the decrypted
1452 * filesystem readonly. This is used when /data is mounted by
1453 * recovery mode.
1454 */
1455 char ro_prop[PROPERTY_VALUE_MAX];
1456 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001457 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001458 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001459 rec->flags |= MS_RDONLY;
1460 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001461
Ken Sumralle5032c42012-04-01 23:58:44 -07001462 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001463 int retries = RETRY_MOUNT_ATTEMPTS;
1464 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001465
1466 /*
1467 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1468 * partitions in the fsck domain.
1469 */
1470 if (setexeccon(secontextFsck())){
1471 SLOGE("Failed to setexeccon");
1472 return -1;
1473 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001474 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001475 crypto_blkdev, 0))
1476 != 0) {
1477 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1478 /* TODO: invoke something similar to
1479 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1480 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1481 SLOGI("Failed to mount %s because it is busy - waiting",
1482 crypto_blkdev);
1483 if (--retries) {
1484 sleep(RETRY_MOUNT_DELAY_SECONDS);
1485 } else {
1486 /* Let's hope that a reboot clears away whatever is keeping
1487 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001488 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001489 }
1490 } else {
1491 SLOGE("Failed to mount decrypted data");
1492 cryptfs_set_corrupt();
1493 cryptfs_trigger_restart_min_framework();
1494 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001495 if (setexeccon(NULL)) {
1496 SLOGE("Failed to setexeccon");
1497 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001498 return -1;
1499 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001500 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001501 if (setexeccon(NULL)) {
1502 SLOGE("Failed to setexeccon");
1503 return -1;
1504 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001505
Ken Sumralle5032c42012-04-01 23:58:44 -07001506 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001507 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001508 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001509
1510 /* startup service classes main and late_start */
1511 property_set("vold.decrypt", "trigger_restart_framework");
1512 SLOGD("Just triggered restart_framework\n");
1513
1514 /* Give it a few moments to get started */
1515 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001516 }
1517
Ken Sumrall0cc16632011-01-18 20:32:26 -08001518 if (rc == 0) {
1519 restart_successful = 1;
1520 }
1521
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001522 return rc;
1523}
1524
Paul Lawrencef4faa572014-01-29 13:31:03 -08001525int cryptfs_restart(void)
1526{
Paul Lawrence05335c32015-03-05 09:46:23 -08001527 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001528 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001529 SLOGE("cryptfs_restart not valid for file encryption:");
1530 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001531 }
1532
Paul Lawrencef4faa572014-01-29 13:31:03 -08001533 /* Call internal implementation forcing a restart of main service group */
1534 return cryptfs_restart_internal(1);
1535}
1536
Wei Wang4375f1b2017-02-24 17:43:01 -08001537static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001538{
1539 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001540 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001541 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001542
1543 property_get("ro.crypto.state", encrypted_state, "");
1544 if (strcmp(encrypted_state, "encrypted") ) {
1545 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001546 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001547 }
1548
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001549 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001550 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001551 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001552 }
1553
Ken Sumrall160b4d62013-04-22 12:15:39 -07001554 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001555 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001556
Ken Sumralle1a45852011-12-14 21:24:27 -08001557 /*
1558 * Only report this error if key_loc is a file and it exists.
1559 * If the device was never encrypted, and /data is not mountable for
1560 * some reason, returning 1 should prevent the UI from presenting the
1561 * a "enter password" screen, or worse, a "press button to wipe the
1562 * device" screen.
1563 */
1564 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1565 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001566 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001567 } else {
1568 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001569 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001570 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001571 }
1572
Paul Lawrence74f29f12014-08-28 15:54:10 -07001573 // Test for possible error flags
1574 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1575 SLOGE("Encryption process is partway completed\n");
1576 return CRYPTO_COMPLETE_PARTIAL;
1577 }
1578
1579 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1580 SLOGE("Encryption process was interrupted but cannot continue\n");
1581 return CRYPTO_COMPLETE_INCONSISTENT;
1582 }
1583
1584 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1585 SLOGE("Encryption is successful but data is corrupt\n");
1586 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001587 }
1588
1589 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001590 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001591}
1592
Paul Lawrencef4faa572014-01-29 13:31:03 -08001593static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001594 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001595{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001597 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598 char crypto_blkdev[MAXPATHLEN];
1599 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001600 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001601 unsigned int orig_failed_decrypt_count;
1602 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001603 int use_keymaster = 0;
1604 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001605 unsigned char* intermediate_key = 0;
1606 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001607 int N = 1 << crypt_ftr->N_factor;
1608 int r = 1 << crypt_ftr->r_factor;
1609 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001610
Paul Lawrencef4faa572014-01-29 13:31:03 -08001611 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1612 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001613
Paul Lawrencef4faa572014-01-29 13:31:03 -08001614 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001615 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1616 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001617 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001618 rc = -1;
1619 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001620 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001621 }
1622
Paul Crowleye2ee1522017-09-26 14:05:26 -07001623 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001624
Paul Lawrence74f29f12014-08-28 15:54:10 -07001625 // Create crypto block device - all (non fatal) code paths
1626 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001627 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1628 SLOGE("Error creating decrypted block device\n");
1629 rc = -1;
1630 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001631 }
1632
Paul Lawrence74f29f12014-08-28 15:54:10 -07001633 /* Work out if the problem is the password or the data */
1634 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1635 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001636
Paul Lawrence74f29f12014-08-28 15:54:10 -07001637 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1638 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1639 N, r, p, scrypted_intermediate_key,
1640 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001641
Paul Lawrence74f29f12014-08-28 15:54:10 -07001642 // Does the key match the crypto footer?
1643 if (rc == 0 && memcmp(scrypted_intermediate_key,
1644 crypt_ftr->scrypted_intermediate_key,
1645 sizeof(scrypted_intermediate_key)) == 0) {
1646 SLOGI("Password matches");
1647 rc = 0;
1648 } else {
1649 /* Try mounting the file system anyway, just in case the problem's with
1650 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001651 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1652 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001653 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001654 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001655 SLOGE("Error temp mounting decrypted block device\n");
1656 delete_crypto_blk_dev(label);
1657
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001658 rc = ++crypt_ftr->failed_decrypt_count;
1659 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001660 } else {
1661 /* Success! */
1662 SLOGI("Password did not match but decrypted drive mounted - continue");
1663 umount(tmp_mount_point);
1664 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001665 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001666 }
1667
1668 if (rc == 0) {
1669 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001670 if (orig_failed_decrypt_count != 0) {
1671 put_crypt_ftr_and_key(crypt_ftr);
1672 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001673
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001674 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001675 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001676 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001677
1678 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001679 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001680 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001681 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001682 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001683 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001684 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001685
Paul Lawrence74f29f12014-08-28 15:54:10 -07001686 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001687 use_keymaster = keymaster_check_compatibility();
1688 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001689 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001690 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1691 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1692 upgrade = 1;
1693 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001694 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001695 upgrade = 1;
1696 }
1697
1698 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001699 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1700 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001701 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001702 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001703 }
1704 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001705
1706 // Do not fail even if upgrade failed - machine is bootable
1707 // Note that if this code is ever hit, there is a *serious* problem
1708 // since KDFs should never fail. You *must* fix the kdf before
1709 // proceeding!
1710 if (rc) {
1711 SLOGW("Upgrade failed with error %d,"
1712 " but continuing with previous state",
1713 rc);
1714 rc = 0;
1715 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001716 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717 }
1718
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001719 errout:
1720 if (intermediate_key) {
1721 memset(intermediate_key, 0, intermediate_key_size);
1722 free(intermediate_key);
1723 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724 return rc;
1725}
1726
Ken Sumrall29d8da82011-05-18 17:20:07 -07001727/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001728 * Called by vold when it's asked to mount an encrypted external
1729 * storage volume. The incoming partition has no crypto header/footer,
1730 * as any metadata is been stored in a separate, small partition.
1731 *
1732 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001733 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001734int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1735 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001736 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001737 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001738 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001739 return -1;
1740 }
1741
1742 unsigned long nr_sec = 0;
1743 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001744 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001745
Ken Sumrall29d8da82011-05-18 17:20:07 -07001746 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001747 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001748 return -1;
1749 }
1750
Jeff Sharkey9c484982015-03-31 10:35:33 -07001751 struct crypt_mnt_ftr ext_crypt_ftr;
1752 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1753 ext_crypt_ftr.fs_size = nr_sec;
1754 ext_crypt_ftr.keysize = keysize;
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001755 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
1756 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001757
Paul Crowley5afbc622017-11-27 09:42:17 -08001758 return create_crypto_blk_dev(
1759 &ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label,
1760 e4crypt_is_native() ? CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE : 0);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001761}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001762
Jeff Sharkey9c484982015-03-31 10:35:33 -07001763/*
1764 * Called by vold when it's asked to unmount an encrypted external
1765 * storage volume.
1766 */
1767int cryptfs_revert_ext_volume(const char* label) {
1768 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001769}
1770
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001771int cryptfs_crypto_complete(void)
1772{
1773 return do_crypto_complete("/data");
1774}
1775
Paul Lawrencef4faa572014-01-29 13:31:03 -08001776int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1777{
1778 char encrypted_state[PROPERTY_VALUE_MAX];
1779 property_get("ro.crypto.state", encrypted_state, "");
1780 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1781 SLOGE("encrypted fs already validated or not running with encryption,"
1782 " aborting");
1783 return -1;
1784 }
1785
1786 if (get_crypt_ftr_and_key(crypt_ftr)) {
1787 SLOGE("Error getting crypt footer and key");
1788 return -1;
1789 }
1790
1791 return 0;
1792}
1793
Wei Wang4375f1b2017-02-24 17:43:01 -08001794int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001795{
Paul Lawrence05335c32015-03-05 09:46:23 -08001796 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001797 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001798 SLOGE("cryptfs_check_passwd not valid for file encryption");
1799 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001800 }
1801
Paul Lawrencef4faa572014-01-29 13:31:03 -08001802 struct crypt_mnt_ftr crypt_ftr;
1803 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001804
Paul Lawrencef4faa572014-01-29 13:31:03 -08001805 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001806 if (rc) {
1807 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001808 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001809 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001810
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001811 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001812 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1813 if (rc) {
1814 SLOGE("Password did not match");
1815 return rc;
1816 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001817
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001818 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1819 // Here we have a default actual password but a real password
1820 // we must test against the scrypted value
1821 // First, we must delete the crypto block device that
1822 // test_mount_encrypted_fs leaves behind as a side effect
1823 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1824 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1825 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1826 if (rc) {
1827 SLOGE("Default password did not match on reboot encryption");
1828 return rc;
1829 }
1830
1831 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1832 put_crypt_ftr_and_key(&crypt_ftr);
1833 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1834 if (rc) {
1835 SLOGE("Could not change password on reboot encryption");
1836 return rc;
1837 }
1838 }
1839
1840 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001841 cryptfs_clear_password();
1842 password = strdup(passwd);
1843 struct timespec now;
1844 clock_gettime(CLOCK_BOOTTIME, &now);
1845 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001846 }
1847
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001848 return rc;
1849}
1850
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001851int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001852{
1853 struct crypt_mnt_ftr crypt_ftr;
1854 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001855 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001856 char encrypted_state[PROPERTY_VALUE_MAX];
1857 int rc;
1858
1859 property_get("ro.crypto.state", encrypted_state, "");
1860 if (strcmp(encrypted_state, "encrypted") ) {
1861 SLOGE("device not encrypted, aborting");
1862 return -2;
1863 }
1864
1865 if (!master_key_saved) {
1866 SLOGE("encrypted fs not yet mounted, aborting");
1867 return -1;
1868 }
1869
1870 if (!saved_mount_point) {
1871 SLOGE("encrypted fs failed to save mount point, aborting");
1872 return -1;
1873 }
1874
Ken Sumrall160b4d62013-04-22 12:15:39 -07001875 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001876 SLOGE("Error getting crypt footer and key\n");
1877 return -1;
1878 }
1879
1880 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1881 /* If the device has no password, then just say the password is valid */
1882 rc = 0;
1883 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001884 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001885 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1886 /* They match, the password is correct */
1887 rc = 0;
1888 } else {
1889 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1890 sleep(1);
1891 rc = 1;
1892 }
1893 }
1894
1895 return rc;
1896}
1897
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001898/* Initialize a crypt_mnt_ftr structure. The keysize is
1899 * defaulted to 16 bytes, and the filesystem size to 0.
1900 * Presumably, at a minimum, the caller will update the
1901 * filesystem size and crypto_type_name after calling this function.
1902 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001903static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001904{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001905 off64_t off;
1906
1907 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001908 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001909 ftr->major_version = CURRENT_MAJOR_VERSION;
1910 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001911 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001912 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001913
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001914 switch (keymaster_check_compatibility()) {
1915 case 1:
1916 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1917 break;
1918
1919 case 0:
1920 ftr->kdf_type = KDF_SCRYPT;
1921 break;
1922
1923 default:
1924 SLOGE("keymaster_check_compatibility failed");
1925 return -1;
1926 }
1927
Kenny Rootc4c70f12013-06-14 12:11:38 -07001928 get_device_scrypt_params(ftr);
1929
Ken Sumrall160b4d62013-04-22 12:15:39 -07001930 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1931 if (get_crypt_ftr_info(NULL, &off) == 0) {
1932 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1933 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1934 ftr->persist_data_size;
1935 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001936
1937 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001938}
1939
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001940#define FRAMEWORK_BOOT_WAIT 60
1941
Paul Lawrence87999172014-02-20 12:21:31 -08001942static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1943{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001944 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001945 if (fd == -1) {
1946 SLOGE("Error opening file %s", filename);
1947 return -1;
1948 }
1949
1950 char block[CRYPT_INPLACE_BUFSIZE];
1951 memset(block, 0, sizeof(block));
1952 if (unix_read(fd, block, sizeof(block)) < 0) {
1953 SLOGE("Error reading file %s", filename);
1954 close(fd);
1955 return -1;
1956 }
1957
1958 close(fd);
1959
1960 SHA256_CTX c;
1961 SHA256_Init(&c);
1962 SHA256_Update(&c, block, sizeof(block));
1963 SHA256_Final(buf, &c);
1964
1965 return 0;
1966}
1967
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001968static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
1969 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08001970 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08001971 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001972
Paul Lawrence87999172014-02-20 12:21:31 -08001973 /* The size of the userdata partition, and add in the vold volumes below */
1974 tot_encryption_size = crypt_ftr->fs_size;
1975
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001976 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08001977 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08001978
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001979 if (rc == ENABLE_INPLACE_ERR_DEV) {
1980 /* Hack for b/17898962 */
1981 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
1982 cryptfs_reboot(RebootType::reboot);
1983 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07001984
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001985 if (!rc) {
1986 crypt_ftr->encrypted_upto = cur_encryption_done;
1987 }
Paul Lawrence87999172014-02-20 12:21:31 -08001988
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001989 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
1990 /* The inplace routine never actually sets the progress to 100% due
1991 * to the round down nature of integer division, so set it here */
1992 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08001993 }
1994
1995 return rc;
1996}
1997
Paul Crowleyb64933a2017-10-31 08:25:55 -07001998static int vold_unmountAll(void) {
1999 VolumeManager* vm = VolumeManager::Instance();
2000 return vm->unmountAll();
2001}
2002
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002003int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002004 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002005 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002006 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002007 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002008 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002009 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002010 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002011 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002012 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002013 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002014 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002015 bool onlyCreateHeader = false;
2016 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002017
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002018 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002019 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2020 /* An encryption was underway and was interrupted */
2021 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2022 crypt_ftr.encrypted_upto = 0;
2023 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002024
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002025 /* At this point, we are in an inconsistent state. Until we successfully
2026 complete encryption, a reboot will leave us broken. So mark the
2027 encryption failed in case that happens.
2028 On successfully completing encryption, remove this flag */
2029 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002030
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002031 put_crypt_ftr_and_key(&crypt_ftr);
2032 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2033 if (!check_ftr_sha(&crypt_ftr)) {
2034 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2035 put_crypt_ftr_and_key(&crypt_ftr);
2036 goto error_unencrypted;
2037 }
2038
2039 /* Doing a reboot-encryption*/
2040 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2041 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2042 rebootEncryption = true;
2043 }
Paul Lawrence87999172014-02-20 12:21:31 -08002044 }
2045
2046 property_get("ro.crypto.state", encrypted_state, "");
2047 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2048 SLOGE("Device is already running encrypted, aborting");
2049 goto error_unencrypted;
2050 }
2051
2052 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002053 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2054 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002055
Ken Sumrall3ed82362011-01-28 23:31:16 -08002056 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002057 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002058 if (fd == -1) {
2059 SLOGE("Cannot open block device %s\n", real_blkdev);
2060 goto error_unencrypted;
2061 }
2062 unsigned long nr_sec;
2063 get_blkdev_size(fd, &nr_sec);
2064 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002065 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2066 goto error_unencrypted;
2067 }
2068 close(fd);
2069
2070 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002071 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002072 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002073 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002074 if (fs_size_sec == 0)
2075 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2076
Paul Lawrence87999172014-02-20 12:21:31 -08002077 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002078
2079 if (fs_size_sec > max_fs_size_sec) {
2080 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2081 goto error_unencrypted;
2082 }
2083 }
2084
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002085 /* Get a wakelock as this may take a while, and we don't want the
2086 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2087 * wants to keep the screen on, it can grab a full wakelock.
2088 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002089 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002090 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2091
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002092 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002093 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002094 */
2095 property_set("vold.decrypt", "trigger_shutdown_framework");
2096 SLOGD("Just asked init to shut down class main\n");
2097
Jeff Sharkey9c484982015-03-31 10:35:33 -07002098 /* Ask vold to unmount all devices that it manages */
2099 if (vold_unmountAll()) {
2100 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002101 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002102
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002103 /* no_ui means we are being called from init, not settings.
2104 Now we always reboot from settings, so !no_ui means reboot
2105 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002106 if (!no_ui) {
2107 /* Try fallback, which is to reboot and try there */
2108 onlyCreateHeader = true;
2109 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2110 if (breadcrumb == 0) {
2111 SLOGE("Failed to create breadcrumb file");
2112 goto error_shutting_down;
2113 }
2114 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002115 }
2116
2117 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002118 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002119 /* Now that /data is unmounted, we need to mount a tmpfs
2120 * /data, set a property saying we're doing inplace encryption,
2121 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002122 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002123 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002124 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002125 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002126 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002127 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002128
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002129 /* restart the framework. */
2130 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002131 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002132
Ken Sumrall92736ef2012-10-17 20:57:14 -07002133 /* Ugh, shutting down the framework is not synchronous, so until it
2134 * can be fixed, this horrible hack will wait a moment for it all to
2135 * shut down before proceeding. Without it, some devices cannot
2136 * restart the graphics services.
2137 */
2138 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002139 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002140
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002141 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002142 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002143 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002144 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2145 goto error_shutting_down;
2146 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002147
Paul Lawrence87999172014-02-20 12:21:31 -08002148 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2149 crypt_ftr.fs_size = nr_sec
2150 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2151 } else {
2152 crypt_ftr.fs_size = nr_sec;
2153 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002154 /* At this point, we are in an inconsistent state. Until we successfully
2155 complete encryption, a reboot will leave us broken. So mark the
2156 encryption failed in case that happens.
2157 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002158 if (onlyCreateHeader) {
2159 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2160 } else {
2161 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2162 }
Paul Lawrence87999172014-02-20 12:21:31 -08002163 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002164 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002165
Paul Lawrence87999172014-02-20 12:21:31 -08002166 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002167 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2168 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002169 SLOGE("Cannot create encrypted master key\n");
2170 goto error_shutting_down;
2171 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002172
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002173 /* Replace scrypted intermediate key if we are preparing for a reboot */
2174 if (onlyCreateHeader) {
2175 unsigned char fake_master_key[KEY_LEN_BYTES];
2176 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2177 memset(fake_master_key, 0, sizeof(fake_master_key));
2178 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2179 encrypted_fake_master_key, &crypt_ftr);
2180 }
2181
Paul Lawrence87999172014-02-20 12:21:31 -08002182 /* Write the key to the end of the partition */
2183 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002184
Paul Lawrence87999172014-02-20 12:21:31 -08002185 /* If any persistent data has been remembered, save it.
2186 * If none, create a valid empty table and save that.
2187 */
2188 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002189 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002190 if (pdata) {
2191 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2192 persist_data = pdata;
2193 }
2194 }
2195 if (persist_data) {
2196 save_persistent_data();
2197 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002198 }
2199
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002200 if (onlyCreateHeader) {
2201 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002202 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002203 }
2204
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002205 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002206 /* startup service classes main and late_start */
2207 property_set("vold.decrypt", "trigger_restart_min_framework");
2208 SLOGD("Just triggered restart_min_framework\n");
2209
2210 /* OK, the framework is restarted and will soon be showing a
2211 * progress bar. Time to setup an encrypted mapping, and
2212 * either write a new filesystem, or encrypt in place updating
2213 * the progress bar as we work.
2214 */
2215 }
2216
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002217 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002218 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002219 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002220
Paul Lawrence87999172014-02-20 12:21:31 -08002221 /* If we are continuing, check checksums match */
2222 rc = 0;
2223 if (previously_encrypted_upto) {
2224 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2225 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002226
Paul Lawrence87999172014-02-20 12:21:31 -08002227 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2228 sizeof(hash_first_block)) != 0) {
2229 SLOGE("Checksums do not match - trigger wipe");
2230 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002231 }
2232 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002233
Paul Lawrence87999172014-02-20 12:21:31 -08002234 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002235 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002236 previously_encrypted_upto);
2237 }
2238
2239 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002240 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002241 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2242 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002243 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002244 SLOGE("Error calculating checksum for continuing encryption");
2245 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002246 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002247 }
2248
2249 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002250 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002251
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002252 if (! rc) {
2253 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002254 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002255
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002256 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002257 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2258 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002259 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002260 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002261
Paul Lawrence6bfed202014-07-28 12:47:22 -07002262 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002263
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002264 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2265 char value[PROPERTY_VALUE_MAX];
2266 property_get("ro.crypto.state", value, "");
2267 if (!strcmp(value, "")) {
2268 /* default encryption - continue first boot sequence */
2269 property_set("ro.crypto.state", "encrypted");
2270 property_set("ro.crypto.type", "block");
2271 release_wake_lock(lockid);
2272 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2273 // Bring up cryptkeeper that will check the password and set it
2274 property_set("vold.decrypt", "trigger_shutdown_framework");
2275 sleep(2);
2276 property_set("vold.encrypt_progress", "");
2277 cryptfs_trigger_restart_min_framework();
2278 } else {
2279 cryptfs_check_passwd(DEFAULT_PASSWORD);
2280 cryptfs_restart_internal(1);
2281 }
2282 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002283 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002284 sleep(2); /* Give the UI a chance to show 100% progress */
2285 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002286 }
Paul Lawrence87999172014-02-20 12:21:31 -08002287 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002288 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002289 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002290 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002291 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002292 char value[PROPERTY_VALUE_MAX];
2293
Ken Sumrall319369a2012-06-27 16:30:18 -07002294 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002295 if (!strcmp(value, "1")) {
2296 /* wipe data if encryption failed */
2297 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002298 std::string err;
2299 const std::vector<std::string> options = {
2300 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2301 };
2302 if (!write_bootloader_message(options, &err)) {
2303 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002304 }
Josh Gaofec44372017-08-28 13:22:55 -07002305 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002306 } else {
2307 /* set property to trigger dialog */
2308 property_set("vold.encrypt_progress", "error_partially_encrypted");
2309 release_wake_lock(lockid);
2310 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002311 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002312 }
2313
Ken Sumrall3ed82362011-01-28 23:31:16 -08002314 /* hrm, the encrypt step claims success, but the reboot failed.
2315 * This should not happen.
2316 * Set the property and return. Hope the framework can deal with it.
2317 */
2318 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002319 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002320 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002321
2322error_unencrypted:
2323 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002324 if (lockid[0]) {
2325 release_wake_lock(lockid);
2326 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002327 return -1;
2328
2329error_shutting_down:
2330 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2331 * but the framework is stopped and not restarted to show the error, so it's up to
2332 * vold to restart the system.
2333 */
2334 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002335 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002336
2337 /* shouldn't get here */
2338 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002339 if (lockid[0]) {
2340 release_wake_lock(lockid);
2341 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002342 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002343}
2344
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002345int cryptfs_enable(int type, const char* passwd, int no_ui) {
2346 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002347}
2348
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002349int cryptfs_enable_default(int no_ui) {
2350 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002351}
2352
2353int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002354{
Paul Crowley38132a12016-02-09 09:50:32 +00002355 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002356 SLOGE("cryptfs_changepw not valid for file encryption");
2357 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002358 }
2359
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002360 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002361 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002362
2363 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002364 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002365 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002366 return -1;
2367 }
2368
Paul Lawrencef4faa572014-01-29 13:31:03 -08002369 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2370 SLOGE("Invalid crypt_type %d", crypt_type);
2371 return -1;
2372 }
2373
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002374 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002375 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002376 SLOGE("Error getting crypt footer and key");
2377 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002378 }
2379
Paul Lawrencef4faa572014-01-29 13:31:03 -08002380 crypt_ftr.crypt_type = crypt_type;
2381
JP Abgrall933216c2015-02-11 13:44:32 -08002382 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002383 : newpw,
2384 crypt_ftr.salt,
2385 saved_master_key,
2386 crypt_ftr.master_key,
2387 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002388 if (rc) {
2389 SLOGE("Encrypt master key failed: %d", rc);
2390 return -1;
2391 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002392 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002393 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002394
2395 return 0;
2396}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002397
Rubin Xu85c01f92014-10-13 12:49:54 +01002398static unsigned int persist_get_max_entries(int encrypted) {
2399 struct crypt_mnt_ftr crypt_ftr;
2400 unsigned int dsize;
2401 unsigned int max_persistent_entries;
2402
2403 /* If encrypted, use the values from the crypt_ftr, otherwise
2404 * use the values for the current spec.
2405 */
2406 if (encrypted) {
2407 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2408 return -1;
2409 }
2410 dsize = crypt_ftr.persist_data_size;
2411 } else {
2412 dsize = CRYPT_PERSIST_DATA_SIZE;
2413 }
2414
2415 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2416 sizeof(struct crypt_persist_entry);
2417
2418 return max_persistent_entries;
2419}
2420
2421static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002422{
2423 unsigned int i;
2424
2425 if (persist_data == NULL) {
2426 return -1;
2427 }
2428 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2429 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2430 /* We found it! */
2431 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2432 return 0;
2433 }
2434 }
2435
2436 return -1;
2437}
2438
Rubin Xu85c01f92014-10-13 12:49:54 +01002439static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002440{
2441 unsigned int i;
2442 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002443 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002444
2445 if (persist_data == NULL) {
2446 return -1;
2447 }
2448
Rubin Xu85c01f92014-10-13 12:49:54 +01002449 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002450
2451 num = persist_data->persist_valid_entries;
2452
2453 for (i = 0; i < num; i++) {
2454 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2455 /* We found an existing entry, update it! */
2456 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2457 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2458 return 0;
2459 }
2460 }
2461
2462 /* We didn't find it, add it to the end, if there is room */
2463 if (persist_data->persist_valid_entries < max_persistent_entries) {
2464 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2465 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2466 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2467 persist_data->persist_valid_entries++;
2468 return 0;
2469 }
2470
2471 return -1;
2472}
2473
Rubin Xu85c01f92014-10-13 12:49:54 +01002474/**
2475 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2476 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2477 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002478int match_multi_entry(const char *key, const char *field, unsigned index) {
2479 std::string key_ = key;
2480 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002481
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002482 std::string parsed_field;
2483 unsigned parsed_index;
2484
2485 std::string::size_type split = key_.find_last_of('_');
2486 if (split == std::string::npos) {
2487 parsed_field = key_;
2488 parsed_index = 0;
2489 } else {
2490 parsed_field = key_.substr(0, split);
2491 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002492 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002493
2494 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002495}
2496
2497/*
2498 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2499 * remaining entries starting from index will be deleted.
2500 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2501 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2502 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2503 *
2504 */
2505static int persist_del_keys(const char *fieldname, unsigned index)
2506{
2507 unsigned int i;
2508 unsigned int j;
2509 unsigned int num;
2510
2511 if (persist_data == NULL) {
2512 return PERSIST_DEL_KEY_ERROR_OTHER;
2513 }
2514
2515 num = persist_data->persist_valid_entries;
2516
2517 j = 0; // points to the end of non-deleted entries.
2518 // Filter out to-be-deleted entries in place.
2519 for (i = 0; i < num; i++) {
2520 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2521 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2522 j++;
2523 }
2524 }
2525
2526 if (j < num) {
2527 persist_data->persist_valid_entries = j;
2528 // Zeroise the remaining entries
2529 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2530 return PERSIST_DEL_KEY_OK;
2531 } else {
2532 // Did not find an entry matching the given fieldname
2533 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2534 }
2535}
2536
2537static int persist_count_keys(const char *fieldname)
2538{
2539 unsigned int i;
2540 unsigned int count;
2541
2542 if (persist_data == NULL) {
2543 return -1;
2544 }
2545
2546 count = 0;
2547 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2548 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2549 count++;
2550 }
2551 }
2552
2553 return count;
2554}
2555
Ken Sumrall160b4d62013-04-22 12:15:39 -07002556/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002557int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002558{
Paul Crowley38132a12016-02-09 09:50:32 +00002559 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002560 SLOGE("Cannot get field when file encrypted");
2561 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002562 }
2563
Ken Sumrall160b4d62013-04-22 12:15:39 -07002564 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002565 /* CRYPTO_GETFIELD_OK is success,
2566 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2567 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2568 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002569 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002570 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2571 int i;
2572 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002573
2574 if (persist_data == NULL) {
2575 load_persistent_data();
2576 if (persist_data == NULL) {
2577 SLOGE("Getfield error, cannot load persistent data");
2578 goto out;
2579 }
2580 }
2581
Rubin Xu85c01f92014-10-13 12:49:54 +01002582 // Read value from persistent entries. If the original value is split into multiple entries,
2583 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002584 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002585 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2586 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2587 // value too small
2588 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2589 goto out;
2590 }
2591 rc = CRYPTO_GETFIELD_OK;
2592
2593 for (i = 1; /* break explicitly */; i++) {
2594 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2595 (int) sizeof(temp_field)) {
2596 // If the fieldname is very long, we stop as soon as it begins to overflow the
2597 // maximum field length. At this point we have in fact fully read out the original
2598 // value because cryptfs_setfield would not allow fields with longer names to be
2599 // written in the first place.
2600 break;
2601 }
2602 if (!persist_get_key(temp_field, temp_value)) {
2603 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2604 // value too small.
2605 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2606 goto out;
2607 }
2608 } else {
2609 // Exhaust all entries.
2610 break;
2611 }
2612 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002613 } else {
2614 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002615 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002616 }
2617
2618out:
2619 return rc;
2620}
2621
2622/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002623int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002624{
Paul Crowley38132a12016-02-09 09:50:32 +00002625 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002626 SLOGE("Cannot set field when file encrypted");
2627 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002628 }
2629
Ken Sumrall160b4d62013-04-22 12:15:39 -07002630 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002631 /* 0 is success, negative values are error */
2632 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002633 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002634 unsigned int field_id;
2635 char temp_field[PROPERTY_KEY_MAX];
2636 unsigned int num_entries;
2637 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002638
2639 if (persist_data == NULL) {
2640 load_persistent_data();
2641 if (persist_data == NULL) {
2642 SLOGE("Setfield error, cannot load persistent data");
2643 goto out;
2644 }
2645 }
2646
2647 property_get("ro.crypto.state", encrypted_state, "");
2648 if (!strcmp(encrypted_state, "encrypted") ) {
2649 encrypted = 1;
2650 }
2651
Rubin Xu85c01f92014-10-13 12:49:54 +01002652 // Compute the number of entries required to store value, each entry can store up to
2653 // (PROPERTY_VALUE_MAX - 1) chars
2654 if (strlen(value) == 0) {
2655 // Empty value also needs one entry to store.
2656 num_entries = 1;
2657 } else {
2658 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2659 }
2660
2661 max_keylen = strlen(fieldname);
2662 if (num_entries > 1) {
2663 // Need an extra "_%d" suffix.
2664 max_keylen += 1 + log10(num_entries);
2665 }
2666 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2667 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002668 goto out;
2669 }
2670
Rubin Xu85c01f92014-10-13 12:49:54 +01002671 // Make sure we have enough space to write the new value
2672 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2673 persist_get_max_entries(encrypted)) {
2674 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2675 goto out;
2676 }
2677
2678 // Now that we know persist_data has enough space for value, let's delete the old field first
2679 // to make up space.
2680 persist_del_keys(fieldname, 0);
2681
2682 if (persist_set_key(fieldname, value, encrypted)) {
2683 // fail to set key, should not happen as we have already checked the available space
2684 SLOGE("persist_set_key() error during setfield()");
2685 goto out;
2686 }
2687
2688 for (field_id = 1; field_id < num_entries; field_id++) {
2689 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
2690
2691 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2692 // fail to set key, should not happen as we have already checked the available space.
2693 SLOGE("persist_set_key() error during setfield()");
2694 goto out;
2695 }
2696 }
2697
Ken Sumrall160b4d62013-04-22 12:15:39 -07002698 /* If we are running encrypted, save the persistent data now */
2699 if (encrypted) {
2700 if (save_persistent_data()) {
2701 SLOGE("Setfield error, cannot save persistent data");
2702 goto out;
2703 }
2704 }
2705
Rubin Xu85c01f92014-10-13 12:49:54 +01002706 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002707
2708out:
2709 return rc;
2710}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002711
2712/* Checks userdata. Attempt to mount the volume if default-
2713 * encrypted.
2714 * On success trigger next init phase and return 0.
2715 * Currently do not handle failure - see TODO below.
2716 */
2717int cryptfs_mount_default_encrypted(void)
2718{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002719 int crypt_type = cryptfs_get_password_type();
2720 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2721 SLOGE("Bad crypt type - error");
2722 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2723 SLOGD("Password is not default - "
2724 "starting min framework to prompt");
2725 property_set("vold.decrypt", "trigger_restart_min_framework");
2726 return 0;
2727 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2728 SLOGD("Password is default - restarting filesystem");
2729 cryptfs_restart_internal(0);
2730 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002731 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002732 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002733 }
2734
Paul Lawrence6bfed202014-07-28 12:47:22 -07002735 /** Corrupt. Allow us to boot into framework, which will detect bad
2736 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002737 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002738 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002739 return 0;
2740}
2741
2742/* Returns type of the password, default, pattern, pin or password.
2743 */
2744int cryptfs_get_password_type(void)
2745{
Paul Crowley38132a12016-02-09 09:50:32 +00002746 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002747 SLOGE("cryptfs_get_password_type not valid for file encryption");
2748 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002749 }
2750
Paul Lawrencef4faa572014-01-29 13:31:03 -08002751 struct crypt_mnt_ftr crypt_ftr;
2752
2753 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2754 SLOGE("Error getting crypt footer and key\n");
2755 return -1;
2756 }
2757
Paul Lawrence6bfed202014-07-28 12:47:22 -07002758 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2759 return -1;
2760 }
2761
Paul Lawrencef4faa572014-01-29 13:31:03 -08002762 return crypt_ftr.crypt_type;
2763}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002764
Paul Lawrence05335c32015-03-05 09:46:23 -08002765const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002766{
Paul Crowley38132a12016-02-09 09:50:32 +00002767 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002768 SLOGE("cryptfs_get_password not valid for file encryption");
2769 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002770 }
2771
Paul Lawrence399317e2014-03-10 13:20:50 -07002772 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002773 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002774 if (now.tv_sec < password_expiry_time) {
2775 return password;
2776 } else {
2777 cryptfs_clear_password();
2778 return 0;
2779 }
2780}
2781
2782void cryptfs_clear_password()
2783{
2784 if (password) {
2785 size_t len = strlen(password);
2786 memset(password, 0, len);
2787 free(password);
2788 password = 0;
2789 password_expiry_time = 0;
2790 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002791}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002792
Paul Lawrence0c247462015-10-29 10:30:57 -07002793int cryptfs_isConvertibleToFBE()
2794{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002795 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002796 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2797}