blob: 8ffe1a7ad0c2e5bbad3fa8db0cf2b0b056632046 [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 Lawrence3bd36d52015-06-09 13:37:44 -07001059 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1060 salt, SALT_LEN, N, r, p, ikey,
1061 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001062
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001063 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001064}
1065
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001066static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1067 unsigned char *ikey, void *params)
1068{
1069 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1070
1071 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001072 size_t signature_size;
1073 unsigned char* signature;
1074 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1075
1076 int N = 1 << ftr->N_factor;
1077 int r = 1 << ftr->r_factor;
1078 int p = 1 << ftr->p_factor;
1079
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001080 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1081 salt, SALT_LEN, N, r, p, ikey,
1082 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001083
1084 if (rc) {
1085 SLOGE("scrypt failed");
1086 return -1;
1087 }
1088
Shawn Willdene17a9c42014-09-08 13:04:08 -06001089 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1090 &signature, &signature_size)) {
1091 SLOGE("Signing failed");
1092 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001093 }
1094
1095 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1096 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1097 free(signature);
1098
1099 if (rc) {
1100 SLOGE("scrypt failed");
1101 return -1;
1102 }
1103
1104 return 0;
1105}
1106
1107static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1108 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001109 unsigned char *encrypted_master_key,
1110 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001111{
1112 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1113 EVP_CIPHER_CTX e_ctx;
1114 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001115 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001116
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001117 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001118 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001119
1120 switch (crypt_ftr->kdf_type) {
1121 case KDF_SCRYPT_KEYMASTER:
1122 if (keymaster_create_key(crypt_ftr)) {
1123 SLOGE("keymaster_create_key failed");
1124 return -1;
1125 }
1126
1127 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1128 SLOGE("scrypt failed");
1129 return -1;
1130 }
1131 break;
1132
1133 case KDF_SCRYPT:
1134 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1135 SLOGE("scrypt failed");
1136 return -1;
1137 }
1138 break;
1139
1140 default:
1141 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001142 return -1;
1143 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001144
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001145 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001146 EVP_CIPHER_CTX_init(&e_ctx);
1147 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001148 SLOGE("EVP_EncryptInit failed\n");
1149 return -1;
1150 }
1151 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001152
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001153 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001154 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001155 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 SLOGE("EVP_EncryptUpdate failed\n");
1157 return -1;
1158 }
Adam Langley889c4f12014-09-03 14:23:13 -07001159 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001160 SLOGE("EVP_EncryptFinal failed\n");
1161 return -1;
1162 }
1163
1164 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1165 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1166 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001167 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001168
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001169 /* Store the scrypt of the intermediate key, so we can validate if it's a
1170 password error or mount error when things go wrong.
1171 Note there's no need to check for errors, since if this is incorrect, we
1172 simply won't wipe userdata, which is the correct default behavior
1173 */
1174 int N = 1 << crypt_ftr->N_factor;
1175 int r = 1 << crypt_ftr->r_factor;
1176 int p = 1 << crypt_ftr->p_factor;
1177
1178 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1179 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1180 crypt_ftr->scrypted_intermediate_key,
1181 sizeof(crypt_ftr->scrypted_intermediate_key));
1182
1183 if (rc) {
1184 SLOGE("encrypt_master_key: crypto_scrypt failed");
1185 }
1186
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001187 EVP_CIPHER_CTX_cleanup(&e_ctx);
1188
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001189 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001190}
1191
Paul Lawrence731a7a22015-04-28 22:14:15 +00001192static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001193 unsigned char *encrypted_master_key,
1194 unsigned char *decrypted_master_key,
1195 kdf_func kdf, void *kdf_params,
1196 unsigned char** intermediate_key,
1197 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001198{
1199 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 -08001200 EVP_CIPHER_CTX d_ctx;
1201 int decrypted_len, final_len;
1202
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001203 /* Turn the password into an intermediate key and IV that can decrypt the
1204 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001205 if (kdf(passwd, salt, ikey, kdf_params)) {
1206 SLOGE("kdf failed");
1207 return -1;
1208 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001209
1210 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001211 EVP_CIPHER_CTX_init(&d_ctx);
1212 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001213 return -1;
1214 }
1215 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1216 /* Decrypt the master key */
1217 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1218 encrypted_master_key, KEY_LEN_BYTES)) {
1219 return -1;
1220 }
Adam Langley889c4f12014-09-03 14:23:13 -07001221 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001222 return -1;
1223 }
1224
1225 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1226 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001227 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001228
1229 /* Copy intermediate key if needed by params */
1230 if (intermediate_key && intermediate_key_size) {
1231 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001232 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001233 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1234 *intermediate_key_size = KEY_LEN_BYTES;
1235 }
1236 }
1237
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001238 EVP_CIPHER_CTX_cleanup(&d_ctx);
1239
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001240 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001241}
1242
Kenny Rootc4c70f12013-06-14 12:11:38 -07001243static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001244{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001245 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001246 *kdf = scrypt_keymaster;
1247 *kdf_params = ftr;
1248 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001249 *kdf = scrypt;
1250 *kdf_params = ftr;
1251 } else {
1252 *kdf = pbkdf2;
1253 *kdf_params = NULL;
1254 }
1255}
1256
Paul Lawrence731a7a22015-04-28 22:14:15 +00001257static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001258 struct crypt_mnt_ftr *crypt_ftr,
1259 unsigned char** intermediate_key,
1260 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001261{
1262 kdf_func kdf;
1263 void *kdf_params;
1264 int ret;
1265
1266 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001267 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1268 decrypted_master_key, kdf, kdf_params,
1269 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001270 if (ret != 0) {
1271 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001272 }
1273
1274 return ret;
1275}
1276
Wei Wang4375f1b2017-02-24 17:43:01 -08001277static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001278 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001279 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001280 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001281
1282 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001283 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001284 read(fd, key_buf, sizeof(key_buf));
1285 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001286 close(fd);
1287
1288 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001289 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001290}
1291
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001292int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001293{
Greg Hackmann955653e2014-09-24 14:55:20 -07001294 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001295#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001296
1297 /* Now umount the tmpfs filesystem */
1298 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001299 if (umount(mountpoint) == 0) {
1300 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001301 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001302
1303 if (errno == EINVAL) {
1304 /* EINVAL is returned if the directory is not a mountpoint,
1305 * i.e. there is no filesystem mounted there. So just get out.
1306 */
1307 break;
1308 }
1309
1310 err = errno;
1311
1312 /* If allowed, be increasingly aggressive before the last two retries */
1313 if (kill) {
1314 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1315 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001316 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001317 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1318 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001319 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001320 }
1321 }
1322
1323 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001324 }
1325
1326 if (i < WAIT_UNMOUNT_COUNT) {
1327 SLOGD("unmounting %s succeeded\n", mountpoint);
1328 rc = 0;
1329 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001330 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001331 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001332 rc = -1;
1333 }
1334
1335 return rc;
1336}
1337
Wei Wang42e38102017-06-07 10:46:12 -07001338static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001339{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001340 // NOTE: post_fs_data results in init calling back around to vold, so all
1341 // callers to this method must be async
1342
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001343 /* Do the prep of the /data filesystem */
1344 property_set("vold.post_fs_data_done", "0");
1345 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001346 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001347
Ken Sumrallc5872692013-05-14 15:26:31 -07001348 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001349 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001350 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001351 std::chrono::seconds(15))) {
1352 /* We timed out to prep /data in time. Continue wait. */
1353 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001354 }
Wei Wang42e38102017-06-07 10:46:12 -07001355 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001356}
1357
Paul Lawrence74f29f12014-08-28 15:54:10 -07001358static void cryptfs_set_corrupt()
1359{
1360 // Mark the footer as bad
1361 struct crypt_mnt_ftr crypt_ftr;
1362 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1363 SLOGE("Failed to get crypto footer - panic");
1364 return;
1365 }
1366
1367 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1368 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1369 SLOGE("Failed to set crypto footer - panic");
1370 return;
1371 }
1372}
1373
1374static void cryptfs_trigger_restart_min_framework()
1375{
1376 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1377 SLOGE("Failed to mount tmpfs on data - panic");
1378 return;
1379 }
1380
1381 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1382 SLOGE("Failed to trigger post fs data - panic");
1383 return;
1384 }
1385
1386 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1387 SLOGE("Failed to trigger restart min framework - panic");
1388 return;
1389 }
1390}
1391
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001392/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001393static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001394{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001395 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001396 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001397 static int restart_successful = 0;
1398
1399 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001400 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001401 SLOGE("Encrypted filesystem not validated, aborting");
1402 return -1;
1403 }
1404
1405 if (restart_successful) {
1406 SLOGE("System already restarted with encrypted disk, aborting");
1407 return -1;
1408 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001409
Paul Lawrencef4faa572014-01-29 13:31:03 -08001410 if (restart_main) {
1411 /* Here is where we shut down the framework. The init scripts
1412 * start all services in one of three classes: core, main or late_start.
1413 * On boot, we start core and main. Now, we stop main, but not core,
1414 * as core includes vold and a few other really important things that
1415 * we need to keep running. Once main has stopped, we should be able
1416 * to umount the tmpfs /data, then mount the encrypted /data.
1417 * We then restart the class main, and also the class late_start.
1418 * At the moment, I've only put a few things in late_start that I know
1419 * are not needed to bring up the framework, and that also cause problems
1420 * with unmounting the tmpfs /data, but I hope to add add more services
1421 * to the late_start class as we optimize this to decrease the delay
1422 * till the user is asked for the password to the filesystem.
1423 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001424
Paul Lawrencef4faa572014-01-29 13:31:03 -08001425 /* The init files are setup to stop the class main when vold.decrypt is
1426 * set to trigger_reset_main.
1427 */
1428 property_set("vold.decrypt", "trigger_reset_main");
1429 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430
Paul Lawrencef4faa572014-01-29 13:31:03 -08001431 /* Ugh, shutting down the framework is not synchronous, so until it
1432 * can be fixed, this horrible hack will wait a moment for it all to
1433 * shut down before proceeding. Without it, some devices cannot
1434 * restart the graphics services.
1435 */
1436 sleep(2);
1437 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001438
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001439 /* Now that the framework is shutdown, we should be able to umount()
1440 * the tmpfs filesystem, and mount the real one.
1441 */
1442
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001443 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1444 if (strlen(crypto_blkdev) == 0) {
1445 SLOGE("fs_crypto_blkdev not set\n");
1446 return -1;
1447 }
1448
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001449 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001450 /* If ro.crypto.readonly is set to 1, mount the decrypted
1451 * filesystem readonly. This is used when /data is mounted by
1452 * recovery mode.
1453 */
1454 char ro_prop[PROPERTY_VALUE_MAX];
1455 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001456 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001457 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001458 rec->flags |= MS_RDONLY;
1459 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001460
Ken Sumralle5032c42012-04-01 23:58:44 -07001461 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001462 int retries = RETRY_MOUNT_ATTEMPTS;
1463 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001464
1465 /*
1466 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1467 * partitions in the fsck domain.
1468 */
1469 if (setexeccon(secontextFsck())){
1470 SLOGE("Failed to setexeccon");
1471 return -1;
1472 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001473 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001474 crypto_blkdev, 0))
1475 != 0) {
1476 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1477 /* TODO: invoke something similar to
1478 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1479 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1480 SLOGI("Failed to mount %s because it is busy - waiting",
1481 crypto_blkdev);
1482 if (--retries) {
1483 sleep(RETRY_MOUNT_DELAY_SECONDS);
1484 } else {
1485 /* Let's hope that a reboot clears away whatever is keeping
1486 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001487 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001488 }
1489 } else {
1490 SLOGE("Failed to mount decrypted data");
1491 cryptfs_set_corrupt();
1492 cryptfs_trigger_restart_min_framework();
1493 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001494 if (setexeccon(NULL)) {
1495 SLOGE("Failed to setexeccon");
1496 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001497 return -1;
1498 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001499 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001500 if (setexeccon(NULL)) {
1501 SLOGE("Failed to setexeccon");
1502 return -1;
1503 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001504
Ken Sumralle5032c42012-04-01 23:58:44 -07001505 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001506 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001507 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001508
1509 /* startup service classes main and late_start */
1510 property_set("vold.decrypt", "trigger_restart_framework");
1511 SLOGD("Just triggered restart_framework\n");
1512
1513 /* Give it a few moments to get started */
1514 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001515 }
1516
Ken Sumrall0cc16632011-01-18 20:32:26 -08001517 if (rc == 0) {
1518 restart_successful = 1;
1519 }
1520
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521 return rc;
1522}
1523
Paul Lawrencef4faa572014-01-29 13:31:03 -08001524int cryptfs_restart(void)
1525{
Paul Lawrence05335c32015-03-05 09:46:23 -08001526 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001527 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001528 SLOGE("cryptfs_restart not valid for file encryption:");
1529 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001530 }
1531
Paul Lawrencef4faa572014-01-29 13:31:03 -08001532 /* Call internal implementation forcing a restart of main service group */
1533 return cryptfs_restart_internal(1);
1534}
1535
Wei Wang4375f1b2017-02-24 17:43:01 -08001536static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001537{
1538 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001539 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001540 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001541
1542 property_get("ro.crypto.state", encrypted_state, "");
1543 if (strcmp(encrypted_state, "encrypted") ) {
1544 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001545 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001546 }
1547
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001548 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001549 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001550 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001551 }
1552
Ken Sumrall160b4d62013-04-22 12:15:39 -07001553 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001554 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001555
Ken Sumralle1a45852011-12-14 21:24:27 -08001556 /*
1557 * Only report this error if key_loc is a file and it exists.
1558 * If the device was never encrypted, and /data is not mountable for
1559 * some reason, returning 1 should prevent the UI from presenting the
1560 * a "enter password" screen, or worse, a "press button to wipe the
1561 * device" screen.
1562 */
1563 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1564 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001565 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001566 } else {
1567 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001568 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001569 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001570 }
1571
Paul Lawrence74f29f12014-08-28 15:54:10 -07001572 // Test for possible error flags
1573 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1574 SLOGE("Encryption process is partway completed\n");
1575 return CRYPTO_COMPLETE_PARTIAL;
1576 }
1577
1578 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1579 SLOGE("Encryption process was interrupted but cannot continue\n");
1580 return CRYPTO_COMPLETE_INCONSISTENT;
1581 }
1582
1583 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1584 SLOGE("Encryption is successful but data is corrupt\n");
1585 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001586 }
1587
1588 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001589 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001590}
1591
Paul Lawrencef4faa572014-01-29 13:31:03 -08001592static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001593 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001594{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001595 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001596 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001597 char crypto_blkdev[MAXPATHLEN];
1598 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001599 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001600 unsigned int orig_failed_decrypt_count;
1601 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001602 int use_keymaster = 0;
1603 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001604 unsigned char* intermediate_key = 0;
1605 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001606 int N = 1 << crypt_ftr->N_factor;
1607 int r = 1 << crypt_ftr->r_factor;
1608 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001609
Paul Lawrencef4faa572014-01-29 13:31:03 -08001610 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1611 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001612
Paul Lawrencef4faa572014-01-29 13:31:03 -08001613 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001614 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1615 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001616 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001617 rc = -1;
1618 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001619 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001620 }
1621
Paul Crowleye2ee1522017-09-26 14:05:26 -07001622 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001623
Paul Lawrence74f29f12014-08-28 15:54:10 -07001624 // Create crypto block device - all (non fatal) code paths
1625 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001626 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1627 SLOGE("Error creating decrypted block device\n");
1628 rc = -1;
1629 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001630 }
1631
Paul Lawrence74f29f12014-08-28 15:54:10 -07001632 /* Work out if the problem is the password or the data */
1633 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1634 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001635
Paul Lawrence74f29f12014-08-28 15:54:10 -07001636 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1637 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1638 N, r, p, scrypted_intermediate_key,
1639 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001640
Paul Lawrence74f29f12014-08-28 15:54:10 -07001641 // Does the key match the crypto footer?
1642 if (rc == 0 && memcmp(scrypted_intermediate_key,
1643 crypt_ftr->scrypted_intermediate_key,
1644 sizeof(scrypted_intermediate_key)) == 0) {
1645 SLOGI("Password matches");
1646 rc = 0;
1647 } else {
1648 /* Try mounting the file system anyway, just in case the problem's with
1649 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001650 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1651 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001652 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001653 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001654 SLOGE("Error temp mounting decrypted block device\n");
1655 delete_crypto_blk_dev(label);
1656
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001657 rc = ++crypt_ftr->failed_decrypt_count;
1658 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001659 } else {
1660 /* Success! */
1661 SLOGI("Password did not match but decrypted drive mounted - continue");
1662 umount(tmp_mount_point);
1663 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001664 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001665 }
1666
1667 if (rc == 0) {
1668 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001669 if (orig_failed_decrypt_count != 0) {
1670 put_crypt_ftr_and_key(crypt_ftr);
1671 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001672
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001673 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001674 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001675 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001676
1677 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001678 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001679 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001680 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001681 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001682 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001683 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001684
Paul Lawrence74f29f12014-08-28 15:54:10 -07001685 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001686 use_keymaster = keymaster_check_compatibility();
1687 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001688 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001689 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1690 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1691 upgrade = 1;
1692 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001693 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001694 upgrade = 1;
1695 }
1696
1697 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001698 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1699 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001700 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001701 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001702 }
1703 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001704
1705 // Do not fail even if upgrade failed - machine is bootable
1706 // Note that if this code is ever hit, there is a *serious* problem
1707 // since KDFs should never fail. You *must* fix the kdf before
1708 // proceeding!
1709 if (rc) {
1710 SLOGW("Upgrade failed with error %d,"
1711 " but continuing with previous state",
1712 rc);
1713 rc = 0;
1714 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001715 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001716 }
1717
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001718 errout:
1719 if (intermediate_key) {
1720 memset(intermediate_key, 0, intermediate_key_size);
1721 free(intermediate_key);
1722 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001723 return rc;
1724}
1725
Ken Sumrall29d8da82011-05-18 17:20:07 -07001726/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001727 * Called by vold when it's asked to mount an encrypted external
1728 * storage volume. The incoming partition has no crypto header/footer,
1729 * as any metadata is been stored in a separate, small partition.
1730 *
1731 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001732 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001733int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1734 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001735 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001736 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001737 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001738 return -1;
1739 }
1740
1741 unsigned long nr_sec = 0;
1742 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001743 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001744
Ken Sumrall29d8da82011-05-18 17:20:07 -07001745 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001746 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001747 return -1;
1748 }
1749
Jeff Sharkey9c484982015-03-31 10:35:33 -07001750 struct crypt_mnt_ftr ext_crypt_ftr;
1751 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1752 ext_crypt_ftr.fs_size = nr_sec;
1753 ext_crypt_ftr.keysize = keysize;
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001754 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
1755 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001756
Paul Crowley5afbc622017-11-27 09:42:17 -08001757 return create_crypto_blk_dev(
1758 &ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label,
1759 e4crypt_is_native() ? CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE : 0);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001760}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001761
Jeff Sharkey9c484982015-03-31 10:35:33 -07001762/*
1763 * Called by vold when it's asked to unmount an encrypted external
1764 * storage volume.
1765 */
1766int cryptfs_revert_ext_volume(const char* label) {
1767 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001768}
1769
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001770int cryptfs_crypto_complete(void)
1771{
1772 return do_crypto_complete("/data");
1773}
1774
Paul Lawrencef4faa572014-01-29 13:31:03 -08001775int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1776{
1777 char encrypted_state[PROPERTY_VALUE_MAX];
1778 property_get("ro.crypto.state", encrypted_state, "");
1779 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1780 SLOGE("encrypted fs already validated or not running with encryption,"
1781 " aborting");
1782 return -1;
1783 }
1784
1785 if (get_crypt_ftr_and_key(crypt_ftr)) {
1786 SLOGE("Error getting crypt footer and key");
1787 return -1;
1788 }
1789
1790 return 0;
1791}
1792
Wei Wang4375f1b2017-02-24 17:43:01 -08001793int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001794{
Paul Lawrence05335c32015-03-05 09:46:23 -08001795 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001796 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001797 SLOGE("cryptfs_check_passwd not valid for file encryption");
1798 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001799 }
1800
Paul Lawrencef4faa572014-01-29 13:31:03 -08001801 struct crypt_mnt_ftr crypt_ftr;
1802 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001803
Paul Lawrencef4faa572014-01-29 13:31:03 -08001804 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001805 if (rc) {
1806 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001807 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001808 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001809
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001810 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001811 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1812 if (rc) {
1813 SLOGE("Password did not match");
1814 return rc;
1815 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001816
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001817 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1818 // Here we have a default actual password but a real password
1819 // we must test against the scrypted value
1820 // First, we must delete the crypto block device that
1821 // test_mount_encrypted_fs leaves behind as a side effect
1822 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1823 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1824 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1825 if (rc) {
1826 SLOGE("Default password did not match on reboot encryption");
1827 return rc;
1828 }
1829
1830 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1831 put_crypt_ftr_and_key(&crypt_ftr);
1832 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1833 if (rc) {
1834 SLOGE("Could not change password on reboot encryption");
1835 return rc;
1836 }
1837 }
1838
1839 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001840 cryptfs_clear_password();
1841 password = strdup(passwd);
1842 struct timespec now;
1843 clock_gettime(CLOCK_BOOTTIME, &now);
1844 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001845 }
1846
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001847 return rc;
1848}
1849
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001850int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001851{
1852 struct crypt_mnt_ftr crypt_ftr;
1853 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001854 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001855 char encrypted_state[PROPERTY_VALUE_MAX];
1856 int rc;
1857
1858 property_get("ro.crypto.state", encrypted_state, "");
1859 if (strcmp(encrypted_state, "encrypted") ) {
1860 SLOGE("device not encrypted, aborting");
1861 return -2;
1862 }
1863
1864 if (!master_key_saved) {
1865 SLOGE("encrypted fs not yet mounted, aborting");
1866 return -1;
1867 }
1868
1869 if (!saved_mount_point) {
1870 SLOGE("encrypted fs failed to save mount point, aborting");
1871 return -1;
1872 }
1873
Ken Sumrall160b4d62013-04-22 12:15:39 -07001874 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001875 SLOGE("Error getting crypt footer and key\n");
1876 return -1;
1877 }
1878
1879 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1880 /* If the device has no password, then just say the password is valid */
1881 rc = 0;
1882 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001883 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001884 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1885 /* They match, the password is correct */
1886 rc = 0;
1887 } else {
1888 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1889 sleep(1);
1890 rc = 1;
1891 }
1892 }
1893
1894 return rc;
1895}
1896
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001897/* Initialize a crypt_mnt_ftr structure. The keysize is
1898 * defaulted to 16 bytes, and the filesystem size to 0.
1899 * Presumably, at a minimum, the caller will update the
1900 * filesystem size and crypto_type_name after calling this function.
1901 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001902static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001904 off64_t off;
1905
1906 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001907 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001908 ftr->major_version = CURRENT_MAJOR_VERSION;
1909 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001910 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001911 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001912
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001913 switch (keymaster_check_compatibility()) {
1914 case 1:
1915 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1916 break;
1917
1918 case 0:
1919 ftr->kdf_type = KDF_SCRYPT;
1920 break;
1921
1922 default:
1923 SLOGE("keymaster_check_compatibility failed");
1924 return -1;
1925 }
1926
Kenny Rootc4c70f12013-06-14 12:11:38 -07001927 get_device_scrypt_params(ftr);
1928
Ken Sumrall160b4d62013-04-22 12:15:39 -07001929 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1930 if (get_crypt_ftr_info(NULL, &off) == 0) {
1931 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1932 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1933 ftr->persist_data_size;
1934 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001935
1936 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001937}
1938
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001939#define FRAMEWORK_BOOT_WAIT 60
1940
Paul Lawrence87999172014-02-20 12:21:31 -08001941static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1942{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001943 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001944 if (fd == -1) {
1945 SLOGE("Error opening file %s", filename);
1946 return -1;
1947 }
1948
1949 char block[CRYPT_INPLACE_BUFSIZE];
1950 memset(block, 0, sizeof(block));
1951 if (unix_read(fd, block, sizeof(block)) < 0) {
1952 SLOGE("Error reading file %s", filename);
1953 close(fd);
1954 return -1;
1955 }
1956
1957 close(fd);
1958
1959 SHA256_CTX c;
1960 SHA256_Init(&c);
1961 SHA256_Update(&c, block, sizeof(block));
1962 SHA256_Final(buf, &c);
1963
1964 return 0;
1965}
1966
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001967static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
1968 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08001969 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08001970 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001971
Paul Lawrence87999172014-02-20 12:21:31 -08001972 /* The size of the userdata partition, and add in the vold volumes below */
1973 tot_encryption_size = crypt_ftr->fs_size;
1974
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001975 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08001976 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08001977
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001978 if (rc == ENABLE_INPLACE_ERR_DEV) {
1979 /* Hack for b/17898962 */
1980 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
1981 cryptfs_reboot(RebootType::reboot);
1982 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07001983
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001984 if (!rc) {
1985 crypt_ftr->encrypted_upto = cur_encryption_done;
1986 }
Paul Lawrence87999172014-02-20 12:21:31 -08001987
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001988 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
1989 /* The inplace routine never actually sets the progress to 100% due
1990 * to the round down nature of integer division, so set it here */
1991 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08001992 }
1993
1994 return rc;
1995}
1996
Paul Crowleyb64933a2017-10-31 08:25:55 -07001997static int vold_unmountAll(void) {
1998 VolumeManager* vm = VolumeManager::Instance();
1999 return vm->unmountAll();
2000}
2001
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002002int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002003 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002004 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002005 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002006 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002007 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002008 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002009 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002010 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002011 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002012 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002013 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002014 bool onlyCreateHeader = false;
2015 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002016
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002017 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002018 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2019 /* An encryption was underway and was interrupted */
2020 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2021 crypt_ftr.encrypted_upto = 0;
2022 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002023
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002024 /* At this point, we are in an inconsistent state. Until we successfully
2025 complete encryption, a reboot will leave us broken. So mark the
2026 encryption failed in case that happens.
2027 On successfully completing encryption, remove this flag */
2028 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002029
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002030 put_crypt_ftr_and_key(&crypt_ftr);
2031 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2032 if (!check_ftr_sha(&crypt_ftr)) {
2033 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2034 put_crypt_ftr_and_key(&crypt_ftr);
2035 goto error_unencrypted;
2036 }
2037
2038 /* Doing a reboot-encryption*/
2039 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2040 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2041 rebootEncryption = true;
2042 }
Paul Lawrence87999172014-02-20 12:21:31 -08002043 }
2044
2045 property_get("ro.crypto.state", encrypted_state, "");
2046 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2047 SLOGE("Device is already running encrypted, aborting");
2048 goto error_unencrypted;
2049 }
2050
2051 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002052 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2053 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002054
Ken Sumrall3ed82362011-01-28 23:31:16 -08002055 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002056 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002057 if (fd == -1) {
2058 SLOGE("Cannot open block device %s\n", real_blkdev);
2059 goto error_unencrypted;
2060 }
2061 unsigned long nr_sec;
2062 get_blkdev_size(fd, &nr_sec);
2063 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002064 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2065 goto error_unencrypted;
2066 }
2067 close(fd);
2068
2069 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002070 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002071 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002072 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002073 if (fs_size_sec == 0)
2074 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2075
Paul Lawrence87999172014-02-20 12:21:31 -08002076 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002077
2078 if (fs_size_sec > max_fs_size_sec) {
2079 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2080 goto error_unencrypted;
2081 }
2082 }
2083
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002084 /* Get a wakelock as this may take a while, and we don't want the
2085 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2086 * wants to keep the screen on, it can grab a full wakelock.
2087 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002088 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002089 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2090
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002091 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002092 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002093 */
2094 property_set("vold.decrypt", "trigger_shutdown_framework");
2095 SLOGD("Just asked init to shut down class main\n");
2096
Jeff Sharkey9c484982015-03-31 10:35:33 -07002097 /* Ask vold to unmount all devices that it manages */
2098 if (vold_unmountAll()) {
2099 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002100 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002101
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002102 /* no_ui means we are being called from init, not settings.
2103 Now we always reboot from settings, so !no_ui means reboot
2104 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002105 if (!no_ui) {
2106 /* Try fallback, which is to reboot and try there */
2107 onlyCreateHeader = true;
2108 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2109 if (breadcrumb == 0) {
2110 SLOGE("Failed to create breadcrumb file");
2111 goto error_shutting_down;
2112 }
2113 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002114 }
2115
2116 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002117 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002118 /* Now that /data is unmounted, we need to mount a tmpfs
2119 * /data, set a property saying we're doing inplace encryption,
2120 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002121 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002122 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002123 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002124 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002125 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002126 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002127
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002128 /* restart the framework. */
2129 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002130 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002131
Ken Sumrall92736ef2012-10-17 20:57:14 -07002132 /* Ugh, shutting down the framework is not synchronous, so until it
2133 * can be fixed, this horrible hack will wait a moment for it all to
2134 * shut down before proceeding. Without it, some devices cannot
2135 * restart the graphics services.
2136 */
2137 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002138 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002139
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002140 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002141 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002142 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002143 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2144 goto error_shutting_down;
2145 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002146
Paul Lawrence87999172014-02-20 12:21:31 -08002147 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2148 crypt_ftr.fs_size = nr_sec
2149 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2150 } else {
2151 crypt_ftr.fs_size = nr_sec;
2152 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002153 /* At this point, we are in an inconsistent state. Until we successfully
2154 complete encryption, a reboot will leave us broken. So mark the
2155 encryption failed in case that happens.
2156 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002157 if (onlyCreateHeader) {
2158 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2159 } else {
2160 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2161 }
Paul Lawrence87999172014-02-20 12:21:31 -08002162 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002163 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002164
Paul Lawrence87999172014-02-20 12:21:31 -08002165 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002166 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2167 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002168 SLOGE("Cannot create encrypted master key\n");
2169 goto error_shutting_down;
2170 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002171
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002172 /* Replace scrypted intermediate key if we are preparing for a reboot */
2173 if (onlyCreateHeader) {
2174 unsigned char fake_master_key[KEY_LEN_BYTES];
2175 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2176 memset(fake_master_key, 0, sizeof(fake_master_key));
2177 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2178 encrypted_fake_master_key, &crypt_ftr);
2179 }
2180
Paul Lawrence87999172014-02-20 12:21:31 -08002181 /* Write the key to the end of the partition */
2182 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002183
Paul Lawrence87999172014-02-20 12:21:31 -08002184 /* If any persistent data has been remembered, save it.
2185 * If none, create a valid empty table and save that.
2186 */
2187 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002188 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002189 if (pdata) {
2190 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2191 persist_data = pdata;
2192 }
2193 }
2194 if (persist_data) {
2195 save_persistent_data();
2196 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002197 }
2198
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002199 if (onlyCreateHeader) {
2200 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002201 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002202 }
2203
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002204 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002205 /* startup service classes main and late_start */
2206 property_set("vold.decrypt", "trigger_restart_min_framework");
2207 SLOGD("Just triggered restart_min_framework\n");
2208
2209 /* OK, the framework is restarted and will soon be showing a
2210 * progress bar. Time to setup an encrypted mapping, and
2211 * either write a new filesystem, or encrypt in place updating
2212 * the progress bar as we work.
2213 */
2214 }
2215
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002216 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002217 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002218 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002219
Paul Lawrence87999172014-02-20 12:21:31 -08002220 /* If we are continuing, check checksums match */
2221 rc = 0;
2222 if (previously_encrypted_upto) {
2223 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2224 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002225
Paul Lawrence87999172014-02-20 12:21:31 -08002226 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2227 sizeof(hash_first_block)) != 0) {
2228 SLOGE("Checksums do not match - trigger wipe");
2229 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002230 }
2231 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002232
Paul Lawrence87999172014-02-20 12:21:31 -08002233 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002234 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002235 previously_encrypted_upto);
2236 }
2237
2238 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002239 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002240 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2241 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002242 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002243 SLOGE("Error calculating checksum for continuing encryption");
2244 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002245 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002246 }
2247
2248 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002249 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002250
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002251 if (! rc) {
2252 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002253 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002254
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002255 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002256 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2257 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002258 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002259 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002260
Paul Lawrence6bfed202014-07-28 12:47:22 -07002261 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002262
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002263 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2264 char value[PROPERTY_VALUE_MAX];
2265 property_get("ro.crypto.state", value, "");
2266 if (!strcmp(value, "")) {
2267 /* default encryption - continue first boot sequence */
2268 property_set("ro.crypto.state", "encrypted");
2269 property_set("ro.crypto.type", "block");
2270 release_wake_lock(lockid);
2271 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2272 // Bring up cryptkeeper that will check the password and set it
2273 property_set("vold.decrypt", "trigger_shutdown_framework");
2274 sleep(2);
2275 property_set("vold.encrypt_progress", "");
2276 cryptfs_trigger_restart_min_framework();
2277 } else {
2278 cryptfs_check_passwd(DEFAULT_PASSWORD);
2279 cryptfs_restart_internal(1);
2280 }
2281 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002282 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002283 sleep(2); /* Give the UI a chance to show 100% progress */
2284 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002285 }
Paul Lawrence87999172014-02-20 12:21:31 -08002286 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002287 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002288 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002289 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002290 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002291 char value[PROPERTY_VALUE_MAX];
2292
Ken Sumrall319369a2012-06-27 16:30:18 -07002293 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002294 if (!strcmp(value, "1")) {
2295 /* wipe data if encryption failed */
2296 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002297 std::string err;
2298 const std::vector<std::string> options = {
2299 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2300 };
2301 if (!write_bootloader_message(options, &err)) {
2302 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002303 }
Josh Gaofec44372017-08-28 13:22:55 -07002304 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002305 } else {
2306 /* set property to trigger dialog */
2307 property_set("vold.encrypt_progress", "error_partially_encrypted");
2308 release_wake_lock(lockid);
2309 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002310 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002311 }
2312
Ken Sumrall3ed82362011-01-28 23:31:16 -08002313 /* hrm, the encrypt step claims success, but the reboot failed.
2314 * This should not happen.
2315 * Set the property and return. Hope the framework can deal with it.
2316 */
2317 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002318 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002319 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002320
2321error_unencrypted:
2322 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002323 if (lockid[0]) {
2324 release_wake_lock(lockid);
2325 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002326 return -1;
2327
2328error_shutting_down:
2329 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2330 * but the framework is stopped and not restarted to show the error, so it's up to
2331 * vold to restart the system.
2332 */
2333 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002334 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002335
2336 /* shouldn't get here */
2337 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002338 if (lockid[0]) {
2339 release_wake_lock(lockid);
2340 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002341 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002342}
2343
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002344int cryptfs_enable(int type, const char* passwd, int no_ui) {
2345 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002346}
2347
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002348int cryptfs_enable_default(int no_ui) {
2349 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002350}
2351
2352int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002353{
Paul Crowley38132a12016-02-09 09:50:32 +00002354 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002355 SLOGE("cryptfs_changepw not valid for file encryption");
2356 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002357 }
2358
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002359 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002360 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002361
2362 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002363 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002364 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002365 return -1;
2366 }
2367
Paul Lawrencef4faa572014-01-29 13:31:03 -08002368 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2369 SLOGE("Invalid crypt_type %d", crypt_type);
2370 return -1;
2371 }
2372
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002373 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002374 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002375 SLOGE("Error getting crypt footer and key");
2376 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002377 }
2378
Paul Lawrencef4faa572014-01-29 13:31:03 -08002379 crypt_ftr.crypt_type = crypt_type;
2380
JP Abgrall933216c2015-02-11 13:44:32 -08002381 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002382 : newpw,
2383 crypt_ftr.salt,
2384 saved_master_key,
2385 crypt_ftr.master_key,
2386 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002387 if (rc) {
2388 SLOGE("Encrypt master key failed: %d", rc);
2389 return -1;
2390 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002391 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002392 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002393
2394 return 0;
2395}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002396
Rubin Xu85c01f92014-10-13 12:49:54 +01002397static unsigned int persist_get_max_entries(int encrypted) {
2398 struct crypt_mnt_ftr crypt_ftr;
2399 unsigned int dsize;
2400 unsigned int max_persistent_entries;
2401
2402 /* If encrypted, use the values from the crypt_ftr, otherwise
2403 * use the values for the current spec.
2404 */
2405 if (encrypted) {
2406 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2407 return -1;
2408 }
2409 dsize = crypt_ftr.persist_data_size;
2410 } else {
2411 dsize = CRYPT_PERSIST_DATA_SIZE;
2412 }
2413
2414 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2415 sizeof(struct crypt_persist_entry);
2416
2417 return max_persistent_entries;
2418}
2419
2420static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002421{
2422 unsigned int i;
2423
2424 if (persist_data == NULL) {
2425 return -1;
2426 }
2427 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2428 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2429 /* We found it! */
2430 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2431 return 0;
2432 }
2433 }
2434
2435 return -1;
2436}
2437
Rubin Xu85c01f92014-10-13 12:49:54 +01002438static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002439{
2440 unsigned int i;
2441 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002442 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002443
2444 if (persist_data == NULL) {
2445 return -1;
2446 }
2447
Rubin Xu85c01f92014-10-13 12:49:54 +01002448 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002449
2450 num = persist_data->persist_valid_entries;
2451
2452 for (i = 0; i < num; i++) {
2453 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2454 /* We found an existing entry, update it! */
2455 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2456 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2457 return 0;
2458 }
2459 }
2460
2461 /* We didn't find it, add it to the end, if there is room */
2462 if (persist_data->persist_valid_entries < max_persistent_entries) {
2463 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2464 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2465 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2466 persist_data->persist_valid_entries++;
2467 return 0;
2468 }
2469
2470 return -1;
2471}
2472
Rubin Xu85c01f92014-10-13 12:49:54 +01002473/**
2474 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2475 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2476 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002477int match_multi_entry(const char *key, const char *field, unsigned index) {
2478 std::string key_ = key;
2479 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002480
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002481 std::string parsed_field;
2482 unsigned parsed_index;
2483
2484 std::string::size_type split = key_.find_last_of('_');
2485 if (split == std::string::npos) {
2486 parsed_field = key_;
2487 parsed_index = 0;
2488 } else {
2489 parsed_field = key_.substr(0, split);
2490 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002491 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002492
2493 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002494}
2495
2496/*
2497 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2498 * remaining entries starting from index will be deleted.
2499 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2500 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2501 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2502 *
2503 */
2504static int persist_del_keys(const char *fieldname, unsigned index)
2505{
2506 unsigned int i;
2507 unsigned int j;
2508 unsigned int num;
2509
2510 if (persist_data == NULL) {
2511 return PERSIST_DEL_KEY_ERROR_OTHER;
2512 }
2513
2514 num = persist_data->persist_valid_entries;
2515
2516 j = 0; // points to the end of non-deleted entries.
2517 // Filter out to-be-deleted entries in place.
2518 for (i = 0; i < num; i++) {
2519 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2520 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2521 j++;
2522 }
2523 }
2524
2525 if (j < num) {
2526 persist_data->persist_valid_entries = j;
2527 // Zeroise the remaining entries
2528 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2529 return PERSIST_DEL_KEY_OK;
2530 } else {
2531 // Did not find an entry matching the given fieldname
2532 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2533 }
2534}
2535
2536static int persist_count_keys(const char *fieldname)
2537{
2538 unsigned int i;
2539 unsigned int count;
2540
2541 if (persist_data == NULL) {
2542 return -1;
2543 }
2544
2545 count = 0;
2546 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2547 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2548 count++;
2549 }
2550 }
2551
2552 return count;
2553}
2554
Ken Sumrall160b4d62013-04-22 12:15:39 -07002555/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002556int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002557{
Paul Crowley38132a12016-02-09 09:50:32 +00002558 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002559 SLOGE("Cannot get field when file encrypted");
2560 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002561 }
2562
Ken Sumrall160b4d62013-04-22 12:15:39 -07002563 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002564 /* CRYPTO_GETFIELD_OK is success,
2565 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2566 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2567 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002568 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002569 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2570 int i;
2571 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002572
2573 if (persist_data == NULL) {
2574 load_persistent_data();
2575 if (persist_data == NULL) {
2576 SLOGE("Getfield error, cannot load persistent data");
2577 goto out;
2578 }
2579 }
2580
Rubin Xu85c01f92014-10-13 12:49:54 +01002581 // Read value from persistent entries. If the original value is split into multiple entries,
2582 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002583 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002584 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2585 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2586 // value too small
2587 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2588 goto out;
2589 }
2590 rc = CRYPTO_GETFIELD_OK;
2591
2592 for (i = 1; /* break explicitly */; i++) {
2593 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2594 (int) sizeof(temp_field)) {
2595 // If the fieldname is very long, we stop as soon as it begins to overflow the
2596 // maximum field length. At this point we have in fact fully read out the original
2597 // value because cryptfs_setfield would not allow fields with longer names to be
2598 // written in the first place.
2599 break;
2600 }
2601 if (!persist_get_key(temp_field, temp_value)) {
2602 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2603 // value too small.
2604 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2605 goto out;
2606 }
2607 } else {
2608 // Exhaust all entries.
2609 break;
2610 }
2611 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002612 } else {
2613 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002614 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002615 }
2616
2617out:
2618 return rc;
2619}
2620
2621/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002622int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002623{
Paul Crowley38132a12016-02-09 09:50:32 +00002624 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002625 SLOGE("Cannot set field when file encrypted");
2626 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002627 }
2628
Ken Sumrall160b4d62013-04-22 12:15:39 -07002629 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002630 /* 0 is success, negative values are error */
2631 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002632 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002633 unsigned int field_id;
2634 char temp_field[PROPERTY_KEY_MAX];
2635 unsigned int num_entries;
2636 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002637
2638 if (persist_data == NULL) {
2639 load_persistent_data();
2640 if (persist_data == NULL) {
2641 SLOGE("Setfield error, cannot load persistent data");
2642 goto out;
2643 }
2644 }
2645
2646 property_get("ro.crypto.state", encrypted_state, "");
2647 if (!strcmp(encrypted_state, "encrypted") ) {
2648 encrypted = 1;
2649 }
2650
Rubin Xu85c01f92014-10-13 12:49:54 +01002651 // Compute the number of entries required to store value, each entry can store up to
2652 // (PROPERTY_VALUE_MAX - 1) chars
2653 if (strlen(value) == 0) {
2654 // Empty value also needs one entry to store.
2655 num_entries = 1;
2656 } else {
2657 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2658 }
2659
2660 max_keylen = strlen(fieldname);
2661 if (num_entries > 1) {
2662 // Need an extra "_%d" suffix.
2663 max_keylen += 1 + log10(num_entries);
2664 }
2665 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2666 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002667 goto out;
2668 }
2669
Rubin Xu85c01f92014-10-13 12:49:54 +01002670 // Make sure we have enough space to write the new value
2671 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2672 persist_get_max_entries(encrypted)) {
2673 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2674 goto out;
2675 }
2676
2677 // Now that we know persist_data has enough space for value, let's delete the old field first
2678 // to make up space.
2679 persist_del_keys(fieldname, 0);
2680
2681 if (persist_set_key(fieldname, value, encrypted)) {
2682 // fail to set key, should not happen as we have already checked the available space
2683 SLOGE("persist_set_key() error during setfield()");
2684 goto out;
2685 }
2686
2687 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002688 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002689
2690 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2691 // fail to set key, should not happen as we have already checked the available space.
2692 SLOGE("persist_set_key() error during setfield()");
2693 goto out;
2694 }
2695 }
2696
Ken Sumrall160b4d62013-04-22 12:15:39 -07002697 /* If we are running encrypted, save the persistent data now */
2698 if (encrypted) {
2699 if (save_persistent_data()) {
2700 SLOGE("Setfield error, cannot save persistent data");
2701 goto out;
2702 }
2703 }
2704
Rubin Xu85c01f92014-10-13 12:49:54 +01002705 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002706
2707out:
2708 return rc;
2709}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002710
2711/* Checks userdata. Attempt to mount the volume if default-
2712 * encrypted.
2713 * On success trigger next init phase and return 0.
2714 * Currently do not handle failure - see TODO below.
2715 */
2716int cryptfs_mount_default_encrypted(void)
2717{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002718 int crypt_type = cryptfs_get_password_type();
2719 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2720 SLOGE("Bad crypt type - error");
2721 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2722 SLOGD("Password is not default - "
2723 "starting min framework to prompt");
2724 property_set("vold.decrypt", "trigger_restart_min_framework");
2725 return 0;
2726 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2727 SLOGD("Password is default - restarting filesystem");
2728 cryptfs_restart_internal(0);
2729 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002730 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002731 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002732 }
2733
Paul Lawrence6bfed202014-07-28 12:47:22 -07002734 /** Corrupt. Allow us to boot into framework, which will detect bad
2735 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002736 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002737 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002738 return 0;
2739}
2740
2741/* Returns type of the password, default, pattern, pin or password.
2742 */
2743int cryptfs_get_password_type(void)
2744{
Paul Crowley38132a12016-02-09 09:50:32 +00002745 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002746 SLOGE("cryptfs_get_password_type not valid for file encryption");
2747 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002748 }
2749
Paul Lawrencef4faa572014-01-29 13:31:03 -08002750 struct crypt_mnt_ftr crypt_ftr;
2751
2752 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2753 SLOGE("Error getting crypt footer and key\n");
2754 return -1;
2755 }
2756
Paul Lawrence6bfed202014-07-28 12:47:22 -07002757 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2758 return -1;
2759 }
2760
Paul Lawrencef4faa572014-01-29 13:31:03 -08002761 return crypt_ftr.crypt_type;
2762}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002763
Paul Lawrence05335c32015-03-05 09:46:23 -08002764const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002765{
Paul Crowley38132a12016-02-09 09:50:32 +00002766 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002767 SLOGE("cryptfs_get_password not valid for file encryption");
2768 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002769 }
2770
Paul Lawrence399317e2014-03-10 13:20:50 -07002771 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002772 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002773 if (now.tv_sec < password_expiry_time) {
2774 return password;
2775 } else {
2776 cryptfs_clear_password();
2777 return 0;
2778 }
2779}
2780
2781void cryptfs_clear_password()
2782{
2783 if (password) {
2784 size_t len = strlen(password);
2785 memset(password, 0, len);
2786 free(password);
2787 password = 0;
2788 password_expiry_time = 0;
2789 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002790}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002791
Paul Lawrence0c247462015-10-29 10:30:57 -07002792int cryptfs_isConvertibleToFBE()
2793{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002794 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002795 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2796}