blob: 427772c98981f123d9c8704d52b07416976ac562 [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 Crowley73473332017-11-21 15:43:51 -080099static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
100
Jason parks70a4b3f2011-01-28 10:10:47 -0600101static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700102static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600103static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700104static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800105
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700106/* Should we use keymaster? */
107static int keymaster_check_compatibility()
108{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000109 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700110}
111
112/* Create a new keymaster key and store it in this footer */
113static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
114{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800115 if (ftr->keymaster_blob_size) {
116 SLOGI("Already have key");
117 return 0;
118 }
119
Janis Danisevskis015ec302017-01-31 11:31:08 +0000120 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
121 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
122 &ftr->keymaster_blob_size);
123 if (rc) {
124 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800125 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000126 ftr->keymaster_blob_size = 0;
127 }
128 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700129 return -1;
130 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000131 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700132}
133
Shawn Willdene17a9c42014-09-08 13:04:08 -0600134/* This signs the given object using the keymaster key. */
135static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600136 const unsigned char *object,
137 const size_t object_size,
138 unsigned char **signature,
139 size_t *signature_size)
140{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600141 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600142 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600143 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600144
Shawn Willdene17a9c42014-09-08 13:04:08 -0600145 // To sign a message with RSA, the message must satisfy two
146 // constraints:
147 //
148 // 1. The message, when interpreted as a big-endian numeric value, must
149 // be strictly less than the public modulus of the RSA key. Note
150 // that because the most significant bit of the public modulus is
151 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
152 // key), an n-bit message with most significant bit 0 always
153 // satisfies this requirement.
154 //
155 // 2. The message must have the same length in bits as the public
156 // modulus of the RSA key. This requirement isn't mathematically
157 // necessary, but is necessary to ensure consistency in
158 // implementations.
159 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600160 case KDF_SCRYPT_KEYMASTER:
161 // This ensures the most significant byte of the signed message
162 // is zero. We could have zero-padded to the left instead, but
163 // this approach is slightly more robust against changes in
164 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600165 // so) because we really should be using a proper deterministic
166 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800167 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600168 SLOGI("Signing safely-padded object");
169 break;
170 default:
171 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000172 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600173 }
Paul Crowley73473332017-11-21 15:43:51 -0800174 for (;;) {
175 auto result = keymaster_sign_object_for_cryptfs_scrypt(
176 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
177 to_sign_size, signature, signature_size);
178 switch (result) {
179 case KeymasterSignResult::ok:
180 return 0;
181 case KeymasterSignResult::upgrade:
182 break;
183 default:
184 return -1;
185 }
186 SLOGD("Upgrading key");
187 if (keymaster_upgrade_key_for_cryptfs_scrypt(
188 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
189 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
190 &ftr->keymaster_blob_size) != 0) {
191 SLOGE("Failed to upgrade key");
192 return -1;
193 }
194 if (put_crypt_ftr_and_key(ftr) != 0) {
195 SLOGE("Failed to write upgraded key to disk");
196 }
197 SLOGD("Key upgraded successfully");
198 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600199}
200
Paul Lawrence399317e2014-03-10 13:20:50 -0700201/* Store password when userdata is successfully decrypted and mounted.
202 * Cleared by cryptfs_clear_password
203 *
204 * To avoid a double prompt at boot, we need to store the CryptKeeper
205 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
206 * Since the entire framework is torn down and rebuilt after encryption,
207 * we have to use a daemon or similar to store the password. Since vold
208 * is secured against IPC except from system processes, it seems a reasonable
209 * place to store this.
210 *
211 * password should be cleared once it has been used.
212 *
213 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800214 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700215static char* password = 0;
216static int password_expiry_time = 0;
217static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800218
Josh Gaofec44372017-08-28 13:22:55 -0700219enum class RebootType {reboot, recovery, shutdown};
220static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700221{
Josh Gaofec44372017-08-28 13:22:55 -0700222 switch (rt) {
223 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800224 property_set(ANDROID_RB_PROPERTY, "reboot");
225 break;
226
Josh Gaofec44372017-08-28 13:22:55 -0700227 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800228 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
229 break;
230
Josh Gaofec44372017-08-28 13:22:55 -0700231 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800232 property_set(ANDROID_RB_PROPERTY, "shutdown");
233 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700234 }
Paul Lawrence87999172014-02-20 12:21:31 -0800235
Ken Sumralladfba362013-06-04 16:37:52 -0700236 sleep(20);
237
238 /* Shouldn't get here, reboot should happen before sleep times out */
239 return;
240}
241
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800242static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
243{
244 memset(io, 0, dataSize);
245 io->data_size = dataSize;
246 io->data_start = sizeof(struct dm_ioctl);
247 io->version[0] = 4;
248 io->version[1] = 0;
249 io->version[2] = 0;
250 io->flags = flags;
251 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100252 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800253 }
254}
255
Kenny Rootc4c70f12013-06-14 12:11:38 -0700256/**
257 * Gets the default device scrypt parameters for key derivation time tuning.
258 * The parameters should lead to about one second derivation time for the
259 * given device.
260 */
261static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700262 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000263 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700264
Paul Crowley63c18d32016-02-10 14:02:47 +0000265 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
266 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
267 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
268 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700269 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000270 ftr->N_factor = Nf;
271 ftr->r_factor = rf;
272 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700273}
274
Ken Sumrall3ed82362011-01-28 23:31:16 -0800275static unsigned int get_fs_size(char *dev)
276{
277 int fd, block_size;
278 struct ext4_super_block sb;
279 off64_t len;
280
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700281 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800282 SLOGE("Cannot open device to get filesystem size ");
283 return 0;
284 }
285
286 if (lseek64(fd, 1024, SEEK_SET) < 0) {
287 SLOGE("Cannot seek to superblock");
288 return 0;
289 }
290
291 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
292 SLOGE("Cannot read superblock");
293 return 0;
294 }
295
296 close(fd);
297
Daniel Rosenberge82df162014-08-15 22:19:23 +0000298 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
299 SLOGE("Not a valid ext4 superblock");
300 return 0;
301 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800302 block_size = 1024 << sb.s_log_block_size;
303 /* compute length in bytes */
304 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
305
306 /* return length in sectors */
307 return (unsigned int) (len / 512);
308}
309
Ken Sumrall160b4d62013-04-22 12:15:39 -0700310static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
311{
312 static int cached_data = 0;
313 static off64_t cached_off = 0;
314 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
315 int fd;
316 char key_loc[PROPERTY_VALUE_MAX];
317 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700318 int rc = -1;
319
320 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700321 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700322
323 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700324 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700325 SLOGE("Cannot open real block device %s\n", real_blkdev);
326 return -1;
327 }
328
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900329 unsigned long nr_sec = 0;
330 get_blkdev_size(fd, &nr_sec);
331 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700332 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
333 * encryption info footer and key, and plenty of bytes to spare for future
334 * growth.
335 */
336 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
337 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
338 cached_data = 1;
339 } else {
340 SLOGE("Cannot get size of block device %s\n", real_blkdev);
341 }
342 close(fd);
343 } else {
344 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
345 cached_off = 0;
346 cached_data = 1;
347 }
348 }
349
350 if (cached_data) {
351 if (metadata_fname) {
352 *metadata_fname = cached_metadata_fname;
353 }
354 if (off) {
355 *off = cached_off;
356 }
357 rc = 0;
358 }
359
360 return rc;
361}
362
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800363/* Set sha256 checksum in structure */
364static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
365{
366 SHA256_CTX c;
367 SHA256_Init(&c);
368 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
369 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
370 SHA256_Final(crypt_ftr->sha256, &c);
371}
372
Ken Sumralle8744072011-01-18 22:01:55 -0800373/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800374 * update the failed mount count but not change the key.
375 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700376static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800377{
378 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800379 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700380 /* starting_off is set to the SEEK_SET offset
381 * where the crypto structure starts
382 */
383 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800384 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700385 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700386 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800387
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800388 set_ftr_sha(crypt_ftr);
389
Ken Sumrall160b4d62013-04-22 12:15:39 -0700390 if (get_crypt_ftr_info(&fname, &starting_off)) {
391 SLOGE("Unable to get crypt_ftr_info\n");
392 return -1;
393 }
394 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700395 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700396 return -1;
397 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700398 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700399 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700400 return -1;
401 }
402
403 /* Seek to the start of the crypt footer */
404 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
405 SLOGE("Cannot seek to real block device footer\n");
406 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800407 }
408
409 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
410 SLOGE("Cannot write real block device footer\n");
411 goto errout;
412 }
413
Ken Sumrall3be890f2011-09-14 16:53:46 -0700414 fstat(fd, &statbuf);
415 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700416 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700417 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800418 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800419 goto errout;
420 }
421 }
422
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800423 /* Success! */
424 rc = 0;
425
426errout:
427 close(fd);
428 return rc;
429
430}
431
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800432static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
433{
434 struct crypt_mnt_ftr copy;
435 memcpy(&copy, crypt_ftr, sizeof(copy));
436 set_ftr_sha(&copy);
437 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
438}
439
Ken Sumrall160b4d62013-04-22 12:15:39 -0700440static inline int unix_read(int fd, void* buff, int len)
441{
442 return TEMP_FAILURE_RETRY(read(fd, buff, len));
443}
444
445static inline int unix_write(int fd, const void* buff, int len)
446{
447 return TEMP_FAILURE_RETRY(write(fd, buff, len));
448}
449
450static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
451{
452 memset(pdata, 0, len);
453 pdata->persist_magic = PERSIST_DATA_MAGIC;
454 pdata->persist_valid_entries = 0;
455}
456
457/* A routine to update the passed in crypt_ftr to the lastest version.
458 * fd is open read/write on the device that holds the crypto footer and persistent
459 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
460 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
461 */
462static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
463{
Kenny Root7434b312013-06-14 11:29:53 -0700464 int orig_major = crypt_ftr->major_version;
465 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700466
Kenny Root7434b312013-06-14 11:29:53 -0700467 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
468 struct crypt_persist_data *pdata;
469 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700470
Kenny Rootc4c70f12013-06-14 12:11:38 -0700471 SLOGW("upgrading crypto footer to 1.1");
472
Wei Wang4375f1b2017-02-24 17:43:01 -0800473 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700474 if (pdata == NULL) {
475 SLOGE("Cannot allocate persisent data\n");
476 return;
477 }
478 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
479
480 /* Need to initialize the persistent data area */
481 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
482 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100483 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700484 return;
485 }
486 /* Write all zeros to the first copy, making it invalid */
487 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
488
489 /* Write a valid but empty structure to the second copy */
490 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
491 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
492
493 /* Update the footer */
494 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
495 crypt_ftr->persist_data_offset[0] = pdata_offset;
496 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
497 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100498 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700499 }
500
Paul Lawrencef4faa572014-01-29 13:31:03 -0800501 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700502 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800503 /* But keep the old kdf_type.
504 * It will get updated later to KDF_SCRYPT after the password has been verified.
505 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700506 crypt_ftr->kdf_type = KDF_PBKDF2;
507 get_device_scrypt_params(crypt_ftr);
508 crypt_ftr->minor_version = 2;
509 }
510
Paul Lawrencef4faa572014-01-29 13:31:03 -0800511 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
512 SLOGW("upgrading crypto footer to 1.3");
513 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
514 crypt_ftr->minor_version = 3;
515 }
516
Kenny Root7434b312013-06-14 11:29:53 -0700517 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
518 if (lseek64(fd, offset, SEEK_SET) == -1) {
519 SLOGE("Cannot seek to crypt footer\n");
520 return;
521 }
522 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700523 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700524}
525
526
527static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800528{
529 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800530 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700531 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800532 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700534 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800535
Ken Sumrall160b4d62013-04-22 12:15:39 -0700536 if (get_crypt_ftr_info(&fname, &starting_off)) {
537 SLOGE("Unable to get crypt_ftr_info\n");
538 return -1;
539 }
540 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700541 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700542 return -1;
543 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700544 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700545 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700546 return -1;
547 }
548
549 /* Make sure it's 16 Kbytes in length */
550 fstat(fd, &statbuf);
551 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
552 SLOGE("footer file %s is not the expected size!\n", fname);
553 goto errout;
554 }
555
556 /* Seek to the start of the crypt footer */
557 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
558 SLOGE("Cannot seek to real block device footer\n");
559 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800560 }
561
562 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
563 SLOGE("Cannot read real block device footer\n");
564 goto errout;
565 }
566
567 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700568 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800569 goto errout;
570 }
571
Kenny Rootc96a5f82013-06-14 12:08:28 -0700572 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
573 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
574 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800575 goto errout;
576 }
577
Kenny Rootc96a5f82013-06-14 12:08:28 -0700578 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
579 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
580 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800581 }
582
Ken Sumrall160b4d62013-04-22 12:15:39 -0700583 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
584 * copy on disk before returning.
585 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700586 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700587 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800588 }
589
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800590 /* Success! */
591 rc = 0;
592
593errout:
594 close(fd);
595 return rc;
596}
597
Ken Sumrall160b4d62013-04-22 12:15:39 -0700598static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
599{
600 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
601 crypt_ftr->persist_data_offset[1]) {
602 SLOGE("Crypt_ftr persist data regions overlap");
603 return -1;
604 }
605
606 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
607 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
608 return -1;
609 }
610
611 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
612 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
613 CRYPT_FOOTER_OFFSET) {
614 SLOGE("Persistent data extends past crypto footer");
615 return -1;
616 }
617
618 return 0;
619}
620
621static int load_persistent_data(void)
622{
623 struct crypt_mnt_ftr crypt_ftr;
624 struct crypt_persist_data *pdata = NULL;
625 char encrypted_state[PROPERTY_VALUE_MAX];
626 char *fname;
627 int found = 0;
628 int fd;
629 int ret;
630 int i;
631
632 if (persist_data) {
633 /* Nothing to do, we've already loaded or initialized it */
634 return 0;
635 }
636
637
638 /* If not encrypted, just allocate an empty table and initialize it */
639 property_get("ro.crypto.state", encrypted_state, "");
640 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800641 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700642 if (pdata) {
643 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
644 persist_data = pdata;
645 return 0;
646 }
647 return -1;
648 }
649
650 if(get_crypt_ftr_and_key(&crypt_ftr)) {
651 return -1;
652 }
653
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700654 if ((crypt_ftr.major_version < 1)
655 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700656 SLOGE("Crypt_ftr version doesn't support persistent data");
657 return -1;
658 }
659
660 if (get_crypt_ftr_info(&fname, NULL)) {
661 return -1;
662 }
663
664 ret = validate_persistent_data_storage(&crypt_ftr);
665 if (ret) {
666 return -1;
667 }
668
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700669 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700670 if (fd < 0) {
671 SLOGE("Cannot open %s metadata file", fname);
672 return -1;
673 }
674
Wei Wang4375f1b2017-02-24 17:43:01 -0800675 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800676 if (pdata == NULL) {
677 SLOGE("Cannot allocate memory for persistent data");
678 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700679 }
680
681 for (i = 0; i < 2; i++) {
682 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
683 SLOGE("Cannot seek to read persistent data on %s", fname);
684 goto err2;
685 }
686 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
687 SLOGE("Error reading persistent data on iteration %d", i);
688 goto err2;
689 }
690 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
691 found = 1;
692 break;
693 }
694 }
695
696 if (!found) {
697 SLOGI("Could not find valid persistent data, creating");
698 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
699 }
700
701 /* Success */
702 persist_data = pdata;
703 close(fd);
704 return 0;
705
706err2:
707 free(pdata);
708
709err:
710 close(fd);
711 return -1;
712}
713
714static int save_persistent_data(void)
715{
716 struct crypt_mnt_ftr crypt_ftr;
717 struct crypt_persist_data *pdata;
718 char *fname;
719 off64_t write_offset;
720 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700721 int fd;
722 int ret;
723
724 if (persist_data == NULL) {
725 SLOGE("No persistent data to save");
726 return -1;
727 }
728
729 if(get_crypt_ftr_and_key(&crypt_ftr)) {
730 return -1;
731 }
732
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700733 if ((crypt_ftr.major_version < 1)
734 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700735 SLOGE("Crypt_ftr version doesn't support persistent data");
736 return -1;
737 }
738
739 ret = validate_persistent_data_storage(&crypt_ftr);
740 if (ret) {
741 return -1;
742 }
743
744 if (get_crypt_ftr_info(&fname, NULL)) {
745 return -1;
746 }
747
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700748 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700749 if (fd < 0) {
750 SLOGE("Cannot open %s metadata file", fname);
751 return -1;
752 }
753
Wei Wang4375f1b2017-02-24 17:43:01 -0800754 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700755 if (pdata == NULL) {
756 SLOGE("Cannot allocate persistant data");
757 goto err;
758 }
759
760 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
761 SLOGE("Cannot seek to read persistent data on %s", fname);
762 goto err2;
763 }
764
765 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
766 SLOGE("Error reading persistent data before save");
767 goto err2;
768 }
769
770 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
771 /* The first copy is the curent valid copy, so write to
772 * the second copy and erase this one */
773 write_offset = crypt_ftr.persist_data_offset[1];
774 erase_offset = crypt_ftr.persist_data_offset[0];
775 } else {
776 /* The second copy must be the valid copy, so write to
777 * the first copy, and erase the second */
778 write_offset = crypt_ftr.persist_data_offset[0];
779 erase_offset = crypt_ftr.persist_data_offset[1];
780 }
781
782 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100783 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700784 SLOGE("Cannot seek to write persistent data");
785 goto err2;
786 }
787 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
788 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100789 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700790 SLOGE("Cannot seek to erase previous persistent data");
791 goto err2;
792 }
793 fsync(fd);
794 memset(pdata, 0, crypt_ftr.persist_data_size);
795 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
796 (int) crypt_ftr.persist_data_size) {
797 SLOGE("Cannot write to erase previous persistent data");
798 goto err2;
799 }
800 fsync(fd);
801 } else {
802 SLOGE("Cannot write to save persistent data");
803 goto err2;
804 }
805
806 /* Success */
807 free(pdata);
808 close(fd);
809 return 0;
810
811err2:
812 free(pdata);
813err:
814 close(fd);
815 return -1;
816}
817
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800818/* Convert a binary key of specified length into an ascii hex string equivalent,
819 * without the leading 0x and with null termination
820 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700821static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700822 unsigned int keysize, char *master_key_ascii) {
823 unsigned int i, a;
824 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800825
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700826 for (i=0, a=0; i<keysize; i++, a+=2) {
827 /* For each byte, write out two ascii hex digits */
828 nibble = (master_key[i] >> 4) & 0xf;
829 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800830
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700831 nibble = master_key[i] & 0xf;
832 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
833 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800834
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700835 /* Add the null termination */
836 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800837
838}
839
Jeff Sharkey9c484982015-03-31 10:35:33 -0700840static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
841 const unsigned char *master_key, const char *real_blk_name,
842 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800843 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800844 struct dm_ioctl *io;
845 struct dm_target_spec *tgt;
846 char *crypt_params;
847 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800848 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800849 int i;
850
851 io = (struct dm_ioctl *) buffer;
852
853 /* Load the mapping table for this device */
854 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
855
856 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
857 io->target_count = 1;
858 tgt->status = 0;
859 tgt->sector_start = 0;
860 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700861 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800862
863 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
864 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800865
866 buff_offset = crypt_params - buffer;
867 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
868 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
869 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800870 crypt_params += strlen(crypt_params) + 1;
871 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
872 tgt->next = crypt_params - buffer;
873
874 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
875 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
876 break;
877 }
878 usleep(500000);
879 }
880
881 if (i == TABLE_LOAD_RETRIES) {
882 /* We failed to load the table, return an error */
883 return -1;
884 } else {
885 return i + 1;
886 }
887}
888
889
890static int get_dm_crypt_version(int fd, const char *name, int *version)
891{
892 char buffer[DM_CRYPT_BUF_SIZE];
893 struct dm_ioctl *io;
894 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800895
896 io = (struct dm_ioctl *) buffer;
897
898 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
899
900 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
901 return -1;
902 }
903
904 /* Iterate over the returned versions, looking for name of "crypt".
905 * When found, get and return the version.
906 */
907 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
908 while (v->next) {
909 if (! strcmp(v->name, "crypt")) {
910 /* We found the crypt driver, return the version, and get out */
911 version[0] = v->version[0];
912 version[1] = v->version[1];
913 version[2] = v->version[2];
914 return 0;
915 }
916 v = (struct dm_target_versions *)(((char *)v) + v->next);
917 }
918
919 return -1;
920}
921
Jeff Sharkey9c484982015-03-31 10:35:33 -0700922static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
923 const unsigned char *master_key, const char *real_blk_name,
924 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800925 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800926 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800927 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -0700928 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800929 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800930 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800931 int version[3];
Wei Wang4375f1b2017-02-24 17:43:01 -0800932 const char *extra_params;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800933 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800934
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700935 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800936 SLOGE("Cannot open device-mapper\n");
937 goto errout;
938 }
939
940 io = (struct dm_ioctl *) buffer;
941
942 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800943 err = ioctl(fd, DM_DEV_CREATE, io);
944 if (err) {
945 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800946 goto errout;
947 }
948
949 /* Get the device status, in particular, the name of it's device file */
950 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
951 if (ioctl(fd, DM_DEV_STATUS, io)) {
952 SLOGE("Cannot retrieve dm-crypt device status\n");
953 goto errout;
954 }
955 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
956 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
957
Ken Sumralldb5e0262013-02-05 17:39:48 -0800958 extra_params = "";
959 if (! get_dm_crypt_version(fd, name, version)) {
960 /* Support for allow_discards was added in version 1.11.0 */
961 if ((version[0] >= 2) ||
962 ((version[0] == 1) && (version[1] >= 11))) {
963 extra_params = "1 allow_discards";
964 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
965 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700966 }
967
Ken Sumralldb5e0262013-02-05 17:39:48 -0800968 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
969 fd, extra_params);
970 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800971 SLOGE("Cannot load dm-crypt mapping table.\n");
972 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800973 } else if (load_count > 1) {
974 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800975 }
976
977 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800978 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800979
980 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
981 SLOGE("Cannot resume the dm-crypt device\n");
982 goto errout;
983 }
984
985 /* We made it here with no errors. Woot! */
986 retval = 0;
987
988errout:
989 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
990
991 return retval;
992}
993
Wei Wang4375f1b2017-02-24 17:43:01 -0800994static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800995{
996 int fd;
997 char buffer[DM_CRYPT_BUF_SIZE];
998 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800999 int retval = -1;
1000
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001001 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001002 SLOGE("Cannot open device-mapper\n");
1003 goto errout;
1004 }
1005
1006 io = (struct dm_ioctl *) buffer;
1007
1008 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1009 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1010 SLOGE("Cannot remove dm-crypt device\n");
1011 goto errout;
1012 }
1013
1014 /* We made it here with no errors. Woot! */
1015 retval = 0;
1016
1017errout:
1018 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1019
1020 return retval;
1021
1022}
1023
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001024static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001025 unsigned char *ikey, void *params UNUSED)
1026{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001027 SLOGI("Using pbkdf2 for cryptfs KDF");
1028
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001029 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001030 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1031 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1032 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001033}
1034
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001035static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001036 unsigned char *ikey, void *params)
1037{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001038 SLOGI("Using scrypt for cryptfs KDF");
1039
Kenny Rootc4c70f12013-06-14 12:11:38 -07001040 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1041
1042 int N = 1 << ftr->N_factor;
1043 int r = 1 << ftr->r_factor;
1044 int p = 1 << ftr->p_factor;
1045
1046 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001047 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001048 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1049 salt, SALT_LEN, N, r, p, ikey,
1050 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001051
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001052 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001053}
1054
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001055static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1056 unsigned char *ikey, void *params)
1057{
1058 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1059
1060 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001061 size_t signature_size;
1062 unsigned char* signature;
1063 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1064
1065 int N = 1 << ftr->N_factor;
1066 int r = 1 << ftr->r_factor;
1067 int p = 1 << ftr->p_factor;
1068
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001069 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1070 salt, SALT_LEN, N, r, p, ikey,
1071 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001072
1073 if (rc) {
1074 SLOGE("scrypt failed");
1075 return -1;
1076 }
1077
Shawn Willdene17a9c42014-09-08 13:04:08 -06001078 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1079 &signature, &signature_size)) {
1080 SLOGE("Signing failed");
1081 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001082 }
1083
1084 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1085 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1086 free(signature);
1087
1088 if (rc) {
1089 SLOGE("scrypt failed");
1090 return -1;
1091 }
1092
1093 return 0;
1094}
1095
1096static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1097 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001098 unsigned char *encrypted_master_key,
1099 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001100{
1101 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1102 EVP_CIPHER_CTX e_ctx;
1103 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001104 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001105
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001106 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001107 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001108
1109 switch (crypt_ftr->kdf_type) {
1110 case KDF_SCRYPT_KEYMASTER:
1111 if (keymaster_create_key(crypt_ftr)) {
1112 SLOGE("keymaster_create_key failed");
1113 return -1;
1114 }
1115
1116 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1117 SLOGE("scrypt failed");
1118 return -1;
1119 }
1120 break;
1121
1122 case KDF_SCRYPT:
1123 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1124 SLOGE("scrypt failed");
1125 return -1;
1126 }
1127 break;
1128
1129 default:
1130 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001131 return -1;
1132 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001133
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001134 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001135 EVP_CIPHER_CTX_init(&e_ctx);
1136 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001137 SLOGE("EVP_EncryptInit failed\n");
1138 return -1;
1139 }
1140 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001141
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001142 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001143 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001144 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001145 SLOGE("EVP_EncryptUpdate failed\n");
1146 return -1;
1147 }
Adam Langley889c4f12014-09-03 14:23:13 -07001148 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149 SLOGE("EVP_EncryptFinal failed\n");
1150 return -1;
1151 }
1152
1153 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1154 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1155 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001157
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001158 /* Store the scrypt of the intermediate key, so we can validate if it's a
1159 password error or mount error when things go wrong.
1160 Note there's no need to check for errors, since if this is incorrect, we
1161 simply won't wipe userdata, which is the correct default behavior
1162 */
1163 int N = 1 << crypt_ftr->N_factor;
1164 int r = 1 << crypt_ftr->r_factor;
1165 int p = 1 << crypt_ftr->p_factor;
1166
1167 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1168 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1169 crypt_ftr->scrypted_intermediate_key,
1170 sizeof(crypt_ftr->scrypted_intermediate_key));
1171
1172 if (rc) {
1173 SLOGE("encrypt_master_key: crypto_scrypt failed");
1174 }
1175
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001176 EVP_CIPHER_CTX_cleanup(&e_ctx);
1177
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001178 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001179}
1180
Paul Lawrence731a7a22015-04-28 22:14:15 +00001181static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001182 unsigned char *encrypted_master_key,
1183 unsigned char *decrypted_master_key,
1184 kdf_func kdf, void *kdf_params,
1185 unsigned char** intermediate_key,
1186 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001187{
1188 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 -08001189 EVP_CIPHER_CTX d_ctx;
1190 int decrypted_len, final_len;
1191
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001192 /* Turn the password into an intermediate key and IV that can decrypt the
1193 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001194 if (kdf(passwd, salt, ikey, kdf_params)) {
1195 SLOGE("kdf failed");
1196 return -1;
1197 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001198
1199 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001200 EVP_CIPHER_CTX_init(&d_ctx);
1201 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001202 return -1;
1203 }
1204 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1205 /* Decrypt the master key */
1206 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1207 encrypted_master_key, KEY_LEN_BYTES)) {
1208 return -1;
1209 }
Adam Langley889c4f12014-09-03 14:23:13 -07001210 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001211 return -1;
1212 }
1213
1214 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1215 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001216 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001217
1218 /* Copy intermediate key if needed by params */
1219 if (intermediate_key && intermediate_key_size) {
1220 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001221 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001222 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1223 *intermediate_key_size = KEY_LEN_BYTES;
1224 }
1225 }
1226
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001227 EVP_CIPHER_CTX_cleanup(&d_ctx);
1228
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001229 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230}
1231
Kenny Rootc4c70f12013-06-14 12:11:38 -07001232static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001233{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001234 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001235 *kdf = scrypt_keymaster;
1236 *kdf_params = ftr;
1237 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001238 *kdf = scrypt;
1239 *kdf_params = ftr;
1240 } else {
1241 *kdf = pbkdf2;
1242 *kdf_params = NULL;
1243 }
1244}
1245
Paul Lawrence731a7a22015-04-28 22:14:15 +00001246static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001247 struct crypt_mnt_ftr *crypt_ftr,
1248 unsigned char** intermediate_key,
1249 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001250{
1251 kdf_func kdf;
1252 void *kdf_params;
1253 int ret;
1254
1255 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001256 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1257 decrypted_master_key, kdf, kdf_params,
1258 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001259 if (ret != 0) {
1260 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001261 }
1262
1263 return ret;
1264}
1265
Wei Wang4375f1b2017-02-24 17:43:01 -08001266static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001267 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001268 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001269 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001270
1271 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001272 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001273 read(fd, key_buf, sizeof(key_buf));
1274 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001275 close(fd);
1276
1277 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001278 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001279}
1280
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001281int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001282{
Greg Hackmann955653e2014-09-24 14:55:20 -07001283 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001284#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001285
1286 /* Now umount the tmpfs filesystem */
1287 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001288 if (umount(mountpoint) == 0) {
1289 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001290 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001291
1292 if (errno == EINVAL) {
1293 /* EINVAL is returned if the directory is not a mountpoint,
1294 * i.e. there is no filesystem mounted there. So just get out.
1295 */
1296 break;
1297 }
1298
1299 err = errno;
1300
1301 /* If allowed, be increasingly aggressive before the last two retries */
1302 if (kill) {
1303 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1304 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001305 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001306 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1307 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001308 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001309 }
1310 }
1311
1312 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001313 }
1314
1315 if (i < WAIT_UNMOUNT_COUNT) {
1316 SLOGD("unmounting %s succeeded\n", mountpoint);
1317 rc = 0;
1318 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001319 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001320 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001321 rc = -1;
1322 }
1323
1324 return rc;
1325}
1326
Wei Wang42e38102017-06-07 10:46:12 -07001327static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001328{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001329 // NOTE: post_fs_data results in init calling back around to vold, so all
1330 // callers to this method must be async
1331
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001332 /* Do the prep of the /data filesystem */
1333 property_set("vold.post_fs_data_done", "0");
1334 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001335 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001336
Ken Sumrallc5872692013-05-14 15:26:31 -07001337 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001338 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001339 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001340 std::chrono::seconds(15))) {
1341 /* We timed out to prep /data in time. Continue wait. */
1342 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001343 }
Wei Wang42e38102017-06-07 10:46:12 -07001344 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001345}
1346
Paul Lawrence74f29f12014-08-28 15:54:10 -07001347static void cryptfs_set_corrupt()
1348{
1349 // Mark the footer as bad
1350 struct crypt_mnt_ftr crypt_ftr;
1351 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1352 SLOGE("Failed to get crypto footer - panic");
1353 return;
1354 }
1355
1356 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1357 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1358 SLOGE("Failed to set crypto footer - panic");
1359 return;
1360 }
1361}
1362
1363static void cryptfs_trigger_restart_min_framework()
1364{
1365 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1366 SLOGE("Failed to mount tmpfs on data - panic");
1367 return;
1368 }
1369
1370 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1371 SLOGE("Failed to trigger post fs data - panic");
1372 return;
1373 }
1374
1375 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1376 SLOGE("Failed to trigger restart min framework - panic");
1377 return;
1378 }
1379}
1380
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001381/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001382static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001383{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001384 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001385 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001386 static int restart_successful = 0;
1387
1388 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001389 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001390 SLOGE("Encrypted filesystem not validated, aborting");
1391 return -1;
1392 }
1393
1394 if (restart_successful) {
1395 SLOGE("System already restarted with encrypted disk, aborting");
1396 return -1;
1397 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001398
Paul Lawrencef4faa572014-01-29 13:31:03 -08001399 if (restart_main) {
1400 /* Here is where we shut down the framework. The init scripts
1401 * start all services in one of three classes: core, main or late_start.
1402 * On boot, we start core and main. Now, we stop main, but not core,
1403 * as core includes vold and a few other really important things that
1404 * we need to keep running. Once main has stopped, we should be able
1405 * to umount the tmpfs /data, then mount the encrypted /data.
1406 * We then restart the class main, and also the class late_start.
1407 * At the moment, I've only put a few things in late_start that I know
1408 * are not needed to bring up the framework, and that also cause problems
1409 * with unmounting the tmpfs /data, but I hope to add add more services
1410 * to the late_start class as we optimize this to decrease the delay
1411 * till the user is asked for the password to the filesystem.
1412 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413
Paul Lawrencef4faa572014-01-29 13:31:03 -08001414 /* The init files are setup to stop the class main when vold.decrypt is
1415 * set to trigger_reset_main.
1416 */
1417 property_set("vold.decrypt", "trigger_reset_main");
1418 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001419
Paul Lawrencef4faa572014-01-29 13:31:03 -08001420 /* Ugh, shutting down the framework is not synchronous, so until it
1421 * can be fixed, this horrible hack will wait a moment for it all to
1422 * shut down before proceeding. Without it, some devices cannot
1423 * restart the graphics services.
1424 */
1425 sleep(2);
1426 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001427
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428 /* Now that the framework is shutdown, we should be able to umount()
1429 * the tmpfs filesystem, and mount the real one.
1430 */
1431
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001432 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1433 if (strlen(crypto_blkdev) == 0) {
1434 SLOGE("fs_crypto_blkdev not set\n");
1435 return -1;
1436 }
1437
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001438 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001439 /* If ro.crypto.readonly is set to 1, mount the decrypted
1440 * filesystem readonly. This is used when /data is mounted by
1441 * recovery mode.
1442 */
1443 char ro_prop[PROPERTY_VALUE_MAX];
1444 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001445 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001446 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001447 rec->flags |= MS_RDONLY;
1448 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001449
Ken Sumralle5032c42012-04-01 23:58:44 -07001450 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001451 int retries = RETRY_MOUNT_ATTEMPTS;
1452 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001453
1454 /*
1455 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1456 * partitions in the fsck domain.
1457 */
1458 if (setexeccon(secontextFsck())){
1459 SLOGE("Failed to setexeccon");
1460 return -1;
1461 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001462 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001463 crypto_blkdev, 0))
1464 != 0) {
1465 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1466 /* TODO: invoke something similar to
1467 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1468 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1469 SLOGI("Failed to mount %s because it is busy - waiting",
1470 crypto_blkdev);
1471 if (--retries) {
1472 sleep(RETRY_MOUNT_DELAY_SECONDS);
1473 } else {
1474 /* Let's hope that a reboot clears away whatever is keeping
1475 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001476 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001477 }
1478 } else {
1479 SLOGE("Failed to mount decrypted data");
1480 cryptfs_set_corrupt();
1481 cryptfs_trigger_restart_min_framework();
1482 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001483 if (setexeccon(NULL)) {
1484 SLOGE("Failed to setexeccon");
1485 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001486 return -1;
1487 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001488 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001489 if (setexeccon(NULL)) {
1490 SLOGE("Failed to setexeccon");
1491 return -1;
1492 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001493
Ken Sumralle5032c42012-04-01 23:58:44 -07001494 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001495 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001496 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001497
1498 /* startup service classes main and late_start */
1499 property_set("vold.decrypt", "trigger_restart_framework");
1500 SLOGD("Just triggered restart_framework\n");
1501
1502 /* Give it a few moments to get started */
1503 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001504 }
1505
Ken Sumrall0cc16632011-01-18 20:32:26 -08001506 if (rc == 0) {
1507 restart_successful = 1;
1508 }
1509
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001510 return rc;
1511}
1512
Paul Lawrencef4faa572014-01-29 13:31:03 -08001513int cryptfs_restart(void)
1514{
Paul Lawrence05335c32015-03-05 09:46:23 -08001515 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001516 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001517 SLOGE("cryptfs_restart not valid for file encryption:");
1518 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001519 }
1520
Paul Lawrencef4faa572014-01-29 13:31:03 -08001521 /* Call internal implementation forcing a restart of main service group */
1522 return cryptfs_restart_internal(1);
1523}
1524
Wei Wang4375f1b2017-02-24 17:43:01 -08001525static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001526{
1527 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001528 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001529 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001530
1531 property_get("ro.crypto.state", encrypted_state, "");
1532 if (strcmp(encrypted_state, "encrypted") ) {
1533 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001534 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001535 }
1536
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001537 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001538 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001539 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001540 }
1541
Ken Sumrall160b4d62013-04-22 12:15:39 -07001542 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001543 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001544
Ken Sumralle1a45852011-12-14 21:24:27 -08001545 /*
1546 * Only report this error if key_loc is a file and it exists.
1547 * If the device was never encrypted, and /data is not mountable for
1548 * some reason, returning 1 should prevent the UI from presenting the
1549 * a "enter password" screen, or worse, a "press button to wipe the
1550 * device" screen.
1551 */
1552 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1553 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001554 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001555 } else {
1556 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001557 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001558 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001559 }
1560
Paul Lawrence74f29f12014-08-28 15:54:10 -07001561 // Test for possible error flags
1562 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1563 SLOGE("Encryption process is partway completed\n");
1564 return CRYPTO_COMPLETE_PARTIAL;
1565 }
1566
1567 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1568 SLOGE("Encryption process was interrupted but cannot continue\n");
1569 return CRYPTO_COMPLETE_INCONSISTENT;
1570 }
1571
1572 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1573 SLOGE("Encryption is successful but data is corrupt\n");
1574 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001575 }
1576
1577 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001578 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001579}
1580
Paul Lawrencef4faa572014-01-29 13:31:03 -08001581static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001582 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001583{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001585 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001586 char crypto_blkdev[MAXPATHLEN];
1587 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001588 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001589 unsigned int orig_failed_decrypt_count;
1590 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001591 int use_keymaster = 0;
1592 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001593 unsigned char* intermediate_key = 0;
1594 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001595 int N = 1 << crypt_ftr->N_factor;
1596 int r = 1 << crypt_ftr->r_factor;
1597 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598
Paul Lawrencef4faa572014-01-29 13:31:03 -08001599 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1600 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001601
Paul Lawrencef4faa572014-01-29 13:31:03 -08001602 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001603 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1604 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001605 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001606 rc = -1;
1607 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001608 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001609 }
1610
Paul Crowleye2ee1522017-09-26 14:05:26 -07001611 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001612
Paul Lawrence74f29f12014-08-28 15:54:10 -07001613 // Create crypto block device - all (non fatal) code paths
1614 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001615 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1616 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001617 SLOGE("Error creating decrypted block device\n");
1618 rc = -1;
1619 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001620 }
1621
Paul Lawrence74f29f12014-08-28 15:54:10 -07001622 /* Work out if the problem is the password or the data */
1623 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1624 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001625
Paul Lawrence74f29f12014-08-28 15:54:10 -07001626 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1627 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1628 N, r, p, scrypted_intermediate_key,
1629 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001630
Paul Lawrence74f29f12014-08-28 15:54:10 -07001631 // Does the key match the crypto footer?
1632 if (rc == 0 && memcmp(scrypted_intermediate_key,
1633 crypt_ftr->scrypted_intermediate_key,
1634 sizeof(scrypted_intermediate_key)) == 0) {
1635 SLOGI("Password matches");
1636 rc = 0;
1637 } else {
1638 /* Try mounting the file system anyway, just in case the problem's with
1639 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001640 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1641 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001642 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001643 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001644 SLOGE("Error temp mounting decrypted block device\n");
1645 delete_crypto_blk_dev(label);
1646
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001647 rc = ++crypt_ftr->failed_decrypt_count;
1648 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001649 } else {
1650 /* Success! */
1651 SLOGI("Password did not match but decrypted drive mounted - continue");
1652 umount(tmp_mount_point);
1653 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001654 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001655 }
1656
1657 if (rc == 0) {
1658 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001659 if (orig_failed_decrypt_count != 0) {
1660 put_crypt_ftr_and_key(crypt_ftr);
1661 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001662
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001663 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001664 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001665 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001666
1667 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001668 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001669 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001670 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001671 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001672 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001673 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001674
Paul Lawrence74f29f12014-08-28 15:54:10 -07001675 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001676 use_keymaster = keymaster_check_compatibility();
1677 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001678 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001679 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1680 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1681 upgrade = 1;
1682 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001683 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001684 upgrade = 1;
1685 }
1686
1687 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001688 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1689 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001690 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001691 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001692 }
1693 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001694
1695 // Do not fail even if upgrade failed - machine is bootable
1696 // Note that if this code is ever hit, there is a *serious* problem
1697 // since KDFs should never fail. You *must* fix the kdf before
1698 // proceeding!
1699 if (rc) {
1700 SLOGW("Upgrade failed with error %d,"
1701 " but continuing with previous state",
1702 rc);
1703 rc = 0;
1704 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001705 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001706 }
1707
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001708 errout:
1709 if (intermediate_key) {
1710 memset(intermediate_key, 0, intermediate_key_size);
1711 free(intermediate_key);
1712 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713 return rc;
1714}
1715
Ken Sumrall29d8da82011-05-18 17:20:07 -07001716/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001717 * Called by vold when it's asked to mount an encrypted external
1718 * storage volume. The incoming partition has no crypto header/footer,
1719 * as any metadata is been stored in a separate, small partition.
1720 *
1721 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001722 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001723int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1724 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001725 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001726 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001727 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001728 return -1;
1729 }
1730
1731 unsigned long nr_sec = 0;
1732 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001733 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001734
Ken Sumrall29d8da82011-05-18 17:20:07 -07001735 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001736 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001737 return -1;
1738 }
1739
Jeff Sharkey9c484982015-03-31 10:35:33 -07001740 struct crypt_mnt_ftr ext_crypt_ftr;
1741 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1742 ext_crypt_ftr.fs_size = nr_sec;
1743 ext_crypt_ftr.keysize = keysize;
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001744 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
1745 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001746
Jeff Sharkey9c484982015-03-31 10:35:33 -07001747 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1748 out_crypto_blkdev, label);
1749}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001750
Jeff Sharkey9c484982015-03-31 10:35:33 -07001751/*
1752 * Called by vold when it's asked to unmount an encrypted external
1753 * storage volume.
1754 */
1755int cryptfs_revert_ext_volume(const char* label) {
1756 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001757}
1758
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001759int cryptfs_crypto_complete(void)
1760{
1761 return do_crypto_complete("/data");
1762}
1763
Paul Lawrencef4faa572014-01-29 13:31:03 -08001764int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1765{
1766 char encrypted_state[PROPERTY_VALUE_MAX];
1767 property_get("ro.crypto.state", encrypted_state, "");
1768 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1769 SLOGE("encrypted fs already validated or not running with encryption,"
1770 " aborting");
1771 return -1;
1772 }
1773
1774 if (get_crypt_ftr_and_key(crypt_ftr)) {
1775 SLOGE("Error getting crypt footer and key");
1776 return -1;
1777 }
1778
1779 return 0;
1780}
1781
Wei Wang4375f1b2017-02-24 17:43:01 -08001782int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001783{
Paul Lawrence05335c32015-03-05 09:46:23 -08001784 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001785 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001786 SLOGE("cryptfs_check_passwd not valid for file encryption");
1787 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001788 }
1789
Paul Lawrencef4faa572014-01-29 13:31:03 -08001790 struct crypt_mnt_ftr crypt_ftr;
1791 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001792
Paul Lawrencef4faa572014-01-29 13:31:03 -08001793 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001794 if (rc) {
1795 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001796 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001797 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001798
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001799 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001800 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1801 if (rc) {
1802 SLOGE("Password did not match");
1803 return rc;
1804 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001805
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001806 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1807 // Here we have a default actual password but a real password
1808 // we must test against the scrypted value
1809 // First, we must delete the crypto block device that
1810 // test_mount_encrypted_fs leaves behind as a side effect
1811 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1812 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1813 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1814 if (rc) {
1815 SLOGE("Default password did not match on reboot encryption");
1816 return rc;
1817 }
1818
1819 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1820 put_crypt_ftr_and_key(&crypt_ftr);
1821 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1822 if (rc) {
1823 SLOGE("Could not change password on reboot encryption");
1824 return rc;
1825 }
1826 }
1827
1828 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001829 cryptfs_clear_password();
1830 password = strdup(passwd);
1831 struct timespec now;
1832 clock_gettime(CLOCK_BOOTTIME, &now);
1833 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001834 }
1835
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001836 return rc;
1837}
1838
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001839int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001840{
1841 struct crypt_mnt_ftr crypt_ftr;
1842 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001843 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001844 char encrypted_state[PROPERTY_VALUE_MAX];
1845 int rc;
1846
1847 property_get("ro.crypto.state", encrypted_state, "");
1848 if (strcmp(encrypted_state, "encrypted") ) {
1849 SLOGE("device not encrypted, aborting");
1850 return -2;
1851 }
1852
1853 if (!master_key_saved) {
1854 SLOGE("encrypted fs not yet mounted, aborting");
1855 return -1;
1856 }
1857
1858 if (!saved_mount_point) {
1859 SLOGE("encrypted fs failed to save mount point, aborting");
1860 return -1;
1861 }
1862
Ken Sumrall160b4d62013-04-22 12:15:39 -07001863 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001864 SLOGE("Error getting crypt footer and key\n");
1865 return -1;
1866 }
1867
1868 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1869 /* If the device has no password, then just say the password is valid */
1870 rc = 0;
1871 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001872 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001873 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1874 /* They match, the password is correct */
1875 rc = 0;
1876 } else {
1877 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1878 sleep(1);
1879 rc = 1;
1880 }
1881 }
1882
1883 return rc;
1884}
1885
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001886/* Initialize a crypt_mnt_ftr structure. The keysize is
1887 * defaulted to 16 bytes, and the filesystem size to 0.
1888 * Presumably, at a minimum, the caller will update the
1889 * filesystem size and crypto_type_name after calling this function.
1890 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001891static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001892{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001893 off64_t off;
1894
1895 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001896 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001897 ftr->major_version = CURRENT_MAJOR_VERSION;
1898 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001899 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001900 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001901
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001902 switch (keymaster_check_compatibility()) {
1903 case 1:
1904 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1905 break;
1906
1907 case 0:
1908 ftr->kdf_type = KDF_SCRYPT;
1909 break;
1910
1911 default:
1912 SLOGE("keymaster_check_compatibility failed");
1913 return -1;
1914 }
1915
Kenny Rootc4c70f12013-06-14 12:11:38 -07001916 get_device_scrypt_params(ftr);
1917
Ken Sumrall160b4d62013-04-22 12:15:39 -07001918 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1919 if (get_crypt_ftr_info(NULL, &off) == 0) {
1920 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1921 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1922 ftr->persist_data_size;
1923 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001924
1925 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001926}
1927
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001928#define FRAMEWORK_BOOT_WAIT 60
1929
Paul Lawrence87999172014-02-20 12:21:31 -08001930static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1931{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001932 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001933 if (fd == -1) {
1934 SLOGE("Error opening file %s", filename);
1935 return -1;
1936 }
1937
1938 char block[CRYPT_INPLACE_BUFSIZE];
1939 memset(block, 0, sizeof(block));
1940 if (unix_read(fd, block, sizeof(block)) < 0) {
1941 SLOGE("Error reading file %s", filename);
1942 close(fd);
1943 return -1;
1944 }
1945
1946 close(fd);
1947
1948 SHA256_CTX c;
1949 SHA256_Init(&c);
1950 SHA256_Update(&c, block, sizeof(block));
1951 SHA256_Final(buf, &c);
1952
1953 return 0;
1954}
1955
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001956static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
1957 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08001958 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08001959 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001960
Paul Lawrence87999172014-02-20 12:21:31 -08001961 /* The size of the userdata partition, and add in the vold volumes below */
1962 tot_encryption_size = crypt_ftr->fs_size;
1963
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001964 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
1965 tot_encryption_size, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08001966
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001967 if (rc == ENABLE_INPLACE_ERR_DEV) {
1968 /* Hack for b/17898962 */
1969 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
1970 cryptfs_reboot(RebootType::reboot);
1971 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07001972
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001973 if (!rc) {
1974 crypt_ftr->encrypted_upto = cur_encryption_done;
1975 }
Paul Lawrence87999172014-02-20 12:21:31 -08001976
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001977 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
1978 /* The inplace routine never actually sets the progress to 100% due
1979 * to the round down nature of integer division, so set it here */
1980 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08001981 }
1982
1983 return rc;
1984}
1985
Paul Crowleyb64933a2017-10-31 08:25:55 -07001986static int vold_unmountAll(void) {
1987 VolumeManager* vm = VolumeManager::Instance();
1988 return vm->unmountAll();
1989}
1990
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001991int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08001992 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001993 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001994 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08001995 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001996 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001997 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001998 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001999 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002000 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002001 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002002 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002003 bool onlyCreateHeader = false;
2004 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002005
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002006 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002007 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2008 /* An encryption was underway and was interrupted */
2009 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2010 crypt_ftr.encrypted_upto = 0;
2011 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002012
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002013 /* At this point, we are in an inconsistent state. Until we successfully
2014 complete encryption, a reboot will leave us broken. So mark the
2015 encryption failed in case that happens.
2016 On successfully completing encryption, remove this flag */
2017 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002018
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002019 put_crypt_ftr_and_key(&crypt_ftr);
2020 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2021 if (!check_ftr_sha(&crypt_ftr)) {
2022 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2023 put_crypt_ftr_and_key(&crypt_ftr);
2024 goto error_unencrypted;
2025 }
2026
2027 /* Doing a reboot-encryption*/
2028 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2029 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2030 rebootEncryption = true;
2031 }
Paul Lawrence87999172014-02-20 12:21:31 -08002032 }
2033
2034 property_get("ro.crypto.state", encrypted_state, "");
2035 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2036 SLOGE("Device is already running encrypted, aborting");
2037 goto error_unencrypted;
2038 }
2039
2040 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002041 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2042 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002043
Ken Sumrall3ed82362011-01-28 23:31:16 -08002044 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002045 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002046 if (fd == -1) {
2047 SLOGE("Cannot open block device %s\n", real_blkdev);
2048 goto error_unencrypted;
2049 }
2050 unsigned long nr_sec;
2051 get_blkdev_size(fd, &nr_sec);
2052 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002053 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2054 goto error_unencrypted;
2055 }
2056 close(fd);
2057
2058 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002059 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002060 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002061 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002062 if (fs_size_sec == 0)
2063 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2064
Paul Lawrence87999172014-02-20 12:21:31 -08002065 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002066
2067 if (fs_size_sec > max_fs_size_sec) {
2068 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2069 goto error_unencrypted;
2070 }
2071 }
2072
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002073 /* Get a wakelock as this may take a while, and we don't want the
2074 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2075 * wants to keep the screen on, it can grab a full wakelock.
2076 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002077 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002078 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2079
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002080 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002081 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002082 */
2083 property_set("vold.decrypt", "trigger_shutdown_framework");
2084 SLOGD("Just asked init to shut down class main\n");
2085
Jeff Sharkey9c484982015-03-31 10:35:33 -07002086 /* Ask vold to unmount all devices that it manages */
2087 if (vold_unmountAll()) {
2088 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002089 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002090
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002091 /* no_ui means we are being called from init, not settings.
2092 Now we always reboot from settings, so !no_ui means reboot
2093 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002094 if (!no_ui) {
2095 /* Try fallback, which is to reboot and try there */
2096 onlyCreateHeader = true;
2097 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2098 if (breadcrumb == 0) {
2099 SLOGE("Failed to create breadcrumb file");
2100 goto error_shutting_down;
2101 }
2102 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002103 }
2104
2105 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002106 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002107 /* Now that /data is unmounted, we need to mount a tmpfs
2108 * /data, set a property saying we're doing inplace encryption,
2109 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002110 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002111 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002112 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002113 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002114 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002115 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002116
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002117 /* restart the framework. */
2118 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002119 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002120
Ken Sumrall92736ef2012-10-17 20:57:14 -07002121 /* Ugh, shutting down the framework is not synchronous, so until it
2122 * can be fixed, this horrible hack will wait a moment for it all to
2123 * shut down before proceeding. Without it, some devices cannot
2124 * restart the graphics services.
2125 */
2126 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002127 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002128
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002129 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002130 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002131 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002132 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2133 goto error_shutting_down;
2134 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002135
Paul Lawrence87999172014-02-20 12:21:31 -08002136 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2137 crypt_ftr.fs_size = nr_sec
2138 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2139 } else {
2140 crypt_ftr.fs_size = nr_sec;
2141 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002142 /* At this point, we are in an inconsistent state. Until we successfully
2143 complete encryption, a reboot will leave us broken. So mark the
2144 encryption failed in case that happens.
2145 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002146 if (onlyCreateHeader) {
2147 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2148 } else {
2149 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2150 }
Paul Lawrence87999172014-02-20 12:21:31 -08002151 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002152 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002153
Paul Lawrence87999172014-02-20 12:21:31 -08002154 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002155 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2156 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002157 SLOGE("Cannot create encrypted master key\n");
2158 goto error_shutting_down;
2159 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002160
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002161 /* Replace scrypted intermediate key if we are preparing for a reboot */
2162 if (onlyCreateHeader) {
2163 unsigned char fake_master_key[KEY_LEN_BYTES];
2164 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2165 memset(fake_master_key, 0, sizeof(fake_master_key));
2166 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2167 encrypted_fake_master_key, &crypt_ftr);
2168 }
2169
Paul Lawrence87999172014-02-20 12:21:31 -08002170 /* Write the key to the end of the partition */
2171 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002172
Paul Lawrence87999172014-02-20 12:21:31 -08002173 /* If any persistent data has been remembered, save it.
2174 * If none, create a valid empty table and save that.
2175 */
2176 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002177 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002178 if (pdata) {
2179 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2180 persist_data = pdata;
2181 }
2182 }
2183 if (persist_data) {
2184 save_persistent_data();
2185 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002186 }
2187
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002188 if (onlyCreateHeader) {
2189 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002190 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002191 }
2192
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002193 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002194 /* startup service classes main and late_start */
2195 property_set("vold.decrypt", "trigger_restart_min_framework");
2196 SLOGD("Just triggered restart_min_framework\n");
2197
2198 /* OK, the framework is restarted and will soon be showing a
2199 * progress bar. Time to setup an encrypted mapping, and
2200 * either write a new filesystem, or encrypt in place updating
2201 * the progress bar as we work.
2202 */
2203 }
2204
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002205 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002206 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002207 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002208
Paul Lawrence87999172014-02-20 12:21:31 -08002209 /* If we are continuing, check checksums match */
2210 rc = 0;
2211 if (previously_encrypted_upto) {
2212 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2213 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002214
Paul Lawrence87999172014-02-20 12:21:31 -08002215 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2216 sizeof(hash_first_block)) != 0) {
2217 SLOGE("Checksums do not match - trigger wipe");
2218 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002219 }
2220 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002221
Paul Lawrence87999172014-02-20 12:21:31 -08002222 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002223 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002224 previously_encrypted_upto);
2225 }
2226
2227 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002228 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002229 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2230 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002231 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002232 SLOGE("Error calculating checksum for continuing encryption");
2233 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002234 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002235 }
2236
2237 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002238 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002239
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002240 if (! rc) {
2241 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002242 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002243
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002244 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002245 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2246 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002247 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002248 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002249
Paul Lawrence6bfed202014-07-28 12:47:22 -07002250 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002251
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002252 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2253 char value[PROPERTY_VALUE_MAX];
2254 property_get("ro.crypto.state", value, "");
2255 if (!strcmp(value, "")) {
2256 /* default encryption - continue first boot sequence */
2257 property_set("ro.crypto.state", "encrypted");
2258 property_set("ro.crypto.type", "block");
2259 release_wake_lock(lockid);
2260 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2261 // Bring up cryptkeeper that will check the password and set it
2262 property_set("vold.decrypt", "trigger_shutdown_framework");
2263 sleep(2);
2264 property_set("vold.encrypt_progress", "");
2265 cryptfs_trigger_restart_min_framework();
2266 } else {
2267 cryptfs_check_passwd(DEFAULT_PASSWORD);
2268 cryptfs_restart_internal(1);
2269 }
2270 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002271 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002272 sleep(2); /* Give the UI a chance to show 100% progress */
2273 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002274 }
Paul Lawrence87999172014-02-20 12:21:31 -08002275 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002276 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002277 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002278 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002279 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002280 char value[PROPERTY_VALUE_MAX];
2281
Ken Sumrall319369a2012-06-27 16:30:18 -07002282 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002283 if (!strcmp(value, "1")) {
2284 /* wipe data if encryption failed */
2285 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002286 std::string err;
2287 const std::vector<std::string> options = {
2288 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2289 };
2290 if (!write_bootloader_message(options, &err)) {
2291 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002292 }
Josh Gaofec44372017-08-28 13:22:55 -07002293 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002294 } else {
2295 /* set property to trigger dialog */
2296 property_set("vold.encrypt_progress", "error_partially_encrypted");
2297 release_wake_lock(lockid);
2298 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002299 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002300 }
2301
Ken Sumrall3ed82362011-01-28 23:31:16 -08002302 /* hrm, the encrypt step claims success, but the reboot failed.
2303 * This should not happen.
2304 * Set the property and return. Hope the framework can deal with it.
2305 */
2306 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002307 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002308 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002309
2310error_unencrypted:
2311 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002312 if (lockid[0]) {
2313 release_wake_lock(lockid);
2314 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002315 return -1;
2316
2317error_shutting_down:
2318 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2319 * but the framework is stopped and not restarted to show the error, so it's up to
2320 * vold to restart the system.
2321 */
2322 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002323 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002324
2325 /* shouldn't get here */
2326 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002327 if (lockid[0]) {
2328 release_wake_lock(lockid);
2329 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002330 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002331}
2332
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002333int cryptfs_enable(int type, const char* passwd, int no_ui) {
2334 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002335}
2336
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002337int cryptfs_enable_default(int no_ui) {
2338 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002339}
2340
2341int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002342{
Paul Crowley38132a12016-02-09 09:50:32 +00002343 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002344 SLOGE("cryptfs_changepw not valid for file encryption");
2345 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002346 }
2347
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002348 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002349 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002350
2351 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002352 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002353 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002354 return -1;
2355 }
2356
Paul Lawrencef4faa572014-01-29 13:31:03 -08002357 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2358 SLOGE("Invalid crypt_type %d", crypt_type);
2359 return -1;
2360 }
2361
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002362 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002363 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002364 SLOGE("Error getting crypt footer and key");
2365 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002366 }
2367
Paul Lawrencef4faa572014-01-29 13:31:03 -08002368 crypt_ftr.crypt_type = crypt_type;
2369
JP Abgrall933216c2015-02-11 13:44:32 -08002370 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002371 : newpw,
2372 crypt_ftr.salt,
2373 saved_master_key,
2374 crypt_ftr.master_key,
2375 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002376 if (rc) {
2377 SLOGE("Encrypt master key failed: %d", rc);
2378 return -1;
2379 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002380 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002381 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002382
2383 return 0;
2384}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002385
Rubin Xu85c01f92014-10-13 12:49:54 +01002386static unsigned int persist_get_max_entries(int encrypted) {
2387 struct crypt_mnt_ftr crypt_ftr;
2388 unsigned int dsize;
2389 unsigned int max_persistent_entries;
2390
2391 /* If encrypted, use the values from the crypt_ftr, otherwise
2392 * use the values for the current spec.
2393 */
2394 if (encrypted) {
2395 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2396 return -1;
2397 }
2398 dsize = crypt_ftr.persist_data_size;
2399 } else {
2400 dsize = CRYPT_PERSIST_DATA_SIZE;
2401 }
2402
2403 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2404 sizeof(struct crypt_persist_entry);
2405
2406 return max_persistent_entries;
2407}
2408
2409static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002410{
2411 unsigned int i;
2412
2413 if (persist_data == NULL) {
2414 return -1;
2415 }
2416 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2417 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2418 /* We found it! */
2419 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2420 return 0;
2421 }
2422 }
2423
2424 return -1;
2425}
2426
Rubin Xu85c01f92014-10-13 12:49:54 +01002427static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002428{
2429 unsigned int i;
2430 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002431 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002432
2433 if (persist_data == NULL) {
2434 return -1;
2435 }
2436
Rubin Xu85c01f92014-10-13 12:49:54 +01002437 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002438
2439 num = persist_data->persist_valid_entries;
2440
2441 for (i = 0; i < num; i++) {
2442 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2443 /* We found an existing entry, update it! */
2444 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2445 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2446 return 0;
2447 }
2448 }
2449
2450 /* We didn't find it, add it to the end, if there is room */
2451 if (persist_data->persist_valid_entries < max_persistent_entries) {
2452 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2453 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2454 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2455 persist_data->persist_valid_entries++;
2456 return 0;
2457 }
2458
2459 return -1;
2460}
2461
Rubin Xu85c01f92014-10-13 12:49:54 +01002462/**
2463 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2464 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2465 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002466int match_multi_entry(const char *key, const char *field, unsigned index) {
2467 std::string key_ = key;
2468 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002469
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002470 std::string parsed_field;
2471 unsigned parsed_index;
2472
2473 std::string::size_type split = key_.find_last_of('_');
2474 if (split == std::string::npos) {
2475 parsed_field = key_;
2476 parsed_index = 0;
2477 } else {
2478 parsed_field = key_.substr(0, split);
2479 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002480 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002481
2482 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002483}
2484
2485/*
2486 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2487 * remaining entries starting from index will be deleted.
2488 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2489 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2490 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2491 *
2492 */
2493static int persist_del_keys(const char *fieldname, unsigned index)
2494{
2495 unsigned int i;
2496 unsigned int j;
2497 unsigned int num;
2498
2499 if (persist_data == NULL) {
2500 return PERSIST_DEL_KEY_ERROR_OTHER;
2501 }
2502
2503 num = persist_data->persist_valid_entries;
2504
2505 j = 0; // points to the end of non-deleted entries.
2506 // Filter out to-be-deleted entries in place.
2507 for (i = 0; i < num; i++) {
2508 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2509 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2510 j++;
2511 }
2512 }
2513
2514 if (j < num) {
2515 persist_data->persist_valid_entries = j;
2516 // Zeroise the remaining entries
2517 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2518 return PERSIST_DEL_KEY_OK;
2519 } else {
2520 // Did not find an entry matching the given fieldname
2521 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2522 }
2523}
2524
2525static int persist_count_keys(const char *fieldname)
2526{
2527 unsigned int i;
2528 unsigned int count;
2529
2530 if (persist_data == NULL) {
2531 return -1;
2532 }
2533
2534 count = 0;
2535 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2536 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2537 count++;
2538 }
2539 }
2540
2541 return count;
2542}
2543
Ken Sumrall160b4d62013-04-22 12:15:39 -07002544/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002545int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002546{
Paul Crowley38132a12016-02-09 09:50:32 +00002547 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002548 SLOGE("Cannot get field when file encrypted");
2549 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002550 }
2551
Ken Sumrall160b4d62013-04-22 12:15:39 -07002552 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002553 /* CRYPTO_GETFIELD_OK is success,
2554 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2555 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2556 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002557 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002558 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2559 int i;
2560 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002561
2562 if (persist_data == NULL) {
2563 load_persistent_data();
2564 if (persist_data == NULL) {
2565 SLOGE("Getfield error, cannot load persistent data");
2566 goto out;
2567 }
2568 }
2569
Rubin Xu85c01f92014-10-13 12:49:54 +01002570 // Read value from persistent entries. If the original value is split into multiple entries,
2571 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002572 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002573 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2574 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2575 // value too small
2576 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2577 goto out;
2578 }
2579 rc = CRYPTO_GETFIELD_OK;
2580
2581 for (i = 1; /* break explicitly */; i++) {
2582 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2583 (int) sizeof(temp_field)) {
2584 // If the fieldname is very long, we stop as soon as it begins to overflow the
2585 // maximum field length. At this point we have in fact fully read out the original
2586 // value because cryptfs_setfield would not allow fields with longer names to be
2587 // written in the first place.
2588 break;
2589 }
2590 if (!persist_get_key(temp_field, temp_value)) {
2591 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2592 // value too small.
2593 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2594 goto out;
2595 }
2596 } else {
2597 // Exhaust all entries.
2598 break;
2599 }
2600 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002601 } else {
2602 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002603 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002604 }
2605
2606out:
2607 return rc;
2608}
2609
2610/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002611int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002612{
Paul Crowley38132a12016-02-09 09:50:32 +00002613 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002614 SLOGE("Cannot set field when file encrypted");
2615 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002616 }
2617
Ken Sumrall160b4d62013-04-22 12:15:39 -07002618 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002619 /* 0 is success, negative values are error */
2620 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002621 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002622 unsigned int field_id;
2623 char temp_field[PROPERTY_KEY_MAX];
2624 unsigned int num_entries;
2625 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002626
2627 if (persist_data == NULL) {
2628 load_persistent_data();
2629 if (persist_data == NULL) {
2630 SLOGE("Setfield error, cannot load persistent data");
2631 goto out;
2632 }
2633 }
2634
2635 property_get("ro.crypto.state", encrypted_state, "");
2636 if (!strcmp(encrypted_state, "encrypted") ) {
2637 encrypted = 1;
2638 }
2639
Rubin Xu85c01f92014-10-13 12:49:54 +01002640 // Compute the number of entries required to store value, each entry can store up to
2641 // (PROPERTY_VALUE_MAX - 1) chars
2642 if (strlen(value) == 0) {
2643 // Empty value also needs one entry to store.
2644 num_entries = 1;
2645 } else {
2646 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2647 }
2648
2649 max_keylen = strlen(fieldname);
2650 if (num_entries > 1) {
2651 // Need an extra "_%d" suffix.
2652 max_keylen += 1 + log10(num_entries);
2653 }
2654 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2655 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002656 goto out;
2657 }
2658
Rubin Xu85c01f92014-10-13 12:49:54 +01002659 // Make sure we have enough space to write the new value
2660 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2661 persist_get_max_entries(encrypted)) {
2662 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2663 goto out;
2664 }
2665
2666 // Now that we know persist_data has enough space for value, let's delete the old field first
2667 // to make up space.
2668 persist_del_keys(fieldname, 0);
2669
2670 if (persist_set_key(fieldname, value, encrypted)) {
2671 // fail to set key, should not happen as we have already checked the available space
2672 SLOGE("persist_set_key() error during setfield()");
2673 goto out;
2674 }
2675
2676 for (field_id = 1; field_id < num_entries; field_id++) {
2677 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
2678
2679 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2680 // fail to set key, should not happen as we have already checked the available space.
2681 SLOGE("persist_set_key() error during setfield()");
2682 goto out;
2683 }
2684 }
2685
Ken Sumrall160b4d62013-04-22 12:15:39 -07002686 /* If we are running encrypted, save the persistent data now */
2687 if (encrypted) {
2688 if (save_persistent_data()) {
2689 SLOGE("Setfield error, cannot save persistent data");
2690 goto out;
2691 }
2692 }
2693
Rubin Xu85c01f92014-10-13 12:49:54 +01002694 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002695
2696out:
2697 return rc;
2698}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002699
2700/* Checks userdata. Attempt to mount the volume if default-
2701 * encrypted.
2702 * On success trigger next init phase and return 0.
2703 * Currently do not handle failure - see TODO below.
2704 */
2705int cryptfs_mount_default_encrypted(void)
2706{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002707 int crypt_type = cryptfs_get_password_type();
2708 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2709 SLOGE("Bad crypt type - error");
2710 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2711 SLOGD("Password is not default - "
2712 "starting min framework to prompt");
2713 property_set("vold.decrypt", "trigger_restart_min_framework");
2714 return 0;
2715 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2716 SLOGD("Password is default - restarting filesystem");
2717 cryptfs_restart_internal(0);
2718 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002719 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002720 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002721 }
2722
Paul Lawrence6bfed202014-07-28 12:47:22 -07002723 /** Corrupt. Allow us to boot into framework, which will detect bad
2724 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002725 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002726 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002727 return 0;
2728}
2729
2730/* Returns type of the password, default, pattern, pin or password.
2731 */
2732int cryptfs_get_password_type(void)
2733{
Paul Crowley38132a12016-02-09 09:50:32 +00002734 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002735 SLOGE("cryptfs_get_password_type not valid for file encryption");
2736 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002737 }
2738
Paul Lawrencef4faa572014-01-29 13:31:03 -08002739 struct crypt_mnt_ftr crypt_ftr;
2740
2741 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2742 SLOGE("Error getting crypt footer and key\n");
2743 return -1;
2744 }
2745
Paul Lawrence6bfed202014-07-28 12:47:22 -07002746 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2747 return -1;
2748 }
2749
Paul Lawrencef4faa572014-01-29 13:31:03 -08002750 return crypt_ftr.crypt_type;
2751}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002752
Paul Lawrence05335c32015-03-05 09:46:23 -08002753const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002754{
Paul Crowley38132a12016-02-09 09:50:32 +00002755 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002756 SLOGE("cryptfs_get_password not valid for file encryption");
2757 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002758 }
2759
Paul Lawrence399317e2014-03-10 13:20:50 -07002760 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002761 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002762 if (now.tv_sec < password_expiry_time) {
2763 return password;
2764 } else {
2765 cryptfs_clear_password();
2766 return 0;
2767 }
2768}
2769
2770void cryptfs_clear_password()
2771{
2772 if (password) {
2773 size_t len = strlen(password);
2774 memset(password, 0, len);
2775 free(password);
2776 password = 0;
2777 password_expiry_time = 0;
2778 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002779}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002780
Paul Lawrence0c247462015-10-29 10:30:57 -07002781int cryptfs_isConvertibleToFBE()
2782{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002783 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002784 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2785}