blob: 207f08cfb5e2c7a344c269a8f015b0812fa28639 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Paul Crowley3b71fc52017-10-09 10:55:21 -070041#include <ext4_utils/ext4_crypt.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070042#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070058#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000059#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000060#include "f2fs_sparseblock.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070061#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080062#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000063#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080064#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070065#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080066extern "C" {
67#include <crypto_scrypt.h>
68}
Mark Salyzyn3e971272014-01-21 13:27:04 -080069
Mark Salyzyn5eecc442014-02-12 14:16:14 -080070#define UNUSED __attribute__((unused))
71
Ken Sumrall8f869aa2010-12-03 03:47:09 -080072#define DM_CRYPT_BUF_SIZE 4096
73
Jason parks70a4b3f2011-01-28 10:10:47 -060074#define HASH_COUNT 2000
75#define KEY_LEN_BYTES 16
76#define IV_LEN_BYTES 16
77
Ken Sumrall29d8da82011-05-18 17:20:07 -070078#define KEY_IN_FOOTER "footer"
79
Paul Lawrence3bd36d52015-06-09 13:37:44 -070080#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080081
Paul Lawrence3d99eba2015-11-20 07:07:19 -080082#define CRYPTO_BLOCK_DEVICE "userdata"
83
84#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
85
Ken Sumrall29d8da82011-05-18 17:20:07 -070086#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070087#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070088
Ken Sumralle919efe2012-09-29 17:07:41 -070089#define TABLE_LOAD_RETRIES 10
90
Shawn Willden47ba10d2014-09-03 17:07:06 -060091#define RSA_KEY_SIZE 2048
92#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
93#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060094#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070095
Paul Lawrence8e3f4512014-09-08 10:11:17 -070096#define RETRY_MOUNT_ATTEMPTS 10
97#define RETRY_MOUNT_DELAY_SECONDS 1
98
Paul Crowley5afbc622017-11-27 09:42:17 -080099#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
100
Paul Crowley73473332017-11-21 15:43:51 -0800101static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
102
Jason parks70a4b3f2011-01-28 10:10:47 -0600103static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700104static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600105static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700106static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800107
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700108/* Should we use keymaster? */
109static int keymaster_check_compatibility()
110{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000111 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700112}
113
114/* Create a new keymaster key and store it in this footer */
115static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
116{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800117 if (ftr->keymaster_blob_size) {
118 SLOGI("Already have key");
119 return 0;
120 }
121
Janis Danisevskis015ec302017-01-31 11:31:08 +0000122 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
123 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
124 &ftr->keymaster_blob_size);
125 if (rc) {
126 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800127 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000128 ftr->keymaster_blob_size = 0;
129 }
130 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700131 return -1;
132 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000133 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700134}
135
Shawn Willdene17a9c42014-09-08 13:04:08 -0600136/* This signs the given object using the keymaster key. */
137static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600138 const unsigned char *object,
139 const size_t object_size,
140 unsigned char **signature,
141 size_t *signature_size)
142{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600143 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600144 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600145 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600146
Shawn Willdene17a9c42014-09-08 13:04:08 -0600147 // To sign a message with RSA, the message must satisfy two
148 // constraints:
149 //
150 // 1. The message, when interpreted as a big-endian numeric value, must
151 // be strictly less than the public modulus of the RSA key. Note
152 // that because the most significant bit of the public modulus is
153 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
154 // key), an n-bit message with most significant bit 0 always
155 // satisfies this requirement.
156 //
157 // 2. The message must have the same length in bits as the public
158 // modulus of the RSA key. This requirement isn't mathematically
159 // necessary, but is necessary to ensure consistency in
160 // implementations.
161 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600162 case KDF_SCRYPT_KEYMASTER:
163 // This ensures the most significant byte of the signed message
164 // is zero. We could have zero-padded to the left instead, but
165 // this approach is slightly more robust against changes in
166 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600167 // so) because we really should be using a proper deterministic
168 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800169 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600170 SLOGI("Signing safely-padded object");
171 break;
172 default:
173 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000174 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600175 }
Paul Crowley73473332017-11-21 15:43:51 -0800176 for (;;) {
177 auto result = keymaster_sign_object_for_cryptfs_scrypt(
178 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
179 to_sign_size, signature, signature_size);
180 switch (result) {
181 case KeymasterSignResult::ok:
182 return 0;
183 case KeymasterSignResult::upgrade:
184 break;
185 default:
186 return -1;
187 }
188 SLOGD("Upgrading key");
189 if (keymaster_upgrade_key_for_cryptfs_scrypt(
190 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
191 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
192 &ftr->keymaster_blob_size) != 0) {
193 SLOGE("Failed to upgrade key");
194 return -1;
195 }
196 if (put_crypt_ftr_and_key(ftr) != 0) {
197 SLOGE("Failed to write upgraded key to disk");
198 }
199 SLOGD("Key upgraded successfully");
200 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600201}
202
Paul Lawrence399317e2014-03-10 13:20:50 -0700203/* Store password when userdata is successfully decrypted and mounted.
204 * Cleared by cryptfs_clear_password
205 *
206 * To avoid a double prompt at boot, we need to store the CryptKeeper
207 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
208 * Since the entire framework is torn down and rebuilt after encryption,
209 * we have to use a daemon or similar to store the password. Since vold
210 * is secured against IPC except from system processes, it seems a reasonable
211 * place to store this.
212 *
213 * password should be cleared once it has been used.
214 *
215 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800216 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700217static char* password = 0;
218static int password_expiry_time = 0;
219static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800220
Josh Gaofec44372017-08-28 13:22:55 -0700221enum class RebootType {reboot, recovery, shutdown};
222static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700223{
Josh Gaofec44372017-08-28 13:22:55 -0700224 switch (rt) {
225 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800226 property_set(ANDROID_RB_PROPERTY, "reboot");
227 break;
228
Josh Gaofec44372017-08-28 13:22:55 -0700229 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800230 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
231 break;
232
Josh Gaofec44372017-08-28 13:22:55 -0700233 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800234 property_set(ANDROID_RB_PROPERTY, "shutdown");
235 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700236 }
Paul Lawrence87999172014-02-20 12:21:31 -0800237
Ken Sumralladfba362013-06-04 16:37:52 -0700238 sleep(20);
239
240 /* Shouldn't get here, reboot should happen before sleep times out */
241 return;
242}
243
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800244static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
245{
246 memset(io, 0, dataSize);
247 io->data_size = dataSize;
248 io->data_start = sizeof(struct dm_ioctl);
249 io->version[0] = 4;
250 io->version[1] = 0;
251 io->version[2] = 0;
252 io->flags = flags;
253 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100254 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800255 }
256}
257
Kenny Rootc4c70f12013-06-14 12:11:38 -0700258/**
259 * Gets the default device scrypt parameters for key derivation time tuning.
260 * The parameters should lead to about one second derivation time for the
261 * given device.
262 */
263static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700264 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000265 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700266
Paul Crowley63c18d32016-02-10 14:02:47 +0000267 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
268 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
269 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
270 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700271 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000272 ftr->N_factor = Nf;
273 ftr->r_factor = rf;
274 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700275}
276
Ken Sumrall3ed82362011-01-28 23:31:16 -0800277static unsigned int get_fs_size(char *dev)
278{
279 int fd, block_size;
280 struct ext4_super_block sb;
281 off64_t len;
282
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700283 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800284 SLOGE("Cannot open device to get filesystem size ");
285 return 0;
286 }
287
288 if (lseek64(fd, 1024, SEEK_SET) < 0) {
289 SLOGE("Cannot seek to superblock");
290 return 0;
291 }
292
293 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
294 SLOGE("Cannot read superblock");
295 return 0;
296 }
297
298 close(fd);
299
Daniel Rosenberge82df162014-08-15 22:19:23 +0000300 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
301 SLOGE("Not a valid ext4 superblock");
302 return 0;
303 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800304 block_size = 1024 << sb.s_log_block_size;
305 /* compute length in bytes */
306 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
307
308 /* return length in sectors */
309 return (unsigned int) (len / 512);
310}
311
Ken Sumrall160b4d62013-04-22 12:15:39 -0700312static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
313{
314 static int cached_data = 0;
315 static off64_t cached_off = 0;
316 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
317 int fd;
318 char key_loc[PROPERTY_VALUE_MAX];
319 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700320 int rc = -1;
321
322 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700323 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700324
325 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700326 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700327 SLOGE("Cannot open real block device %s\n", real_blkdev);
328 return -1;
329 }
330
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900331 unsigned long nr_sec = 0;
332 get_blkdev_size(fd, &nr_sec);
333 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700334 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
335 * encryption info footer and key, and plenty of bytes to spare for future
336 * growth.
337 */
338 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
339 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
340 cached_data = 1;
341 } else {
342 SLOGE("Cannot get size of block device %s\n", real_blkdev);
343 }
344 close(fd);
345 } else {
346 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
347 cached_off = 0;
348 cached_data = 1;
349 }
350 }
351
352 if (cached_data) {
353 if (metadata_fname) {
354 *metadata_fname = cached_metadata_fname;
355 }
356 if (off) {
357 *off = cached_off;
358 }
359 rc = 0;
360 }
361
362 return rc;
363}
364
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800365/* Set sha256 checksum in structure */
366static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
367{
368 SHA256_CTX c;
369 SHA256_Init(&c);
370 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
371 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
372 SHA256_Final(crypt_ftr->sha256, &c);
373}
374
Ken Sumralle8744072011-01-18 22:01:55 -0800375/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800376 * update the failed mount count but not change the key.
377 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800379{
380 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800381 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700382 /* starting_off is set to the SEEK_SET offset
383 * where the crypto structure starts
384 */
385 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800386 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700387 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700388 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800389
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800390 set_ftr_sha(crypt_ftr);
391
Ken Sumrall160b4d62013-04-22 12:15:39 -0700392 if (get_crypt_ftr_info(&fname, &starting_off)) {
393 SLOGE("Unable to get crypt_ftr_info\n");
394 return -1;
395 }
396 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700397 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700398 return -1;
399 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700400 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700401 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700402 return -1;
403 }
404
405 /* Seek to the start of the crypt footer */
406 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
407 SLOGE("Cannot seek to real block device footer\n");
408 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800409 }
410
411 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
412 SLOGE("Cannot write real block device footer\n");
413 goto errout;
414 }
415
Ken Sumrall3be890f2011-09-14 16:53:46 -0700416 fstat(fd, &statbuf);
417 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700418 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700419 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800420 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800421 goto errout;
422 }
423 }
424
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800425 /* Success! */
426 rc = 0;
427
428errout:
429 close(fd);
430 return rc;
431
432}
433
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800434static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
435{
436 struct crypt_mnt_ftr copy;
437 memcpy(&copy, crypt_ftr, sizeof(copy));
438 set_ftr_sha(&copy);
439 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
440}
441
Ken Sumrall160b4d62013-04-22 12:15:39 -0700442static inline int unix_read(int fd, void* buff, int len)
443{
444 return TEMP_FAILURE_RETRY(read(fd, buff, len));
445}
446
447static inline int unix_write(int fd, const void* buff, int len)
448{
449 return TEMP_FAILURE_RETRY(write(fd, buff, len));
450}
451
452static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
453{
454 memset(pdata, 0, len);
455 pdata->persist_magic = PERSIST_DATA_MAGIC;
456 pdata->persist_valid_entries = 0;
457}
458
459/* A routine to update the passed in crypt_ftr to the lastest version.
460 * fd is open read/write on the device that holds the crypto footer and persistent
461 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
462 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
463 */
464static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
465{
Kenny Root7434b312013-06-14 11:29:53 -0700466 int orig_major = crypt_ftr->major_version;
467 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700468
Kenny Root7434b312013-06-14 11:29:53 -0700469 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
470 struct crypt_persist_data *pdata;
471 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700472
Kenny Rootc4c70f12013-06-14 12:11:38 -0700473 SLOGW("upgrading crypto footer to 1.1");
474
Wei Wang4375f1b2017-02-24 17:43:01 -0800475 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700476 if (pdata == NULL) {
477 SLOGE("Cannot allocate persisent data\n");
478 return;
479 }
480 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
481
482 /* Need to initialize the persistent data area */
483 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
484 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100485 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700486 return;
487 }
488 /* Write all zeros to the first copy, making it invalid */
489 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
490
491 /* Write a valid but empty structure to the second copy */
492 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
493 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
494
495 /* Update the footer */
496 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
497 crypt_ftr->persist_data_offset[0] = pdata_offset;
498 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
499 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100500 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700501 }
502
Paul Lawrencef4faa572014-01-29 13:31:03 -0800503 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700504 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800505 /* But keep the old kdf_type.
506 * It will get updated later to KDF_SCRYPT after the password has been verified.
507 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700508 crypt_ftr->kdf_type = KDF_PBKDF2;
509 get_device_scrypt_params(crypt_ftr);
510 crypt_ftr->minor_version = 2;
511 }
512
Paul Lawrencef4faa572014-01-29 13:31:03 -0800513 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
514 SLOGW("upgrading crypto footer to 1.3");
515 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
516 crypt_ftr->minor_version = 3;
517 }
518
Kenny Root7434b312013-06-14 11:29:53 -0700519 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
520 if (lseek64(fd, offset, SEEK_SET) == -1) {
521 SLOGE("Cannot seek to crypt footer\n");
522 return;
523 }
524 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700525 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700526}
527
528
529static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800530{
531 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800532 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800534 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700535 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700536 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800537
Ken Sumrall160b4d62013-04-22 12:15:39 -0700538 if (get_crypt_ftr_info(&fname, &starting_off)) {
539 SLOGE("Unable to get crypt_ftr_info\n");
540 return -1;
541 }
542 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700543 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700544 return -1;
545 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700546 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700547 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700548 return -1;
549 }
550
551 /* Make sure it's 16 Kbytes in length */
552 fstat(fd, &statbuf);
553 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
554 SLOGE("footer file %s is not the expected size!\n", fname);
555 goto errout;
556 }
557
558 /* Seek to the start of the crypt footer */
559 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
560 SLOGE("Cannot seek to real block device footer\n");
561 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800562 }
563
564 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
565 SLOGE("Cannot read real block device footer\n");
566 goto errout;
567 }
568
569 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700570 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800571 goto errout;
572 }
573
Kenny Rootc96a5f82013-06-14 12:08:28 -0700574 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
575 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
576 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800577 goto errout;
578 }
579
Kenny Rootc96a5f82013-06-14 12:08:28 -0700580 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
581 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
582 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800583 }
584
Ken Sumrall160b4d62013-04-22 12:15:39 -0700585 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
586 * copy on disk before returning.
587 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700588 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700589 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800590 }
591
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800592 /* Success! */
593 rc = 0;
594
595errout:
596 close(fd);
597 return rc;
598}
599
Ken Sumrall160b4d62013-04-22 12:15:39 -0700600static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
601{
602 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
603 crypt_ftr->persist_data_offset[1]) {
604 SLOGE("Crypt_ftr persist data regions overlap");
605 return -1;
606 }
607
608 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
609 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
610 return -1;
611 }
612
613 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
614 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
615 CRYPT_FOOTER_OFFSET) {
616 SLOGE("Persistent data extends past crypto footer");
617 return -1;
618 }
619
620 return 0;
621}
622
623static int load_persistent_data(void)
624{
625 struct crypt_mnt_ftr crypt_ftr;
626 struct crypt_persist_data *pdata = NULL;
627 char encrypted_state[PROPERTY_VALUE_MAX];
628 char *fname;
629 int found = 0;
630 int fd;
631 int ret;
632 int i;
633
634 if (persist_data) {
635 /* Nothing to do, we've already loaded or initialized it */
636 return 0;
637 }
638
639
640 /* If not encrypted, just allocate an empty table and initialize it */
641 property_get("ro.crypto.state", encrypted_state, "");
642 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800643 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700644 if (pdata) {
645 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
646 persist_data = pdata;
647 return 0;
648 }
649 return -1;
650 }
651
652 if(get_crypt_ftr_and_key(&crypt_ftr)) {
653 return -1;
654 }
655
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700656 if ((crypt_ftr.major_version < 1)
657 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700658 SLOGE("Crypt_ftr version doesn't support persistent data");
659 return -1;
660 }
661
662 if (get_crypt_ftr_info(&fname, NULL)) {
663 return -1;
664 }
665
666 ret = validate_persistent_data_storage(&crypt_ftr);
667 if (ret) {
668 return -1;
669 }
670
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700671 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700672 if (fd < 0) {
673 SLOGE("Cannot open %s metadata file", fname);
674 return -1;
675 }
676
Wei Wang4375f1b2017-02-24 17:43:01 -0800677 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800678 if (pdata == NULL) {
679 SLOGE("Cannot allocate memory for persistent data");
680 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700681 }
682
683 for (i = 0; i < 2; i++) {
684 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
685 SLOGE("Cannot seek to read persistent data on %s", fname);
686 goto err2;
687 }
688 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
689 SLOGE("Error reading persistent data on iteration %d", i);
690 goto err2;
691 }
692 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
693 found = 1;
694 break;
695 }
696 }
697
698 if (!found) {
699 SLOGI("Could not find valid persistent data, creating");
700 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
701 }
702
703 /* Success */
704 persist_data = pdata;
705 close(fd);
706 return 0;
707
708err2:
709 free(pdata);
710
711err:
712 close(fd);
713 return -1;
714}
715
716static int save_persistent_data(void)
717{
718 struct crypt_mnt_ftr crypt_ftr;
719 struct crypt_persist_data *pdata;
720 char *fname;
721 off64_t write_offset;
722 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700723 int fd;
724 int ret;
725
726 if (persist_data == NULL) {
727 SLOGE("No persistent data to save");
728 return -1;
729 }
730
731 if(get_crypt_ftr_and_key(&crypt_ftr)) {
732 return -1;
733 }
734
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700735 if ((crypt_ftr.major_version < 1)
736 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700737 SLOGE("Crypt_ftr version doesn't support persistent data");
738 return -1;
739 }
740
741 ret = validate_persistent_data_storage(&crypt_ftr);
742 if (ret) {
743 return -1;
744 }
745
746 if (get_crypt_ftr_info(&fname, NULL)) {
747 return -1;
748 }
749
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700750 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700751 if (fd < 0) {
752 SLOGE("Cannot open %s metadata file", fname);
753 return -1;
754 }
755
Wei Wang4375f1b2017-02-24 17:43:01 -0800756 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700757 if (pdata == NULL) {
758 SLOGE("Cannot allocate persistant data");
759 goto err;
760 }
761
762 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
763 SLOGE("Cannot seek to read persistent data on %s", fname);
764 goto err2;
765 }
766
767 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
768 SLOGE("Error reading persistent data before save");
769 goto err2;
770 }
771
772 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
773 /* The first copy is the curent valid copy, so write to
774 * the second copy and erase this one */
775 write_offset = crypt_ftr.persist_data_offset[1];
776 erase_offset = crypt_ftr.persist_data_offset[0];
777 } else {
778 /* The second copy must be the valid copy, so write to
779 * the first copy, and erase the second */
780 write_offset = crypt_ftr.persist_data_offset[0];
781 erase_offset = crypt_ftr.persist_data_offset[1];
782 }
783
784 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100785 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700786 SLOGE("Cannot seek to write persistent data");
787 goto err2;
788 }
789 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
790 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100791 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700792 SLOGE("Cannot seek to erase previous persistent data");
793 goto err2;
794 }
795 fsync(fd);
796 memset(pdata, 0, crypt_ftr.persist_data_size);
797 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
798 (int) crypt_ftr.persist_data_size) {
799 SLOGE("Cannot write to erase previous persistent data");
800 goto err2;
801 }
802 fsync(fd);
803 } else {
804 SLOGE("Cannot write to save persistent data");
805 goto err2;
806 }
807
808 /* Success */
809 free(pdata);
810 close(fd);
811 return 0;
812
813err2:
814 free(pdata);
815err:
816 close(fd);
817 return -1;
818}
819
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800820/* Convert a binary key of specified length into an ascii hex string equivalent,
821 * without the leading 0x and with null termination
822 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700823static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700824 unsigned int keysize, char *master_key_ascii) {
825 unsigned int i, a;
826 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800827
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700828 for (i=0, a=0; i<keysize; i++, a+=2) {
829 /* For each byte, write out two ascii hex digits */
830 nibble = (master_key[i] >> 4) & 0xf;
831 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800832
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700833 nibble = master_key[i] & 0xf;
834 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
835 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800836
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700837 /* Add the null termination */
838 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800839
840}
841
Jeff Sharkey9c484982015-03-31 10:35:33 -0700842static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
843 const unsigned char *master_key, const char *real_blk_name,
844 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800845 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800846 struct dm_ioctl *io;
847 struct dm_target_spec *tgt;
848 char *crypt_params;
849 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800850 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800851 int i;
852
853 io = (struct dm_ioctl *) buffer;
854
855 /* Load the mapping table for this device */
856 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
857
858 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
859 io->target_count = 1;
860 tgt->status = 0;
861 tgt->sector_start = 0;
862 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700863 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800864
865 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
866 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800867
868 buff_offset = crypt_params - buffer;
Paul Crowley5afbc622017-11-27 09:42:17 -0800869 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800870 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
871 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
872 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800873 crypt_params += strlen(crypt_params) + 1;
874 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
875 tgt->next = crypt_params - buffer;
876
877 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
878 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
879 break;
880 }
881 usleep(500000);
882 }
883
884 if (i == TABLE_LOAD_RETRIES) {
885 /* We failed to load the table, return an error */
886 return -1;
887 } else {
888 return i + 1;
889 }
890}
891
892
893static int get_dm_crypt_version(int fd, const char *name, int *version)
894{
895 char buffer[DM_CRYPT_BUF_SIZE];
896 struct dm_ioctl *io;
897 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800898
899 io = (struct dm_ioctl *) buffer;
900
901 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
902
903 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
904 return -1;
905 }
906
907 /* Iterate over the returned versions, looking for name of "crypt".
908 * When found, get and return the version.
909 */
910 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
911 while (v->next) {
912 if (! strcmp(v->name, "crypt")) {
913 /* We found the crypt driver, return the version, and get out */
914 version[0] = v->version[0];
915 version[1] = v->version[1];
916 version[2] = v->version[2];
917 return 0;
918 }
919 v = (struct dm_target_versions *)(((char *)v) + v->next);
920 }
921
922 return -1;
923}
924
Paul Crowley5afbc622017-11-27 09:42:17 -0800925static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
926 if (extra_params_vec.empty()) return "";
927 std::string extra_params = std::to_string(extra_params_vec.size());
928 for (const auto& p : extra_params_vec) {
929 extra_params.append(" ");
930 extra_params.append(p);
931 }
932 return extra_params;
933}
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800934
Paul Crowley5afbc622017-11-27 09:42:17 -0800935static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
936 const char* real_blk_name, char* crypto_blk_name, const char* name,
937 uint32_t flags) {
938 char buffer[DM_CRYPT_BUF_SIZE];
939 struct dm_ioctl* io;
940 unsigned int minor;
941 int fd = 0;
942 int err;
943 int retval = -1;
944 int version[3];
945 int load_count;
946 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800947
Paul Crowley5afbc622017-11-27 09:42:17 -0800948 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
949 SLOGE("Cannot open device-mapper\n");
950 goto errout;
951 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800952
Paul Crowley5afbc622017-11-27 09:42:17 -0800953 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800954
Paul Crowley5afbc622017-11-27 09:42:17 -0800955 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
956 err = ioctl(fd, DM_DEV_CREATE, io);
957 if (err) {
958 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
959 goto errout;
960 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800961
Paul Crowley5afbc622017-11-27 09:42:17 -0800962 /* Get the device status, in particular, the name of it's device file */
963 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
964 if (ioctl(fd, DM_DEV_STATUS, io)) {
965 SLOGE("Cannot retrieve dm-crypt device status\n");
966 goto errout;
967 }
968 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
969 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -0700970
Paul Crowley5afbc622017-11-27 09:42:17 -0800971 if (!get_dm_crypt_version(fd, name, version)) {
972 /* Support for allow_discards was added in version 1.11.0 */
973 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
974 extra_params_vec.emplace_back("allow_discards");
975 }
976 }
977 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
978 extra_params_vec.emplace_back("allow_encrypt_override");
979 }
980 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
981 extra_params_as_string(extra_params_vec).c_str());
982 if (load_count < 0) {
983 SLOGE("Cannot load dm-crypt mapping table.\n");
984 goto errout;
985 } else if (load_count > 1) {
986 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
987 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800988
Paul Crowley5afbc622017-11-27 09:42:17 -0800989 /* Resume this device to activate it */
990 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800991
Paul Crowley5afbc622017-11-27 09:42:17 -0800992 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
993 SLOGE("Cannot resume the dm-crypt device\n");
994 goto errout;
995 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800996
Paul Crowley5afbc622017-11-27 09:42:17 -0800997 /* We made it here with no errors. Woot! */
998 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800999
1000errout:
1001 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1002
1003 return retval;
1004}
1005
Wei Wang4375f1b2017-02-24 17:43:01 -08001006static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001007{
1008 int fd;
1009 char buffer[DM_CRYPT_BUF_SIZE];
1010 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001011 int retval = -1;
1012
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001013 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001014 SLOGE("Cannot open device-mapper\n");
1015 goto errout;
1016 }
1017
1018 io = (struct dm_ioctl *) buffer;
1019
1020 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1021 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1022 SLOGE("Cannot remove dm-crypt device\n");
1023 goto errout;
1024 }
1025
1026 /* We made it here with no errors. Woot! */
1027 retval = 0;
1028
1029errout:
1030 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1031
1032 return retval;
1033
1034}
1035
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001036static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001037 unsigned char *ikey, void *params UNUSED)
1038{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001039 SLOGI("Using pbkdf2 for cryptfs KDF");
1040
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001041 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001042 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1043 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1044 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001045}
1046
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001047static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001048 unsigned char *ikey, void *params)
1049{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001050 SLOGI("Using scrypt for cryptfs KDF");
1051
Kenny Rootc4c70f12013-06-14 12:11:38 -07001052 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1053
1054 int N = 1 << ftr->N_factor;
1055 int r = 1 << ftr->r_factor;
1056 int p = 1 << ftr->p_factor;
1057
1058 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001059 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001060 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1061 salt, SALT_LEN, N, r, p, ikey,
1062 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001063
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001064 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001065}
1066
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001067static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1068 unsigned char *ikey, void *params)
1069{
1070 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1071
1072 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001073 size_t signature_size;
1074 unsigned char* signature;
1075 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1076
1077 int N = 1 << ftr->N_factor;
1078 int r = 1 << ftr->r_factor;
1079 int p = 1 << ftr->p_factor;
1080
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001081 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1082 salt, SALT_LEN, N, r, p, ikey,
1083 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001084
1085 if (rc) {
1086 SLOGE("scrypt failed");
1087 return -1;
1088 }
1089
Shawn Willdene17a9c42014-09-08 13:04:08 -06001090 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1091 &signature, &signature_size)) {
1092 SLOGE("Signing failed");
1093 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001094 }
1095
1096 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1097 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1098 free(signature);
1099
1100 if (rc) {
1101 SLOGE("scrypt failed");
1102 return -1;
1103 }
1104
1105 return 0;
1106}
1107
1108static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1109 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001110 unsigned char *encrypted_master_key,
1111 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001112{
1113 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1114 EVP_CIPHER_CTX e_ctx;
1115 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001116 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001117
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001118 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001119 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001120
1121 switch (crypt_ftr->kdf_type) {
1122 case KDF_SCRYPT_KEYMASTER:
1123 if (keymaster_create_key(crypt_ftr)) {
1124 SLOGE("keymaster_create_key failed");
1125 return -1;
1126 }
1127
1128 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1129 SLOGE("scrypt failed");
1130 return -1;
1131 }
1132 break;
1133
1134 case KDF_SCRYPT:
1135 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1136 SLOGE("scrypt failed");
1137 return -1;
1138 }
1139 break;
1140
1141 default:
1142 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001143 return -1;
1144 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001145
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001146 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001147 EVP_CIPHER_CTX_init(&e_ctx);
1148 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149 SLOGE("EVP_EncryptInit failed\n");
1150 return -1;
1151 }
1152 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001153
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001154 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001155 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001156 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 SLOGE("EVP_EncryptUpdate failed\n");
1158 return -1;
1159 }
Adam Langley889c4f12014-09-03 14:23:13 -07001160 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 SLOGE("EVP_EncryptFinal failed\n");
1162 return -1;
1163 }
1164
1165 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1166 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1167 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001168 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001169
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001170 /* Store the scrypt of the intermediate key, so we can validate if it's a
1171 password error or mount error when things go wrong.
1172 Note there's no need to check for errors, since if this is incorrect, we
1173 simply won't wipe userdata, which is the correct default behavior
1174 */
1175 int N = 1 << crypt_ftr->N_factor;
1176 int r = 1 << crypt_ftr->r_factor;
1177 int p = 1 << crypt_ftr->p_factor;
1178
1179 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1180 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1181 crypt_ftr->scrypted_intermediate_key,
1182 sizeof(crypt_ftr->scrypted_intermediate_key));
1183
1184 if (rc) {
1185 SLOGE("encrypt_master_key: crypto_scrypt failed");
1186 }
1187
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001188 EVP_CIPHER_CTX_cleanup(&e_ctx);
1189
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001190 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001191}
1192
Paul Lawrence731a7a22015-04-28 22:14:15 +00001193static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001194 unsigned char *encrypted_master_key,
1195 unsigned char *decrypted_master_key,
1196 kdf_func kdf, void *kdf_params,
1197 unsigned char** intermediate_key,
1198 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001199{
1200 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001201 EVP_CIPHER_CTX d_ctx;
1202 int decrypted_len, final_len;
1203
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001204 /* Turn the password into an intermediate key and IV that can decrypt the
1205 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001206 if (kdf(passwd, salt, ikey, kdf_params)) {
1207 SLOGE("kdf failed");
1208 return -1;
1209 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001210
1211 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001212 EVP_CIPHER_CTX_init(&d_ctx);
1213 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001214 return -1;
1215 }
1216 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1217 /* Decrypt the master key */
1218 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1219 encrypted_master_key, KEY_LEN_BYTES)) {
1220 return -1;
1221 }
Adam Langley889c4f12014-09-03 14:23:13 -07001222 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223 return -1;
1224 }
1225
1226 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1227 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001228 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001229
1230 /* Copy intermediate key if needed by params */
1231 if (intermediate_key && intermediate_key_size) {
1232 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001233 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001234 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1235 *intermediate_key_size = KEY_LEN_BYTES;
1236 }
1237 }
1238
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001239 EVP_CIPHER_CTX_cleanup(&d_ctx);
1240
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001241 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001242}
1243
Kenny Rootc4c70f12013-06-14 12:11:38 -07001244static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001245{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001246 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001247 *kdf = scrypt_keymaster;
1248 *kdf_params = ftr;
1249 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001250 *kdf = scrypt;
1251 *kdf_params = ftr;
1252 } else {
1253 *kdf = pbkdf2;
1254 *kdf_params = NULL;
1255 }
1256}
1257
Paul Lawrence731a7a22015-04-28 22:14:15 +00001258static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001259 struct crypt_mnt_ftr *crypt_ftr,
1260 unsigned char** intermediate_key,
1261 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001262{
1263 kdf_func kdf;
1264 void *kdf_params;
1265 int ret;
1266
1267 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001268 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1269 decrypted_master_key, kdf, kdf_params,
1270 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001271 if (ret != 0) {
1272 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001273 }
1274
1275 return ret;
1276}
1277
Wei Wang4375f1b2017-02-24 17:43:01 -08001278static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001279 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001280 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001281 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001282
1283 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001284 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001285 read(fd, key_buf, sizeof(key_buf));
1286 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001287 close(fd);
1288
1289 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001290 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001291}
1292
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001293int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294{
Greg Hackmann955653e2014-09-24 14:55:20 -07001295 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001296#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001297
1298 /* Now umount the tmpfs filesystem */
1299 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001300 if (umount(mountpoint) == 0) {
1301 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001303
1304 if (errno == EINVAL) {
1305 /* EINVAL is returned if the directory is not a mountpoint,
1306 * i.e. there is no filesystem mounted there. So just get out.
1307 */
1308 break;
1309 }
1310
1311 err = errno;
1312
1313 /* If allowed, be increasingly aggressive before the last two retries */
1314 if (kill) {
1315 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1316 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001317 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001318 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1319 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001320 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001321 }
1322 }
1323
1324 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001325 }
1326
1327 if (i < WAIT_UNMOUNT_COUNT) {
1328 SLOGD("unmounting %s succeeded\n", mountpoint);
1329 rc = 0;
1330 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001331 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001332 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001333 rc = -1;
1334 }
1335
1336 return rc;
1337}
1338
Wei Wang42e38102017-06-07 10:46:12 -07001339static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001340{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001341 // NOTE: post_fs_data results in init calling back around to vold, so all
1342 // callers to this method must be async
1343
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001344 /* Do the prep of the /data filesystem */
1345 property_set("vold.post_fs_data_done", "0");
1346 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001347 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001348
Ken Sumrallc5872692013-05-14 15:26:31 -07001349 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001350 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001351 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001352 std::chrono::seconds(15))) {
1353 /* We timed out to prep /data in time. Continue wait. */
1354 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001355 }
Wei Wang42e38102017-06-07 10:46:12 -07001356 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001357}
1358
Paul Lawrence74f29f12014-08-28 15:54:10 -07001359static void cryptfs_set_corrupt()
1360{
1361 // Mark the footer as bad
1362 struct crypt_mnt_ftr crypt_ftr;
1363 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1364 SLOGE("Failed to get crypto footer - panic");
1365 return;
1366 }
1367
1368 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1369 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1370 SLOGE("Failed to set crypto footer - panic");
1371 return;
1372 }
1373}
1374
1375static void cryptfs_trigger_restart_min_framework()
1376{
1377 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1378 SLOGE("Failed to mount tmpfs on data - panic");
1379 return;
1380 }
1381
1382 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1383 SLOGE("Failed to trigger post fs data - panic");
1384 return;
1385 }
1386
1387 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1388 SLOGE("Failed to trigger restart min framework - panic");
1389 return;
1390 }
1391}
1392
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001393/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001394static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001395{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001396 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001397 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001398 static int restart_successful = 0;
1399
1400 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001401 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001402 SLOGE("Encrypted filesystem not validated, aborting");
1403 return -1;
1404 }
1405
1406 if (restart_successful) {
1407 SLOGE("System already restarted with encrypted disk, aborting");
1408 return -1;
1409 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001410
Paul Lawrencef4faa572014-01-29 13:31:03 -08001411 if (restart_main) {
1412 /* Here is where we shut down the framework. The init scripts
1413 * start all services in one of three classes: core, main or late_start.
1414 * On boot, we start core and main. Now, we stop main, but not core,
1415 * as core includes vold and a few other really important things that
1416 * we need to keep running. Once main has stopped, we should be able
1417 * to umount the tmpfs /data, then mount the encrypted /data.
1418 * We then restart the class main, and also the class late_start.
1419 * At the moment, I've only put a few things in late_start that I know
1420 * are not needed to bring up the framework, and that also cause problems
1421 * with unmounting the tmpfs /data, but I hope to add add more services
1422 * to the late_start class as we optimize this to decrease the delay
1423 * till the user is asked for the password to the filesystem.
1424 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001425
Paul Lawrencef4faa572014-01-29 13:31:03 -08001426 /* The init files are setup to stop the class main when vold.decrypt is
1427 * set to trigger_reset_main.
1428 */
1429 property_set("vold.decrypt", "trigger_reset_main");
1430 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001431
Paul Lawrencef4faa572014-01-29 13:31:03 -08001432 /* Ugh, shutting down the framework is not synchronous, so until it
1433 * can be fixed, this horrible hack will wait a moment for it all to
1434 * shut down before proceeding. Without it, some devices cannot
1435 * restart the graphics services.
1436 */
1437 sleep(2);
1438 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001439
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001440 /* Now that the framework is shutdown, we should be able to umount()
1441 * the tmpfs filesystem, and mount the real one.
1442 */
1443
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001444 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1445 if (strlen(crypto_blkdev) == 0) {
1446 SLOGE("fs_crypto_blkdev not set\n");
1447 return -1;
1448 }
1449
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001450 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001451 /* If ro.crypto.readonly is set to 1, mount the decrypted
1452 * filesystem readonly. This is used when /data is mounted by
1453 * recovery mode.
1454 */
1455 char ro_prop[PROPERTY_VALUE_MAX];
1456 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001457 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001458 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001459 rec->flags |= MS_RDONLY;
1460 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001461
Ken Sumralle5032c42012-04-01 23:58:44 -07001462 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001463 int retries = RETRY_MOUNT_ATTEMPTS;
1464 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001465
1466 /*
1467 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1468 * partitions in the fsck domain.
1469 */
1470 if (setexeccon(secontextFsck())){
1471 SLOGE("Failed to setexeccon");
1472 return -1;
1473 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001474 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001475 crypto_blkdev, 0))
1476 != 0) {
1477 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1478 /* TODO: invoke something similar to
1479 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1480 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1481 SLOGI("Failed to mount %s because it is busy - waiting",
1482 crypto_blkdev);
1483 if (--retries) {
1484 sleep(RETRY_MOUNT_DELAY_SECONDS);
1485 } else {
1486 /* Let's hope that a reboot clears away whatever is keeping
1487 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001488 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001489 }
1490 } else {
1491 SLOGE("Failed to mount decrypted data");
1492 cryptfs_set_corrupt();
1493 cryptfs_trigger_restart_min_framework();
1494 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001495 if (setexeccon(NULL)) {
1496 SLOGE("Failed to setexeccon");
1497 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001498 return -1;
1499 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001500 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001501 if (setexeccon(NULL)) {
1502 SLOGE("Failed to setexeccon");
1503 return -1;
1504 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001505
Ken Sumralle5032c42012-04-01 23:58:44 -07001506 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001507 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001508 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001509
1510 /* startup service classes main and late_start */
1511 property_set("vold.decrypt", "trigger_restart_framework");
1512 SLOGD("Just triggered restart_framework\n");
1513
1514 /* Give it a few moments to get started */
1515 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001516 }
1517
Ken Sumrall0cc16632011-01-18 20:32:26 -08001518 if (rc == 0) {
1519 restart_successful = 1;
1520 }
1521
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001522 return rc;
1523}
1524
Paul Lawrencef4faa572014-01-29 13:31:03 -08001525int cryptfs_restart(void)
1526{
Paul Lawrence05335c32015-03-05 09:46:23 -08001527 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001528 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001529 SLOGE("cryptfs_restart not valid for file encryption:");
1530 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001531 }
1532
Paul Lawrencef4faa572014-01-29 13:31:03 -08001533 /* Call internal implementation forcing a restart of main service group */
1534 return cryptfs_restart_internal(1);
1535}
1536
Wei Wang4375f1b2017-02-24 17:43:01 -08001537static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001538{
1539 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001540 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001541 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001542
1543 property_get("ro.crypto.state", encrypted_state, "");
1544 if (strcmp(encrypted_state, "encrypted") ) {
1545 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001546 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001547 }
1548
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001549 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001550 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001551 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001552 }
1553
Ken Sumrall160b4d62013-04-22 12:15:39 -07001554 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001555 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001556
Ken Sumralle1a45852011-12-14 21:24:27 -08001557 /*
1558 * Only report this error if key_loc is a file and it exists.
1559 * If the device was never encrypted, and /data is not mountable for
1560 * some reason, returning 1 should prevent the UI from presenting the
1561 * a "enter password" screen, or worse, a "press button to wipe the
1562 * device" screen.
1563 */
1564 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1565 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001566 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001567 } else {
1568 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001569 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001570 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001571 }
1572
Paul Lawrence74f29f12014-08-28 15:54:10 -07001573 // Test for possible error flags
1574 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1575 SLOGE("Encryption process is partway completed\n");
1576 return CRYPTO_COMPLETE_PARTIAL;
1577 }
1578
1579 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1580 SLOGE("Encryption process was interrupted but cannot continue\n");
1581 return CRYPTO_COMPLETE_INCONSISTENT;
1582 }
1583
1584 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1585 SLOGE("Encryption is successful but data is corrupt\n");
1586 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001587 }
1588
1589 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001590 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001591}
1592
Paul Lawrencef4faa572014-01-29 13:31:03 -08001593static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001594 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001595{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001597 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598 char crypto_blkdev[MAXPATHLEN];
1599 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001600 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001601 unsigned int orig_failed_decrypt_count;
1602 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001603 int use_keymaster = 0;
1604 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001605 unsigned char* intermediate_key = 0;
1606 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001607 int N = 1 << crypt_ftr->N_factor;
1608 int r = 1 << crypt_ftr->r_factor;
1609 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001610
Paul Lawrencef4faa572014-01-29 13:31:03 -08001611 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1612 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001613
Paul Lawrencef4faa572014-01-29 13:31:03 -08001614 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001615 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1616 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001617 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001618 rc = -1;
1619 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001620 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001621 }
1622
Paul Crowleye2ee1522017-09-26 14:05:26 -07001623 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001624
Paul Lawrence74f29f12014-08-28 15:54:10 -07001625 // Create crypto block device - all (non fatal) code paths
1626 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001627 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1628 SLOGE("Error creating decrypted block device\n");
1629 rc = -1;
1630 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001631 }
1632
Paul Lawrence74f29f12014-08-28 15:54:10 -07001633 /* Work out if the problem is the password or the data */
1634 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1635 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001636
Paul Lawrence74f29f12014-08-28 15:54:10 -07001637 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1638 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1639 N, r, p, scrypted_intermediate_key,
1640 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001641
Paul Lawrence74f29f12014-08-28 15:54:10 -07001642 // Does the key match the crypto footer?
1643 if (rc == 0 && memcmp(scrypted_intermediate_key,
1644 crypt_ftr->scrypted_intermediate_key,
1645 sizeof(scrypted_intermediate_key)) == 0) {
1646 SLOGI("Password matches");
1647 rc = 0;
1648 } else {
1649 /* Try mounting the file system anyway, just in case the problem's with
1650 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001651 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1652 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001653 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001654 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001655 SLOGE("Error temp mounting decrypted block device\n");
1656 delete_crypto_blk_dev(label);
1657
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001658 rc = ++crypt_ftr->failed_decrypt_count;
1659 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001660 } else {
1661 /* Success! */
1662 SLOGI("Password did not match but decrypted drive mounted - continue");
1663 umount(tmp_mount_point);
1664 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001665 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001666 }
1667
1668 if (rc == 0) {
1669 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001670 if (orig_failed_decrypt_count != 0) {
1671 put_crypt_ftr_and_key(crypt_ftr);
1672 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001673
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001674 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001675 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001676 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001677
1678 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001679 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001680 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001681 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001682 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001683 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001684 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001685
Paul Lawrence74f29f12014-08-28 15:54:10 -07001686 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001687 use_keymaster = keymaster_check_compatibility();
1688 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001689 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001690 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1691 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1692 upgrade = 1;
1693 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001694 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001695 upgrade = 1;
1696 }
1697
1698 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001699 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1700 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001701 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001702 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001703 }
1704 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001705
1706 // Do not fail even if upgrade failed - machine is bootable
1707 // Note that if this code is ever hit, there is a *serious* problem
1708 // since KDFs should never fail. You *must* fix the kdf before
1709 // proceeding!
1710 if (rc) {
1711 SLOGW("Upgrade failed with error %d,"
1712 " but continuing with previous state",
1713 rc);
1714 rc = 0;
1715 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001716 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717 }
1718
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001719 errout:
1720 if (intermediate_key) {
1721 memset(intermediate_key, 0, intermediate_key_size);
1722 free(intermediate_key);
1723 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724 return rc;
1725}
1726
Ken Sumrall29d8da82011-05-18 17:20:07 -07001727/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001728 * Called by vold when it's asked to mount an encrypted external
1729 * storage volume. The incoming partition has no crypto header/footer,
1730 * as any metadata is been stored in a separate, small partition.
1731 *
1732 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001733 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001734int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1735 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001736 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001737 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001738 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001739 return -1;
1740 }
1741
1742 unsigned long nr_sec = 0;
1743 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001744 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001745
Ken Sumrall29d8da82011-05-18 17:20:07 -07001746 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001747 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001748 return -1;
1749 }
1750
Jeff Sharkey9c484982015-03-31 10:35:33 -07001751 struct crypt_mnt_ftr ext_crypt_ftr;
1752 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1753 ext_crypt_ftr.fs_size = nr_sec;
1754 ext_crypt_ftr.keysize = keysize;
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001755 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
1756 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001757
Paul Crowley5afbc622017-11-27 09:42:17 -08001758 return create_crypto_blk_dev(
1759 &ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label,
1760 e4crypt_is_native() ? CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE : 0);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001761}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001762
Jeff Sharkey9c484982015-03-31 10:35:33 -07001763/*
1764 * Called by vold when it's asked to unmount an encrypted external
1765 * storage volume.
1766 */
1767int cryptfs_revert_ext_volume(const char* label) {
1768 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001769}
1770
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001771int cryptfs_crypto_complete(void)
1772{
1773 return do_crypto_complete("/data");
1774}
1775
Paul Lawrencef4faa572014-01-29 13:31:03 -08001776int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1777{
1778 char encrypted_state[PROPERTY_VALUE_MAX];
1779 property_get("ro.crypto.state", encrypted_state, "");
1780 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1781 SLOGE("encrypted fs already validated or not running with encryption,"
1782 " aborting");
1783 return -1;
1784 }
1785
1786 if (get_crypt_ftr_and_key(crypt_ftr)) {
1787 SLOGE("Error getting crypt footer and key");
1788 return -1;
1789 }
1790
1791 return 0;
1792}
1793
Wei Wang4375f1b2017-02-24 17:43:01 -08001794int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001795{
Paul Lawrence05335c32015-03-05 09:46:23 -08001796 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001797 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001798 SLOGE("cryptfs_check_passwd not valid for file encryption");
1799 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001800 }
1801
Paul Lawrencef4faa572014-01-29 13:31:03 -08001802 struct crypt_mnt_ftr crypt_ftr;
1803 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001804
Paul Lawrencef4faa572014-01-29 13:31:03 -08001805 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001806 if (rc) {
1807 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001808 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001809 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001810
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001811 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001812 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1813 if (rc) {
1814 SLOGE("Password did not match");
1815 return rc;
1816 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001817
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001818 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1819 // Here we have a default actual password but a real password
1820 // we must test against the scrypted value
1821 // First, we must delete the crypto block device that
1822 // test_mount_encrypted_fs leaves behind as a side effect
1823 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1824 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1825 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1826 if (rc) {
1827 SLOGE("Default password did not match on reboot encryption");
1828 return rc;
1829 }
1830
1831 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1832 put_crypt_ftr_and_key(&crypt_ftr);
1833 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1834 if (rc) {
1835 SLOGE("Could not change password on reboot encryption");
1836 return rc;
1837 }
1838 }
1839
1840 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001841 cryptfs_clear_password();
1842 password = strdup(passwd);
1843 struct timespec now;
1844 clock_gettime(CLOCK_BOOTTIME, &now);
1845 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001846 }
1847
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001848 return rc;
1849}
1850
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001851int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001852{
1853 struct crypt_mnt_ftr crypt_ftr;
1854 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001855 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001856 char encrypted_state[PROPERTY_VALUE_MAX];
1857 int rc;
1858
1859 property_get("ro.crypto.state", encrypted_state, "");
1860 if (strcmp(encrypted_state, "encrypted") ) {
1861 SLOGE("device not encrypted, aborting");
1862 return -2;
1863 }
1864
1865 if (!master_key_saved) {
1866 SLOGE("encrypted fs not yet mounted, aborting");
1867 return -1;
1868 }
1869
1870 if (!saved_mount_point) {
1871 SLOGE("encrypted fs failed to save mount point, aborting");
1872 return -1;
1873 }
1874
Ken Sumrall160b4d62013-04-22 12:15:39 -07001875 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001876 SLOGE("Error getting crypt footer and key\n");
1877 return -1;
1878 }
1879
1880 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1881 /* If the device has no password, then just say the password is valid */
1882 rc = 0;
1883 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001884 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001885 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1886 /* They match, the password is correct */
1887 rc = 0;
1888 } else {
1889 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1890 sleep(1);
1891 rc = 1;
1892 }
1893 }
1894
1895 return rc;
1896}
1897
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001898/* Initialize a crypt_mnt_ftr structure. The keysize is
1899 * defaulted to 16 bytes, and the filesystem size to 0.
1900 * Presumably, at a minimum, the caller will update the
1901 * filesystem size and crypto_type_name after calling this function.
1902 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001903static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001904{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001905 off64_t off;
1906
1907 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001908 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001909 ftr->major_version = CURRENT_MAJOR_VERSION;
1910 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001911 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001912 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001913
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001914 switch (keymaster_check_compatibility()) {
1915 case 1:
1916 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1917 break;
1918
1919 case 0:
1920 ftr->kdf_type = KDF_SCRYPT;
1921 break;
1922
1923 default:
1924 SLOGE("keymaster_check_compatibility failed");
1925 return -1;
1926 }
1927
Kenny Rootc4c70f12013-06-14 12:11:38 -07001928 get_device_scrypt_params(ftr);
1929
Ken Sumrall160b4d62013-04-22 12:15:39 -07001930 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1931 if (get_crypt_ftr_info(NULL, &off) == 0) {
1932 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1933 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1934 ftr->persist_data_size;
1935 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001936
1937 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001938}
1939
Ken Sumrall29d8da82011-05-18 17:20:07 -07001940static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001941{
Ken Sumralle550f782013-08-20 13:48:23 -07001942 const char *args[10];
1943 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1944 int num_args;
1945 int status;
1946 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001947 int rc = -1;
1948
Ken Sumrall29d8da82011-05-18 17:20:07 -07001949 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001950 args[0] = "/system/bin/mke2fs";
1951 args[1] = "-M";
1952 args[2] = "/data";
1953 args[3] = "-b";
1954 args[4] = "4096";
1955 args[5] = "-t";
1956 args[6] = "ext4";
1957 args[7] = crypto_blkdev;
1958 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1959 args[8] = size_str;
1960 num_args = 9;
Ken Sumralle550f782013-08-20 13:48:23 -07001961 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1962 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001963 } else if (type == F2FS_FS) {
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001964 args[0] = "/system/bin/make_f2fs";
Jaegeuk Kim8de9f062017-11-01 10:35:30 -07001965 args[1] = "-f";
JP Abgrall62c7af32014-06-16 13:01:23 -07001966 args[2] = "-d1";
Jaegeuk Kim8de9f062017-11-01 10:35:30 -07001967 args[3] = "-O";
1968 args[4] = "encrypt";
1969 args[5] = "-O";
1970 args[6] = "quota";
1971 args[7] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001972 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
Jaegeuk Kim8de9f062017-11-01 10:35:30 -07001973 args[8] = size_str;
1974 num_args = 9;
1975 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s\n",
1976 args[0], args[1], args[2], args[3], args[4], args[5],
1977 args[6], args[7], args[8]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001978 } else {
1979 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1980 return -1;
1981 }
1982
Ken Sumralle550f782013-08-20 13:48:23 -07001983 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1984
1985 if (tmp != 0) {
1986 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001987 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001988 if (WIFEXITED(status)) {
1989 if (WEXITSTATUS(status)) {
1990 SLOGE("Error creating filesystem on %s, exit status %d ",
1991 crypto_blkdev, WEXITSTATUS(status));
1992 } else {
1993 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1994 rc = 0;
1995 }
1996 } else {
1997 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1998 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001999 }
2000
2001 return rc;
2002}
2003
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002004#define CRYPTO_ENABLE_WIPE 1
2005#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002006
2007#define FRAMEWORK_BOOT_WAIT 60
2008
Paul Lawrence87999172014-02-20 12:21:31 -08002009static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2010{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002011 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002012 if (fd == -1) {
2013 SLOGE("Error opening file %s", filename);
2014 return -1;
2015 }
2016
2017 char block[CRYPT_INPLACE_BUFSIZE];
2018 memset(block, 0, sizeof(block));
2019 if (unix_read(fd, block, sizeof(block)) < 0) {
2020 SLOGE("Error reading file %s", filename);
2021 close(fd);
2022 return -1;
2023 }
2024
2025 close(fd);
2026
2027 SHA256_CTX c;
2028 SHA256_Init(&c);
2029 SHA256_Update(&c, block, sizeof(block));
2030 SHA256_Final(buf, &c);
2031
2032 return 0;
2033}
2034
JP Abgrall62c7af32014-06-16 13:01:23 -07002035static int get_fs_type(struct fstab_rec *rec)
2036{
2037 if (!strcmp(rec->fs_type, "ext4")) {
2038 return EXT4_FS;
2039 } else if (!strcmp(rec->fs_type, "f2fs")) {
2040 return F2FS_FS;
2041 } else {
2042 return -1;
2043 }
2044}
2045
Paul Lawrence87999172014-02-20 12:21:31 -08002046static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2047 char *crypto_blkdev, char *real_blkdev,
2048 int previously_encrypted_upto)
2049{
2050 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002051 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002052
Paul Lawrence87999172014-02-20 12:21:31 -08002053 /* The size of the userdata partition, and add in the vold volumes below */
2054 tot_encryption_size = crypt_ftr->fs_size;
2055
2056 if (how == CRYPTO_ENABLE_WIPE) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002057 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
JP Abgrall62c7af32014-06-16 13:01:23 -07002058 int fs_type = get_fs_type(rec);
2059 if (fs_type < 0) {
2060 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2061 return -1;
2062 }
2063 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002064 } else if (how == CRYPTO_ENABLE_INPLACE) {
2065 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2066 crypt_ftr->fs_size, &cur_encryption_done,
2067 tot_encryption_size,
2068 previously_encrypted_upto);
2069
JP Abgrall7fc1de82014-10-10 18:43:41 -07002070 if (rc == ENABLE_INPLACE_ERR_DEV) {
2071 /* Hack for b/17898962 */
2072 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
Josh Gaofec44372017-08-28 13:22:55 -07002073 cryptfs_reboot(RebootType::reboot);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002074 }
2075
Paul Lawrence73d7a022014-06-09 14:10:09 -07002076 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002077 crypt_ftr->encrypted_upto = cur_encryption_done;
2078 }
2079
Paul Lawrence73d7a022014-06-09 14:10:09 -07002080 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002081 /* The inplace routine never actually sets the progress to 100% due
2082 * to the round down nature of integer division, so set it here */
2083 property_set("vold.encrypt_progress", "100");
2084 }
2085 } else {
2086 /* Shouldn't happen */
2087 SLOGE("cryptfs_enable: internal error, unknown option\n");
2088 rc = -1;
2089 }
2090
2091 return rc;
2092}
2093
Paul Crowleyb64933a2017-10-31 08:25:55 -07002094static int vold_unmountAll(void) {
2095 VolumeManager* vm = VolumeManager::Instance();
2096 return vm->unmountAll();
2097}
2098
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002099int cryptfs_enable_internal(const char *howarg, int crypt_type, const char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002100 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002101{
2102 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002103 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002104 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002105 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002106 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002107 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002108 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002109 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002110 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002111 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002112 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002113 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002114 bool onlyCreateHeader = false;
2115 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002116
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002117 if (!strcmp(howarg, "wipe")) {
2118 how = CRYPTO_ENABLE_WIPE;
2119 } else if (! strcmp(howarg, "inplace")) {
2120 how = CRYPTO_ENABLE_INPLACE;
2121 } else {
2122 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002123 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002124 }
2125
Paul Lawrence87999172014-02-20 12:21:31 -08002126 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002127 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2128 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2129 /* An encryption was underway and was interrupted */
2130 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2131 crypt_ftr.encrypted_upto = 0;
2132 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002133
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002134 /* At this point, we are in an inconsistent state. Until we successfully
2135 complete encryption, a reboot will leave us broken. So mark the
2136 encryption failed in case that happens.
2137 On successfully completing encryption, remove this flag */
2138 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002139
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002140 put_crypt_ftr_and_key(&crypt_ftr);
2141 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2142 if (!check_ftr_sha(&crypt_ftr)) {
2143 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2144 put_crypt_ftr_and_key(&crypt_ftr);
2145 goto error_unencrypted;
2146 }
2147
2148 /* Doing a reboot-encryption*/
2149 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2150 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2151 rebootEncryption = true;
2152 }
Paul Lawrence87999172014-02-20 12:21:31 -08002153 }
2154
2155 property_get("ro.crypto.state", encrypted_state, "");
2156 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2157 SLOGE("Device is already running encrypted, aborting");
2158 goto error_unencrypted;
2159 }
2160
2161 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002162 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2163 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002164
Ken Sumrall3ed82362011-01-28 23:31:16 -08002165 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002166 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002167 if (fd == -1) {
2168 SLOGE("Cannot open block device %s\n", real_blkdev);
2169 goto error_unencrypted;
2170 }
2171 unsigned long nr_sec;
2172 get_blkdev_size(fd, &nr_sec);
2173 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002174 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2175 goto error_unencrypted;
2176 }
2177 close(fd);
2178
2179 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002180 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002181 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002182 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002183 if (fs_size_sec == 0)
2184 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2185
Paul Lawrence87999172014-02-20 12:21:31 -08002186 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002187
2188 if (fs_size_sec > max_fs_size_sec) {
2189 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2190 goto error_unencrypted;
2191 }
2192 }
2193
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002194 /* Get a wakelock as this may take a while, and we don't want the
2195 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2196 * wants to keep the screen on, it can grab a full wakelock.
2197 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002198 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002199 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002201 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002202 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002203 */
2204 property_set("vold.decrypt", "trigger_shutdown_framework");
2205 SLOGD("Just asked init to shut down class main\n");
2206
Jeff Sharkey9c484982015-03-31 10:35:33 -07002207 /* Ask vold to unmount all devices that it manages */
2208 if (vold_unmountAll()) {
2209 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002210 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002211
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002212 /* no_ui means we are being called from init, not settings.
2213 Now we always reboot from settings, so !no_ui means reboot
2214 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002215 if (!no_ui) {
2216 /* Try fallback, which is to reboot and try there */
2217 onlyCreateHeader = true;
2218 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2219 if (breadcrumb == 0) {
2220 SLOGE("Failed to create breadcrumb file");
2221 goto error_shutting_down;
2222 }
2223 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002224 }
2225
2226 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002227 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002228 /* Now that /data is unmounted, we need to mount a tmpfs
2229 * /data, set a property saying we're doing inplace encryption,
2230 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002231 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002232 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002233 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002234 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002235 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002236 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002237
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002238 /* restart the framework. */
2239 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002240 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002241
Ken Sumrall92736ef2012-10-17 20:57:14 -07002242 /* Ugh, shutting down the framework is not synchronous, so until it
2243 * can be fixed, this horrible hack will wait a moment for it all to
2244 * shut down before proceeding. Without it, some devices cannot
2245 * restart the graphics services.
2246 */
2247 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002248 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002249
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002250 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002251 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002252 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002253 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2254 goto error_shutting_down;
2255 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002256
Paul Lawrence87999172014-02-20 12:21:31 -08002257 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2258 crypt_ftr.fs_size = nr_sec
2259 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2260 } else {
2261 crypt_ftr.fs_size = nr_sec;
2262 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002263 /* At this point, we are in an inconsistent state. Until we successfully
2264 complete encryption, a reboot will leave us broken. So mark the
2265 encryption failed in case that happens.
2266 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002267 if (onlyCreateHeader) {
2268 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2269 } else {
2270 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2271 }
Paul Lawrence87999172014-02-20 12:21:31 -08002272 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002273 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002274
Paul Lawrence87999172014-02-20 12:21:31 -08002275 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002276 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2277 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002278 SLOGE("Cannot create encrypted master key\n");
2279 goto error_shutting_down;
2280 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002281
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002282 /* Replace scrypted intermediate key if we are preparing for a reboot */
2283 if (onlyCreateHeader) {
2284 unsigned char fake_master_key[KEY_LEN_BYTES];
2285 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2286 memset(fake_master_key, 0, sizeof(fake_master_key));
2287 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2288 encrypted_fake_master_key, &crypt_ftr);
2289 }
2290
Paul Lawrence87999172014-02-20 12:21:31 -08002291 /* Write the key to the end of the partition */
2292 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002293
Paul Lawrence87999172014-02-20 12:21:31 -08002294 /* If any persistent data has been remembered, save it.
2295 * If none, create a valid empty table and save that.
2296 */
2297 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002298 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002299 if (pdata) {
2300 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2301 persist_data = pdata;
2302 }
2303 }
2304 if (persist_data) {
2305 save_persistent_data();
2306 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002307 }
2308
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002309 if (onlyCreateHeader) {
2310 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002311 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002312 }
2313
2314 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002315 /* startup service classes main and late_start */
2316 property_set("vold.decrypt", "trigger_restart_min_framework");
2317 SLOGD("Just triggered restart_min_framework\n");
2318
2319 /* OK, the framework is restarted and will soon be showing a
2320 * progress bar. Time to setup an encrypted mapping, and
2321 * either write a new filesystem, or encrypt in place updating
2322 * the progress bar as we work.
2323 */
2324 }
2325
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002326 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002327 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002328 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002329
Paul Lawrence87999172014-02-20 12:21:31 -08002330 /* If we are continuing, check checksums match */
2331 rc = 0;
2332 if (previously_encrypted_upto) {
2333 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2334 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002335
Paul Lawrence87999172014-02-20 12:21:31 -08002336 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2337 sizeof(hash_first_block)) != 0) {
2338 SLOGE("Checksums do not match - trigger wipe");
2339 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002340 }
2341 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002342
Paul Lawrence87999172014-02-20 12:21:31 -08002343 if (!rc) {
2344 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2345 crypto_blkdev, real_blkdev,
2346 previously_encrypted_upto);
2347 }
2348
2349 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002350 if (!rc && how == CRYPTO_ENABLE_INPLACE
2351 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002352 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2353 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002354 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002355 SLOGE("Error calculating checksum for continuing encryption");
2356 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002357 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002358 }
2359
2360 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002361 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002362
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002363 if (! rc) {
2364 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002365 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002366
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002367 if (how == CRYPTO_ENABLE_INPLACE
2368 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002369 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2370 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002371 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002372 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002373
Paul Lawrence6bfed202014-07-28 12:47:22 -07002374 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002375
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002376 if (how == CRYPTO_ENABLE_WIPE
2377 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002378 char value[PROPERTY_VALUE_MAX];
2379 property_get("ro.crypto.state", value, "");
2380 if (!strcmp(value, "")) {
2381 /* default encryption - continue first boot sequence */
2382 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08002383 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002384 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002385 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2386 // Bring up cryptkeeper that will check the password and set it
2387 property_set("vold.decrypt", "trigger_shutdown_framework");
2388 sleep(2);
2389 property_set("vold.encrypt_progress", "");
2390 cryptfs_trigger_restart_min_framework();
2391 } else {
2392 cryptfs_check_passwd(DEFAULT_PASSWORD);
2393 cryptfs_restart_internal(1);
2394 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002395 return 0;
2396 } else {
2397 sleep(2); /* Give the UI a chance to show 100% progress */
Josh Gaofec44372017-08-28 13:22:55 -07002398 cryptfs_reboot(RebootType::reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002399 }
Paul Lawrence87999172014-02-20 12:21:31 -08002400 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002401 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002402 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002403 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002404 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002405 char value[PROPERTY_VALUE_MAX];
2406
Ken Sumrall319369a2012-06-27 16:30:18 -07002407 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002408 if (!strcmp(value, "1")) {
2409 /* wipe data if encryption failed */
2410 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002411 std::string err;
2412 const std::vector<std::string> options = {
2413 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2414 };
2415 if (!write_bootloader_message(options, &err)) {
2416 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002417 }
Josh Gaofec44372017-08-28 13:22:55 -07002418 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002419 } else {
2420 /* set property to trigger dialog */
2421 property_set("vold.encrypt_progress", "error_partially_encrypted");
2422 release_wake_lock(lockid);
2423 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002424 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002425 }
2426
Ken Sumrall3ed82362011-01-28 23:31:16 -08002427 /* hrm, the encrypt step claims success, but the reboot failed.
2428 * This should not happen.
2429 * Set the property and return. Hope the framework can deal with it.
2430 */
2431 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002432 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002433 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002434
2435error_unencrypted:
2436 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002437 if (lockid[0]) {
2438 release_wake_lock(lockid);
2439 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002440 return -1;
2441
2442error_shutting_down:
2443 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2444 * but the framework is stopped and not restarted to show the error, so it's up to
2445 * vold to restart the system.
2446 */
2447 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002448 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002449
2450 /* shouldn't get here */
2451 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002452 if (lockid[0]) {
2453 release_wake_lock(lockid);
2454 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002455 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002456}
2457
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002458int cryptfs_enable(const char *howarg, int type, const char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002459{
Paul Lawrence569649f2015-09-09 12:13:00 -07002460 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002461}
2462
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002463int cryptfs_enable_default(const char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002464{
2465 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07002466 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002467}
2468
2469int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002470{
Paul Crowley38132a12016-02-09 09:50:32 +00002471 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002472 SLOGE("cryptfs_changepw not valid for file encryption");
2473 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002474 }
2475
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002476 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002477 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002478
2479 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002480 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002481 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002482 return -1;
2483 }
2484
Paul Lawrencef4faa572014-01-29 13:31:03 -08002485 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2486 SLOGE("Invalid crypt_type %d", crypt_type);
2487 return -1;
2488 }
2489
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002490 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002491 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002492 SLOGE("Error getting crypt footer and key");
2493 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002494 }
2495
Paul Lawrencef4faa572014-01-29 13:31:03 -08002496 crypt_ftr.crypt_type = crypt_type;
2497
JP Abgrall933216c2015-02-11 13:44:32 -08002498 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002499 : newpw,
2500 crypt_ftr.salt,
2501 saved_master_key,
2502 crypt_ftr.master_key,
2503 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002504 if (rc) {
2505 SLOGE("Encrypt master key failed: %d", rc);
2506 return -1;
2507 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002508 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002509 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002510
2511 return 0;
2512}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002513
Rubin Xu85c01f92014-10-13 12:49:54 +01002514static unsigned int persist_get_max_entries(int encrypted) {
2515 struct crypt_mnt_ftr crypt_ftr;
2516 unsigned int dsize;
2517 unsigned int max_persistent_entries;
2518
2519 /* If encrypted, use the values from the crypt_ftr, otherwise
2520 * use the values for the current spec.
2521 */
2522 if (encrypted) {
2523 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2524 return -1;
2525 }
2526 dsize = crypt_ftr.persist_data_size;
2527 } else {
2528 dsize = CRYPT_PERSIST_DATA_SIZE;
2529 }
2530
2531 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2532 sizeof(struct crypt_persist_entry);
2533
2534 return max_persistent_entries;
2535}
2536
2537static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002538{
2539 unsigned int i;
2540
2541 if (persist_data == NULL) {
2542 return -1;
2543 }
2544 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2545 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2546 /* We found it! */
2547 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2548 return 0;
2549 }
2550 }
2551
2552 return -1;
2553}
2554
Rubin Xu85c01f92014-10-13 12:49:54 +01002555static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002556{
2557 unsigned int i;
2558 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002559 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002560
2561 if (persist_data == NULL) {
2562 return -1;
2563 }
2564
Rubin Xu85c01f92014-10-13 12:49:54 +01002565 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002566
2567 num = persist_data->persist_valid_entries;
2568
2569 for (i = 0; i < num; i++) {
2570 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2571 /* We found an existing entry, update it! */
2572 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2573 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2574 return 0;
2575 }
2576 }
2577
2578 /* We didn't find it, add it to the end, if there is room */
2579 if (persist_data->persist_valid_entries < max_persistent_entries) {
2580 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2581 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2582 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2583 persist_data->persist_valid_entries++;
2584 return 0;
2585 }
2586
2587 return -1;
2588}
2589
Rubin Xu85c01f92014-10-13 12:49:54 +01002590/**
2591 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2592 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2593 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002594int match_multi_entry(const char *key, const char *field, unsigned index) {
2595 std::string key_ = key;
2596 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002597
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002598 std::string parsed_field;
2599 unsigned parsed_index;
2600
2601 std::string::size_type split = key_.find_last_of('_');
2602 if (split == std::string::npos) {
2603 parsed_field = key_;
2604 parsed_index = 0;
2605 } else {
2606 parsed_field = key_.substr(0, split);
2607 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002608 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002609
2610 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002611}
2612
2613/*
2614 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2615 * remaining entries starting from index will be deleted.
2616 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2617 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2618 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2619 *
2620 */
2621static int persist_del_keys(const char *fieldname, unsigned index)
2622{
2623 unsigned int i;
2624 unsigned int j;
2625 unsigned int num;
2626
2627 if (persist_data == NULL) {
2628 return PERSIST_DEL_KEY_ERROR_OTHER;
2629 }
2630
2631 num = persist_data->persist_valid_entries;
2632
2633 j = 0; // points to the end of non-deleted entries.
2634 // Filter out to-be-deleted entries in place.
2635 for (i = 0; i < num; i++) {
2636 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2637 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2638 j++;
2639 }
2640 }
2641
2642 if (j < num) {
2643 persist_data->persist_valid_entries = j;
2644 // Zeroise the remaining entries
2645 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2646 return PERSIST_DEL_KEY_OK;
2647 } else {
2648 // Did not find an entry matching the given fieldname
2649 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2650 }
2651}
2652
2653static int persist_count_keys(const char *fieldname)
2654{
2655 unsigned int i;
2656 unsigned int count;
2657
2658 if (persist_data == NULL) {
2659 return -1;
2660 }
2661
2662 count = 0;
2663 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2664 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2665 count++;
2666 }
2667 }
2668
2669 return count;
2670}
2671
Ken Sumrall160b4d62013-04-22 12:15:39 -07002672/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002673int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002674{
Paul Crowley38132a12016-02-09 09:50:32 +00002675 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002676 SLOGE("Cannot get field when file encrypted");
2677 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002678 }
2679
Ken Sumrall160b4d62013-04-22 12:15:39 -07002680 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002681 /* CRYPTO_GETFIELD_OK is success,
2682 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2683 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2684 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002685 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002686 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2687 int i;
2688 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002689
2690 if (persist_data == NULL) {
2691 load_persistent_data();
2692 if (persist_data == NULL) {
2693 SLOGE("Getfield error, cannot load persistent data");
2694 goto out;
2695 }
2696 }
2697
Rubin Xu85c01f92014-10-13 12:49:54 +01002698 // Read value from persistent entries. If the original value is split into multiple entries,
2699 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002700 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002701 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2702 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2703 // value too small
2704 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2705 goto out;
2706 }
2707 rc = CRYPTO_GETFIELD_OK;
2708
2709 for (i = 1; /* break explicitly */; i++) {
2710 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2711 (int) sizeof(temp_field)) {
2712 // If the fieldname is very long, we stop as soon as it begins to overflow the
2713 // maximum field length. At this point we have in fact fully read out the original
2714 // value because cryptfs_setfield would not allow fields with longer names to be
2715 // written in the first place.
2716 break;
2717 }
2718 if (!persist_get_key(temp_field, temp_value)) {
2719 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2720 // value too small.
2721 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2722 goto out;
2723 }
2724 } else {
2725 // Exhaust all entries.
2726 break;
2727 }
2728 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002729 } else {
2730 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002731 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002732 }
2733
2734out:
2735 return rc;
2736}
2737
2738/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002739int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002740{
Paul Crowley38132a12016-02-09 09:50:32 +00002741 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002742 SLOGE("Cannot set field when file encrypted");
2743 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002744 }
2745
Ken Sumrall160b4d62013-04-22 12:15:39 -07002746 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002747 /* 0 is success, negative values are error */
2748 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002749 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002750 unsigned int field_id;
2751 char temp_field[PROPERTY_KEY_MAX];
2752 unsigned int num_entries;
2753 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002754
2755 if (persist_data == NULL) {
2756 load_persistent_data();
2757 if (persist_data == NULL) {
2758 SLOGE("Setfield error, cannot load persistent data");
2759 goto out;
2760 }
2761 }
2762
2763 property_get("ro.crypto.state", encrypted_state, "");
2764 if (!strcmp(encrypted_state, "encrypted") ) {
2765 encrypted = 1;
2766 }
2767
Rubin Xu85c01f92014-10-13 12:49:54 +01002768 // Compute the number of entries required to store value, each entry can store up to
2769 // (PROPERTY_VALUE_MAX - 1) chars
2770 if (strlen(value) == 0) {
2771 // Empty value also needs one entry to store.
2772 num_entries = 1;
2773 } else {
2774 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2775 }
2776
2777 max_keylen = strlen(fieldname);
2778 if (num_entries > 1) {
2779 // Need an extra "_%d" suffix.
2780 max_keylen += 1 + log10(num_entries);
2781 }
2782 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2783 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002784 goto out;
2785 }
2786
Rubin Xu85c01f92014-10-13 12:49:54 +01002787 // Make sure we have enough space to write the new value
2788 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2789 persist_get_max_entries(encrypted)) {
2790 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2791 goto out;
2792 }
2793
2794 // Now that we know persist_data has enough space for value, let's delete the old field first
2795 // to make up space.
2796 persist_del_keys(fieldname, 0);
2797
2798 if (persist_set_key(fieldname, value, encrypted)) {
2799 // fail to set key, should not happen as we have already checked the available space
2800 SLOGE("persist_set_key() error during setfield()");
2801 goto out;
2802 }
2803
2804 for (field_id = 1; field_id < num_entries; field_id++) {
2805 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
2806
2807 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2808 // fail to set key, should not happen as we have already checked the available space.
2809 SLOGE("persist_set_key() error during setfield()");
2810 goto out;
2811 }
2812 }
2813
Ken Sumrall160b4d62013-04-22 12:15:39 -07002814 /* If we are running encrypted, save the persistent data now */
2815 if (encrypted) {
2816 if (save_persistent_data()) {
2817 SLOGE("Setfield error, cannot save persistent data");
2818 goto out;
2819 }
2820 }
2821
Rubin Xu85c01f92014-10-13 12:49:54 +01002822 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002823
2824out:
2825 return rc;
2826}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002827
2828/* Checks userdata. Attempt to mount the volume if default-
2829 * encrypted.
2830 * On success trigger next init phase and return 0.
2831 * Currently do not handle failure - see TODO below.
2832 */
2833int cryptfs_mount_default_encrypted(void)
2834{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002835 int crypt_type = cryptfs_get_password_type();
2836 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2837 SLOGE("Bad crypt type - error");
2838 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2839 SLOGD("Password is not default - "
2840 "starting min framework to prompt");
2841 property_set("vold.decrypt", "trigger_restart_min_framework");
2842 return 0;
2843 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2844 SLOGD("Password is default - restarting filesystem");
2845 cryptfs_restart_internal(0);
2846 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002847 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002848 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002849 }
2850
Paul Lawrence6bfed202014-07-28 12:47:22 -07002851 /** Corrupt. Allow us to boot into framework, which will detect bad
2852 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002853 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002854 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002855 return 0;
2856}
2857
2858/* Returns type of the password, default, pattern, pin or password.
2859 */
2860int cryptfs_get_password_type(void)
2861{
Paul Crowley38132a12016-02-09 09:50:32 +00002862 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002863 SLOGE("cryptfs_get_password_type not valid for file encryption");
2864 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002865 }
2866
Paul Lawrencef4faa572014-01-29 13:31:03 -08002867 struct crypt_mnt_ftr crypt_ftr;
2868
2869 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2870 SLOGE("Error getting crypt footer and key\n");
2871 return -1;
2872 }
2873
Paul Lawrence6bfed202014-07-28 12:47:22 -07002874 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2875 return -1;
2876 }
2877
Paul Lawrencef4faa572014-01-29 13:31:03 -08002878 return crypt_ftr.crypt_type;
2879}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002880
Paul Lawrence05335c32015-03-05 09:46:23 -08002881const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002882{
Paul Crowley38132a12016-02-09 09:50:32 +00002883 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002884 SLOGE("cryptfs_get_password not valid for file encryption");
2885 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002886 }
2887
Paul Lawrence399317e2014-03-10 13:20:50 -07002888 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002889 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002890 if (now.tv_sec < password_expiry_time) {
2891 return password;
2892 } else {
2893 cryptfs_clear_password();
2894 return 0;
2895 }
2896}
2897
2898void cryptfs_clear_password()
2899{
2900 if (password) {
2901 size_t len = strlen(password);
2902 memset(password, 0, len);
2903 free(password);
2904 password = 0;
2905 password_expiry_time = 0;
2906 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002907}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002908
Paul Lawrence0c247462015-10-29 10:30:57 -07002909int cryptfs_isConvertibleToFBE()
2910{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002911 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002912 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2913}