blob: af7fda3b92d22f84c0bee2094102a0aa94f04f2b [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 Sumrall29d8da82011-05-18 17:20:07 -07001928static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001929{
Ken Sumralle550f782013-08-20 13:48:23 -07001930 const char *args[10];
1931 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1932 int num_args;
1933 int status;
1934 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001935 int rc = -1;
1936
Ken Sumrall29d8da82011-05-18 17:20:07 -07001937 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001938 args[0] = "/system/bin/mke2fs";
1939 args[1] = "-M";
1940 args[2] = "/data";
1941 args[3] = "-b";
1942 args[4] = "4096";
1943 args[5] = "-t";
1944 args[6] = "ext4";
1945 args[7] = crypto_blkdev;
1946 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1947 args[8] = size_str;
1948 num_args = 9;
Ken Sumralle550f782013-08-20 13:48:23 -07001949 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1950 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001951 } else if (type == F2FS_FS) {
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001952 args[0] = "/system/bin/make_f2fs";
Jaegeuk Kim8de9f062017-11-01 10:35:30 -07001953 args[1] = "-f";
JP Abgrall62c7af32014-06-16 13:01:23 -07001954 args[2] = "-d1";
Jaegeuk Kim8de9f062017-11-01 10:35:30 -07001955 args[3] = "-O";
1956 args[4] = "encrypt";
1957 args[5] = "-O";
1958 args[6] = "quota";
1959 args[7] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001960 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
Jaegeuk Kim8de9f062017-11-01 10:35:30 -07001961 args[8] = size_str;
1962 num_args = 9;
1963 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s\n",
1964 args[0], args[1], args[2], args[3], args[4], args[5],
1965 args[6], args[7], args[8]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001966 } else {
1967 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1968 return -1;
1969 }
1970
Ken Sumralle550f782013-08-20 13:48:23 -07001971 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1972
1973 if (tmp != 0) {
1974 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001975 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001976 if (WIFEXITED(status)) {
1977 if (WEXITSTATUS(status)) {
1978 SLOGE("Error creating filesystem on %s, exit status %d ",
1979 crypto_blkdev, WEXITSTATUS(status));
1980 } else {
1981 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1982 rc = 0;
1983 }
1984 } else {
1985 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1986 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001987 }
1988
1989 return rc;
1990}
1991
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001992#define CRYPTO_ENABLE_WIPE 1
1993#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001994
1995#define FRAMEWORK_BOOT_WAIT 60
1996
Paul Lawrence87999172014-02-20 12:21:31 -08001997static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1998{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001999 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002000 if (fd == -1) {
2001 SLOGE("Error opening file %s", filename);
2002 return -1;
2003 }
2004
2005 char block[CRYPT_INPLACE_BUFSIZE];
2006 memset(block, 0, sizeof(block));
2007 if (unix_read(fd, block, sizeof(block)) < 0) {
2008 SLOGE("Error reading file %s", filename);
2009 close(fd);
2010 return -1;
2011 }
2012
2013 close(fd);
2014
2015 SHA256_CTX c;
2016 SHA256_Init(&c);
2017 SHA256_Update(&c, block, sizeof(block));
2018 SHA256_Final(buf, &c);
2019
2020 return 0;
2021}
2022
JP Abgrall62c7af32014-06-16 13:01:23 -07002023static int get_fs_type(struct fstab_rec *rec)
2024{
2025 if (!strcmp(rec->fs_type, "ext4")) {
2026 return EXT4_FS;
2027 } else if (!strcmp(rec->fs_type, "f2fs")) {
2028 return F2FS_FS;
2029 } else {
2030 return -1;
2031 }
2032}
2033
Paul Lawrence87999172014-02-20 12:21:31 -08002034static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2035 char *crypto_blkdev, char *real_blkdev,
2036 int previously_encrypted_upto)
2037{
2038 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002039 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002040
Paul Lawrence87999172014-02-20 12:21:31 -08002041 /* The size of the userdata partition, and add in the vold volumes below */
2042 tot_encryption_size = crypt_ftr->fs_size;
2043
2044 if (how == CRYPTO_ENABLE_WIPE) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002045 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
JP Abgrall62c7af32014-06-16 13:01:23 -07002046 int fs_type = get_fs_type(rec);
2047 if (fs_type < 0) {
2048 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2049 return -1;
2050 }
2051 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002052 } else if (how == CRYPTO_ENABLE_INPLACE) {
2053 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2054 crypt_ftr->fs_size, &cur_encryption_done,
2055 tot_encryption_size,
2056 previously_encrypted_upto);
2057
JP Abgrall7fc1de82014-10-10 18:43:41 -07002058 if (rc == ENABLE_INPLACE_ERR_DEV) {
2059 /* Hack for b/17898962 */
2060 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
Josh Gaofec44372017-08-28 13:22:55 -07002061 cryptfs_reboot(RebootType::reboot);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002062 }
2063
Paul Lawrence73d7a022014-06-09 14:10:09 -07002064 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002065 crypt_ftr->encrypted_upto = cur_encryption_done;
2066 }
2067
Paul Lawrence73d7a022014-06-09 14:10:09 -07002068 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002069 /* The inplace routine never actually sets the progress to 100% due
2070 * to the round down nature of integer division, so set it here */
2071 property_set("vold.encrypt_progress", "100");
2072 }
2073 } else {
2074 /* Shouldn't happen */
2075 SLOGE("cryptfs_enable: internal error, unknown option\n");
2076 rc = -1;
2077 }
2078
2079 return rc;
2080}
2081
Paul Crowleyb64933a2017-10-31 08:25:55 -07002082static int vold_unmountAll(void) {
2083 VolumeManager* vm = VolumeManager::Instance();
2084 return vm->unmountAll();
2085}
2086
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002087int cryptfs_enable_internal(const char *howarg, int crypt_type, const char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002088 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002089{
2090 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002091 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002092 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002093 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002094 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002095 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002096 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002097 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002098 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002099 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002100 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002101 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002102 bool onlyCreateHeader = false;
2103 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002104
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002105 if (!strcmp(howarg, "wipe")) {
2106 how = CRYPTO_ENABLE_WIPE;
2107 } else if (! strcmp(howarg, "inplace")) {
2108 how = CRYPTO_ENABLE_INPLACE;
2109 } else {
2110 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002111 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002112 }
2113
Paul Lawrence87999172014-02-20 12:21:31 -08002114 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002115 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2116 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2117 /* An encryption was underway and was interrupted */
2118 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2119 crypt_ftr.encrypted_upto = 0;
2120 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002121
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002122 /* At this point, we are in an inconsistent state. Until we successfully
2123 complete encryption, a reboot will leave us broken. So mark the
2124 encryption failed in case that happens.
2125 On successfully completing encryption, remove this flag */
2126 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002127
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002128 put_crypt_ftr_and_key(&crypt_ftr);
2129 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2130 if (!check_ftr_sha(&crypt_ftr)) {
2131 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2132 put_crypt_ftr_and_key(&crypt_ftr);
2133 goto error_unencrypted;
2134 }
2135
2136 /* Doing a reboot-encryption*/
2137 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2138 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2139 rebootEncryption = true;
2140 }
Paul Lawrence87999172014-02-20 12:21:31 -08002141 }
2142
2143 property_get("ro.crypto.state", encrypted_state, "");
2144 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2145 SLOGE("Device is already running encrypted, aborting");
2146 goto error_unencrypted;
2147 }
2148
2149 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002150 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2151 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002152
Ken Sumrall3ed82362011-01-28 23:31:16 -08002153 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002154 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002155 if (fd == -1) {
2156 SLOGE("Cannot open block device %s\n", real_blkdev);
2157 goto error_unencrypted;
2158 }
2159 unsigned long nr_sec;
2160 get_blkdev_size(fd, &nr_sec);
2161 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002162 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2163 goto error_unencrypted;
2164 }
2165 close(fd);
2166
2167 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002168 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002169 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002170 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002171 if (fs_size_sec == 0)
2172 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2173
Paul Lawrence87999172014-02-20 12:21:31 -08002174 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002175
2176 if (fs_size_sec > max_fs_size_sec) {
2177 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2178 goto error_unencrypted;
2179 }
2180 }
2181
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002182 /* Get a wakelock as this may take a while, and we don't want the
2183 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2184 * wants to keep the screen on, it can grab a full wakelock.
2185 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002186 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002187 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2188
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002189 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002190 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002191 */
2192 property_set("vold.decrypt", "trigger_shutdown_framework");
2193 SLOGD("Just asked init to shut down class main\n");
2194
Jeff Sharkey9c484982015-03-31 10:35:33 -07002195 /* Ask vold to unmount all devices that it manages */
2196 if (vold_unmountAll()) {
2197 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002198 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002199
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002200 /* no_ui means we are being called from init, not settings.
2201 Now we always reboot from settings, so !no_ui means reboot
2202 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002203 if (!no_ui) {
2204 /* Try fallback, which is to reboot and try there */
2205 onlyCreateHeader = true;
2206 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2207 if (breadcrumb == 0) {
2208 SLOGE("Failed to create breadcrumb file");
2209 goto error_shutting_down;
2210 }
2211 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002212 }
2213
2214 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002215 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002216 /* Now that /data is unmounted, we need to mount a tmpfs
2217 * /data, set a property saying we're doing inplace encryption,
2218 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002219 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002220 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002221 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002222 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002223 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002224 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002225
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002226 /* restart the framework. */
2227 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002228 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002229
Ken Sumrall92736ef2012-10-17 20:57:14 -07002230 /* Ugh, shutting down the framework is not synchronous, so until it
2231 * can be fixed, this horrible hack will wait a moment for it all to
2232 * shut down before proceeding. Without it, some devices cannot
2233 * restart the graphics services.
2234 */
2235 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002236 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002237
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002238 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002239 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002240 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002241 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2242 goto error_shutting_down;
2243 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002244
Paul Lawrence87999172014-02-20 12:21:31 -08002245 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2246 crypt_ftr.fs_size = nr_sec
2247 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2248 } else {
2249 crypt_ftr.fs_size = nr_sec;
2250 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002251 /* At this point, we are in an inconsistent state. Until we successfully
2252 complete encryption, a reboot will leave us broken. So mark the
2253 encryption failed in case that happens.
2254 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002255 if (onlyCreateHeader) {
2256 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2257 } else {
2258 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2259 }
Paul Lawrence87999172014-02-20 12:21:31 -08002260 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002261 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002262
Paul Lawrence87999172014-02-20 12:21:31 -08002263 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002264 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2265 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002266 SLOGE("Cannot create encrypted master key\n");
2267 goto error_shutting_down;
2268 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002269
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002270 /* Replace scrypted intermediate key if we are preparing for a reboot */
2271 if (onlyCreateHeader) {
2272 unsigned char fake_master_key[KEY_LEN_BYTES];
2273 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2274 memset(fake_master_key, 0, sizeof(fake_master_key));
2275 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2276 encrypted_fake_master_key, &crypt_ftr);
2277 }
2278
Paul Lawrence87999172014-02-20 12:21:31 -08002279 /* Write the key to the end of the partition */
2280 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002281
Paul Lawrence87999172014-02-20 12:21:31 -08002282 /* If any persistent data has been remembered, save it.
2283 * If none, create a valid empty table and save that.
2284 */
2285 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002286 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002287 if (pdata) {
2288 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2289 persist_data = pdata;
2290 }
2291 }
2292 if (persist_data) {
2293 save_persistent_data();
2294 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002295 }
2296
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002297 if (onlyCreateHeader) {
2298 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002299 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002300 }
2301
2302 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002303 /* startup service classes main and late_start */
2304 property_set("vold.decrypt", "trigger_restart_min_framework");
2305 SLOGD("Just triggered restart_min_framework\n");
2306
2307 /* OK, the framework is restarted and will soon be showing a
2308 * progress bar. Time to setup an encrypted mapping, and
2309 * either write a new filesystem, or encrypt in place updating
2310 * the progress bar as we work.
2311 */
2312 }
2313
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002314 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002315 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002316 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002317
Paul Lawrence87999172014-02-20 12:21:31 -08002318 /* If we are continuing, check checksums match */
2319 rc = 0;
2320 if (previously_encrypted_upto) {
2321 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2322 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002323
Paul Lawrence87999172014-02-20 12:21:31 -08002324 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2325 sizeof(hash_first_block)) != 0) {
2326 SLOGE("Checksums do not match - trigger wipe");
2327 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002328 }
2329 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002330
Paul Lawrence87999172014-02-20 12:21:31 -08002331 if (!rc) {
2332 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2333 crypto_blkdev, real_blkdev,
2334 previously_encrypted_upto);
2335 }
2336
2337 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002338 if (!rc && how == CRYPTO_ENABLE_INPLACE
2339 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002340 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2341 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002342 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002343 SLOGE("Error calculating checksum for continuing encryption");
2344 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002345 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002346 }
2347
2348 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002349 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002350
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002351 if (! rc) {
2352 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002353 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002354
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002355 if (how == CRYPTO_ENABLE_INPLACE
2356 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002357 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2358 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002359 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002360 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002361
Paul Lawrence6bfed202014-07-28 12:47:22 -07002362 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002363
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002364 if (how == CRYPTO_ENABLE_WIPE
2365 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002366 char value[PROPERTY_VALUE_MAX];
2367 property_get("ro.crypto.state", value, "");
2368 if (!strcmp(value, "")) {
2369 /* default encryption - continue first boot sequence */
2370 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08002371 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002372 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002373 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2374 // Bring up cryptkeeper that will check the password and set it
2375 property_set("vold.decrypt", "trigger_shutdown_framework");
2376 sleep(2);
2377 property_set("vold.encrypt_progress", "");
2378 cryptfs_trigger_restart_min_framework();
2379 } else {
2380 cryptfs_check_passwd(DEFAULT_PASSWORD);
2381 cryptfs_restart_internal(1);
2382 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002383 return 0;
2384 } else {
2385 sleep(2); /* Give the UI a chance to show 100% progress */
Josh Gaofec44372017-08-28 13:22:55 -07002386 cryptfs_reboot(RebootType::reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002387 }
Paul Lawrence87999172014-02-20 12:21:31 -08002388 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002389 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002390 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002391 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002392 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002393 char value[PROPERTY_VALUE_MAX];
2394
Ken Sumrall319369a2012-06-27 16:30:18 -07002395 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002396 if (!strcmp(value, "1")) {
2397 /* wipe data if encryption failed */
2398 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002399 std::string err;
2400 const std::vector<std::string> options = {
2401 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2402 };
2403 if (!write_bootloader_message(options, &err)) {
2404 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002405 }
Josh Gaofec44372017-08-28 13:22:55 -07002406 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002407 } else {
2408 /* set property to trigger dialog */
2409 property_set("vold.encrypt_progress", "error_partially_encrypted");
2410 release_wake_lock(lockid);
2411 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002412 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002413 }
2414
Ken Sumrall3ed82362011-01-28 23:31:16 -08002415 /* hrm, the encrypt step claims success, but the reboot failed.
2416 * This should not happen.
2417 * Set the property and return. Hope the framework can deal with it.
2418 */
2419 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002420 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002421 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002422
2423error_unencrypted:
2424 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002425 if (lockid[0]) {
2426 release_wake_lock(lockid);
2427 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002428 return -1;
2429
2430error_shutting_down:
2431 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2432 * but the framework is stopped and not restarted to show the error, so it's up to
2433 * vold to restart the system.
2434 */
2435 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002436 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002437
2438 /* shouldn't get here */
2439 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002440 if (lockid[0]) {
2441 release_wake_lock(lockid);
2442 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002443 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002444}
2445
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002446int cryptfs_enable(const char *howarg, int type, const char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002447{
Paul Lawrence569649f2015-09-09 12:13:00 -07002448 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002449}
2450
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002451int cryptfs_enable_default(const char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002452{
2453 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07002454 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002455}
2456
2457int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002458{
Paul Crowley38132a12016-02-09 09:50:32 +00002459 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002460 SLOGE("cryptfs_changepw not valid for file encryption");
2461 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002462 }
2463
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002464 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002465 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002466
2467 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002468 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002469 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002470 return -1;
2471 }
2472
Paul Lawrencef4faa572014-01-29 13:31:03 -08002473 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2474 SLOGE("Invalid crypt_type %d", crypt_type);
2475 return -1;
2476 }
2477
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002478 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002479 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002480 SLOGE("Error getting crypt footer and key");
2481 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002482 }
2483
Paul Lawrencef4faa572014-01-29 13:31:03 -08002484 crypt_ftr.crypt_type = crypt_type;
2485
JP Abgrall933216c2015-02-11 13:44:32 -08002486 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002487 : newpw,
2488 crypt_ftr.salt,
2489 saved_master_key,
2490 crypt_ftr.master_key,
2491 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002492 if (rc) {
2493 SLOGE("Encrypt master key failed: %d", rc);
2494 return -1;
2495 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002496 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002497 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002498
2499 return 0;
2500}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002501
Rubin Xu85c01f92014-10-13 12:49:54 +01002502static unsigned int persist_get_max_entries(int encrypted) {
2503 struct crypt_mnt_ftr crypt_ftr;
2504 unsigned int dsize;
2505 unsigned int max_persistent_entries;
2506
2507 /* If encrypted, use the values from the crypt_ftr, otherwise
2508 * use the values for the current spec.
2509 */
2510 if (encrypted) {
2511 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2512 return -1;
2513 }
2514 dsize = crypt_ftr.persist_data_size;
2515 } else {
2516 dsize = CRYPT_PERSIST_DATA_SIZE;
2517 }
2518
2519 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2520 sizeof(struct crypt_persist_entry);
2521
2522 return max_persistent_entries;
2523}
2524
2525static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002526{
2527 unsigned int i;
2528
2529 if (persist_data == NULL) {
2530 return -1;
2531 }
2532 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2533 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2534 /* We found it! */
2535 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2536 return 0;
2537 }
2538 }
2539
2540 return -1;
2541}
2542
Rubin Xu85c01f92014-10-13 12:49:54 +01002543static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002544{
2545 unsigned int i;
2546 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002547 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002548
2549 if (persist_data == NULL) {
2550 return -1;
2551 }
2552
Rubin Xu85c01f92014-10-13 12:49:54 +01002553 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002554
2555 num = persist_data->persist_valid_entries;
2556
2557 for (i = 0; i < num; i++) {
2558 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2559 /* We found an existing entry, update it! */
2560 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2561 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2562 return 0;
2563 }
2564 }
2565
2566 /* We didn't find it, add it to the end, if there is room */
2567 if (persist_data->persist_valid_entries < max_persistent_entries) {
2568 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2569 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2570 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2571 persist_data->persist_valid_entries++;
2572 return 0;
2573 }
2574
2575 return -1;
2576}
2577
Rubin Xu85c01f92014-10-13 12:49:54 +01002578/**
2579 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2580 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2581 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002582int match_multi_entry(const char *key, const char *field, unsigned index) {
2583 std::string key_ = key;
2584 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002585
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002586 std::string parsed_field;
2587 unsigned parsed_index;
2588
2589 std::string::size_type split = key_.find_last_of('_');
2590 if (split == std::string::npos) {
2591 parsed_field = key_;
2592 parsed_index = 0;
2593 } else {
2594 parsed_field = key_.substr(0, split);
2595 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002596 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002597
2598 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002599}
2600
2601/*
2602 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2603 * remaining entries starting from index will be deleted.
2604 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2605 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2606 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2607 *
2608 */
2609static int persist_del_keys(const char *fieldname, unsigned index)
2610{
2611 unsigned int i;
2612 unsigned int j;
2613 unsigned int num;
2614
2615 if (persist_data == NULL) {
2616 return PERSIST_DEL_KEY_ERROR_OTHER;
2617 }
2618
2619 num = persist_data->persist_valid_entries;
2620
2621 j = 0; // points to the end of non-deleted entries.
2622 // Filter out to-be-deleted entries in place.
2623 for (i = 0; i < num; i++) {
2624 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2625 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2626 j++;
2627 }
2628 }
2629
2630 if (j < num) {
2631 persist_data->persist_valid_entries = j;
2632 // Zeroise the remaining entries
2633 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2634 return PERSIST_DEL_KEY_OK;
2635 } else {
2636 // Did not find an entry matching the given fieldname
2637 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2638 }
2639}
2640
2641static int persist_count_keys(const char *fieldname)
2642{
2643 unsigned int i;
2644 unsigned int count;
2645
2646 if (persist_data == NULL) {
2647 return -1;
2648 }
2649
2650 count = 0;
2651 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2652 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2653 count++;
2654 }
2655 }
2656
2657 return count;
2658}
2659
Ken Sumrall160b4d62013-04-22 12:15:39 -07002660/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002661int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002662{
Paul Crowley38132a12016-02-09 09:50:32 +00002663 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002664 SLOGE("Cannot get field when file encrypted");
2665 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002666 }
2667
Ken Sumrall160b4d62013-04-22 12:15:39 -07002668 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002669 /* CRYPTO_GETFIELD_OK is success,
2670 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2671 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2672 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002673 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002674 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2675 int i;
2676 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002677
2678 if (persist_data == NULL) {
2679 load_persistent_data();
2680 if (persist_data == NULL) {
2681 SLOGE("Getfield error, cannot load persistent data");
2682 goto out;
2683 }
2684 }
2685
Rubin Xu85c01f92014-10-13 12:49:54 +01002686 // Read value from persistent entries. If the original value is split into multiple entries,
2687 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002688 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002689 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2690 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2691 // value too small
2692 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2693 goto out;
2694 }
2695 rc = CRYPTO_GETFIELD_OK;
2696
2697 for (i = 1; /* break explicitly */; i++) {
2698 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2699 (int) sizeof(temp_field)) {
2700 // If the fieldname is very long, we stop as soon as it begins to overflow the
2701 // maximum field length. At this point we have in fact fully read out the original
2702 // value because cryptfs_setfield would not allow fields with longer names to be
2703 // written in the first place.
2704 break;
2705 }
2706 if (!persist_get_key(temp_field, temp_value)) {
2707 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2708 // value too small.
2709 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2710 goto out;
2711 }
2712 } else {
2713 // Exhaust all entries.
2714 break;
2715 }
2716 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002717 } else {
2718 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002719 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002720 }
2721
2722out:
2723 return rc;
2724}
2725
2726/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002727int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002728{
Paul Crowley38132a12016-02-09 09:50:32 +00002729 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002730 SLOGE("Cannot set field when file encrypted");
2731 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002732 }
2733
Ken Sumrall160b4d62013-04-22 12:15:39 -07002734 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002735 /* 0 is success, negative values are error */
2736 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002737 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002738 unsigned int field_id;
2739 char temp_field[PROPERTY_KEY_MAX];
2740 unsigned int num_entries;
2741 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002742
2743 if (persist_data == NULL) {
2744 load_persistent_data();
2745 if (persist_data == NULL) {
2746 SLOGE("Setfield error, cannot load persistent data");
2747 goto out;
2748 }
2749 }
2750
2751 property_get("ro.crypto.state", encrypted_state, "");
2752 if (!strcmp(encrypted_state, "encrypted") ) {
2753 encrypted = 1;
2754 }
2755
Rubin Xu85c01f92014-10-13 12:49:54 +01002756 // Compute the number of entries required to store value, each entry can store up to
2757 // (PROPERTY_VALUE_MAX - 1) chars
2758 if (strlen(value) == 0) {
2759 // Empty value also needs one entry to store.
2760 num_entries = 1;
2761 } else {
2762 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2763 }
2764
2765 max_keylen = strlen(fieldname);
2766 if (num_entries > 1) {
2767 // Need an extra "_%d" suffix.
2768 max_keylen += 1 + log10(num_entries);
2769 }
2770 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2771 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002772 goto out;
2773 }
2774
Rubin Xu85c01f92014-10-13 12:49:54 +01002775 // Make sure we have enough space to write the new value
2776 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2777 persist_get_max_entries(encrypted)) {
2778 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2779 goto out;
2780 }
2781
2782 // Now that we know persist_data has enough space for value, let's delete the old field first
2783 // to make up space.
2784 persist_del_keys(fieldname, 0);
2785
2786 if (persist_set_key(fieldname, value, encrypted)) {
2787 // fail to set key, should not happen as we have already checked the available space
2788 SLOGE("persist_set_key() error during setfield()");
2789 goto out;
2790 }
2791
2792 for (field_id = 1; field_id < num_entries; field_id++) {
2793 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
2794
2795 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2796 // fail to set key, should not happen as we have already checked the available space.
2797 SLOGE("persist_set_key() error during setfield()");
2798 goto out;
2799 }
2800 }
2801
Ken Sumrall160b4d62013-04-22 12:15:39 -07002802 /* If we are running encrypted, save the persistent data now */
2803 if (encrypted) {
2804 if (save_persistent_data()) {
2805 SLOGE("Setfield error, cannot save persistent data");
2806 goto out;
2807 }
2808 }
2809
Rubin Xu85c01f92014-10-13 12:49:54 +01002810 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002811
2812out:
2813 return rc;
2814}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002815
2816/* Checks userdata. Attempt to mount the volume if default-
2817 * encrypted.
2818 * On success trigger next init phase and return 0.
2819 * Currently do not handle failure - see TODO below.
2820 */
2821int cryptfs_mount_default_encrypted(void)
2822{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002823 int crypt_type = cryptfs_get_password_type();
2824 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2825 SLOGE("Bad crypt type - error");
2826 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2827 SLOGD("Password is not default - "
2828 "starting min framework to prompt");
2829 property_set("vold.decrypt", "trigger_restart_min_framework");
2830 return 0;
2831 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2832 SLOGD("Password is default - restarting filesystem");
2833 cryptfs_restart_internal(0);
2834 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002835 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002836 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002837 }
2838
Paul Lawrence6bfed202014-07-28 12:47:22 -07002839 /** Corrupt. Allow us to boot into framework, which will detect bad
2840 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002841 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002842 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002843 return 0;
2844}
2845
2846/* Returns type of the password, default, pattern, pin or password.
2847 */
2848int cryptfs_get_password_type(void)
2849{
Paul Crowley38132a12016-02-09 09:50:32 +00002850 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002851 SLOGE("cryptfs_get_password_type not valid for file encryption");
2852 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002853 }
2854
Paul Lawrencef4faa572014-01-29 13:31:03 -08002855 struct crypt_mnt_ftr crypt_ftr;
2856
2857 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2858 SLOGE("Error getting crypt footer and key\n");
2859 return -1;
2860 }
2861
Paul Lawrence6bfed202014-07-28 12:47:22 -07002862 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2863 return -1;
2864 }
2865
Paul Lawrencef4faa572014-01-29 13:31:03 -08002866 return crypt_ftr.crypt_type;
2867}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002868
Paul Lawrence05335c32015-03-05 09:46:23 -08002869const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002870{
Paul Crowley38132a12016-02-09 09:50:32 +00002871 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002872 SLOGE("cryptfs_get_password not valid for file encryption");
2873 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002874 }
2875
Paul Lawrence399317e2014-03-10 13:20:50 -07002876 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002877 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002878 if (now.tv_sec < password_expiry_time) {
2879 return password;
2880 } else {
2881 cryptfs_clear_password();
2882 return 0;
2883 }
2884}
2885
2886void cryptfs_clear_password()
2887{
2888 if (password) {
2889 size_t len = strlen(password);
2890 memset(password, 0, len);
2891 free(password);
2892 password = 0;
2893 password_expiry_time = 0;
2894 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002895}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002896
Paul Lawrence0c247462015-10-29 10:30:57 -07002897int cryptfs_isConvertibleToFBE()
2898{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002899 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002900 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2901}