blob: c152631f8e108a9a0dba79a8be50f2e7ca1e09b3 [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
Logan Chien862eef72018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
27#include "EncryptInplace.h"
28#include "Ext4Crypt.h"
29#include "Keymaster.h"
30#include "Process.h"
31#include "ScryptParameters.h"
32#include "VoldUtil.h"
33#include "VolumeManager.h"
34#include "secontext.h"
35
36#include <bootloader_message/bootloader_message.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070037#include <ext4_utils/ext4.h>
38#include <ext4_utils/ext4_utils.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070039#include <fs_mgr.h>
Logan Chien862eef72018-05-02 11:36:45 +080040#include <logwrap/logwrap.h>
41#include <openssl/evp.h>
42#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080043#include <selinux/selinux.h>
Logan Chien862eef72018-05-02 11:36:45 +080044#include "android-base/properties.h"
45#include "cutils/android_reboot.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080046#include "cutils/log.h"
47#include "cutils/properties.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000048#include "f2fs_sparseblock.h"
Logan Chien862eef72018-05-02 11:36:45 +080049#include "hardware_legacy/power.h"
50
51#include <ctype.h>
52#include <errno.h>
53#include <fcntl.h>
54#include <inttypes.h>
55#include <libgen.h>
56#include <linux/dm-ioctl.h>
57#include <linux/kdev_t.h>
58#include <math.h>
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <sys/ioctl.h>
63#include <sys/mount.h>
64#include <sys/param.h>
65#include <sys/stat.h>
66#include <sys/types.h>
67#include <sys/wait.h>
68#include <time.h>
69#include <unistd.h>
70
Wei Wang4375f1b2017-02-24 17:43:01 -080071extern "C" {
72#include <crypto_scrypt.h>
73}
Mark Salyzyn3e971272014-01-21 13:27:04 -080074
Mark Salyzyn5eecc442014-02-12 14:16:14 -080075#define UNUSED __attribute__((unused))
76
Ken Sumrall8f869aa2010-12-03 03:47:09 -080077#define DM_CRYPT_BUF_SIZE 4096
78
Jason parks70a4b3f2011-01-28 10:10:47 -060079#define HASH_COUNT 2000
80#define KEY_LEN_BYTES 16
81#define IV_LEN_BYTES 16
82
Ken Sumrall29d8da82011-05-18 17:20:07 -070083#define KEY_IN_FOOTER "footer"
84
Paul Lawrence3bd36d52015-06-09 13:37:44 -070085#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080086
Paul Lawrence3d99eba2015-11-20 07:07:19 -080087#define CRYPTO_BLOCK_DEVICE "userdata"
88
89#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
90
Ken Sumrall29d8da82011-05-18 17:20:07 -070091#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070092#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070093
Ken Sumralle919efe2012-09-29 17:07:41 -070094#define TABLE_LOAD_RETRIES 10
95
Shawn Willden47ba10d2014-09-03 17:07:06 -060096#define RSA_KEY_SIZE 2048
97#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
98#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060099#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700100
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700101#define RETRY_MOUNT_ATTEMPTS 10
102#define RETRY_MOUNT_DELAY_SECONDS 1
103
Paul Crowley73473332017-11-21 15:43:51 -0800104static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
105
Jason parks70a4b3f2011-01-28 10:10:47 -0600106static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700107static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600108static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700109static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800110
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700111/* Should we use keymaster? */
112static int keymaster_check_compatibility()
113{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000114 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700115}
116
117/* Create a new keymaster key and store it in this footer */
118static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
119{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800120 if (ftr->keymaster_blob_size) {
121 SLOGI("Already have key");
122 return 0;
123 }
124
Janis Danisevskis015ec302017-01-31 11:31:08 +0000125 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
126 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
127 &ftr->keymaster_blob_size);
128 if (rc) {
129 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800130 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000131 ftr->keymaster_blob_size = 0;
132 }
133 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700134 return -1;
135 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000136 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700137}
138
Shawn Willdene17a9c42014-09-08 13:04:08 -0600139/* This signs the given object using the keymaster key. */
140static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600141 const unsigned char *object,
142 const size_t object_size,
143 unsigned char **signature,
144 size_t *signature_size)
145{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600146 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600147 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600148 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600149
Shawn Willdene17a9c42014-09-08 13:04:08 -0600150 // To sign a message with RSA, the message must satisfy two
151 // constraints:
152 //
153 // 1. The message, when interpreted as a big-endian numeric value, must
154 // be strictly less than the public modulus of the RSA key. Note
155 // that because the most significant bit of the public modulus is
156 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
157 // key), an n-bit message with most significant bit 0 always
158 // satisfies this requirement.
159 //
160 // 2. The message must have the same length in bits as the public
161 // modulus of the RSA key. This requirement isn't mathematically
162 // necessary, but is necessary to ensure consistency in
163 // implementations.
164 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600165 case KDF_SCRYPT_KEYMASTER:
166 // This ensures the most significant byte of the signed message
167 // is zero. We could have zero-padded to the left instead, but
168 // this approach is slightly more robust against changes in
169 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600170 // so) because we really should be using a proper deterministic
171 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800172 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600173 SLOGI("Signing safely-padded object");
174 break;
175 default:
176 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000177 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600178 }
Paul Crowley73473332017-11-21 15:43:51 -0800179 for (;;) {
180 auto result = keymaster_sign_object_for_cryptfs_scrypt(
181 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
182 to_sign_size, signature, signature_size);
183 switch (result) {
184 case KeymasterSignResult::ok:
185 return 0;
186 case KeymasterSignResult::upgrade:
187 break;
188 default:
189 return -1;
190 }
191 SLOGD("Upgrading key");
192 if (keymaster_upgrade_key_for_cryptfs_scrypt(
193 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
194 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
195 &ftr->keymaster_blob_size) != 0) {
196 SLOGE("Failed to upgrade key");
197 return -1;
198 }
199 if (put_crypt_ftr_and_key(ftr) != 0) {
200 SLOGE("Failed to write upgraded key to disk");
201 }
202 SLOGD("Key upgraded successfully");
203 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600204}
205
Paul Lawrence399317e2014-03-10 13:20:50 -0700206/* Store password when userdata is successfully decrypted and mounted.
207 * Cleared by cryptfs_clear_password
208 *
209 * To avoid a double prompt at boot, we need to store the CryptKeeper
210 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
211 * Since the entire framework is torn down and rebuilt after encryption,
212 * we have to use a daemon or similar to store the password. Since vold
213 * is secured against IPC except from system processes, it seems a reasonable
214 * place to store this.
215 *
216 * password should be cleared once it has been used.
217 *
218 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800219 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700220static char* password = 0;
221static int password_expiry_time = 0;
222static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800223
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800224extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800225
Josh Gaofec44372017-08-28 13:22:55 -0700226enum class RebootType {reboot, recovery, shutdown};
227static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700228{
Josh Gaofec44372017-08-28 13:22:55 -0700229 switch (rt) {
230 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800231 property_set(ANDROID_RB_PROPERTY, "reboot");
232 break;
233
Josh Gaofec44372017-08-28 13:22:55 -0700234 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800235 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
236 break;
237
Josh Gaofec44372017-08-28 13:22:55 -0700238 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800239 property_set(ANDROID_RB_PROPERTY, "shutdown");
240 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700241 }
Paul Lawrence87999172014-02-20 12:21:31 -0800242
Ken Sumralladfba362013-06-04 16:37:52 -0700243 sleep(20);
244
245 /* Shouldn't get here, reboot should happen before sleep times out */
246 return;
247}
248
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800249static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
250{
251 memset(io, 0, dataSize);
252 io->data_size = dataSize;
253 io->data_start = sizeof(struct dm_ioctl);
254 io->version[0] = 4;
255 io->version[1] = 0;
256 io->version[2] = 0;
257 io->flags = flags;
258 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100259 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800260 }
261}
262
Kenny Rootc4c70f12013-06-14 12:11:38 -0700263/**
264 * Gets the default device scrypt parameters for key derivation time tuning.
265 * The parameters should lead to about one second derivation time for the
266 * given device.
267 */
268static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700269 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000270 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700271
Paul Crowley63c18d32016-02-10 14:02:47 +0000272 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
273 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
274 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
275 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700276 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000277 ftr->N_factor = Nf;
278 ftr->r_factor = rf;
279 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700280}
281
Ken Sumrall3ed82362011-01-28 23:31:16 -0800282static unsigned int get_fs_size(char *dev)
283{
284 int fd, block_size;
285 struct ext4_super_block sb;
286 off64_t len;
287
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700288 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800289 SLOGE("Cannot open device to get filesystem size ");
290 return 0;
291 }
292
293 if (lseek64(fd, 1024, SEEK_SET) < 0) {
294 SLOGE("Cannot seek to superblock");
295 return 0;
296 }
297
298 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
299 SLOGE("Cannot read superblock");
300 return 0;
301 }
302
303 close(fd);
304
Daniel Rosenberge82df162014-08-15 22:19:23 +0000305 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
306 SLOGE("Not a valid ext4 superblock");
307 return 0;
308 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800309 block_size = 1024 << sb.s_log_block_size;
310 /* compute length in bytes */
311 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
312
313 /* return length in sectors */
314 return (unsigned int) (len / 512);
315}
316
Ken Sumrall160b4d62013-04-22 12:15:39 -0700317static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
318{
319 static int cached_data = 0;
320 static off64_t cached_off = 0;
321 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
322 int fd;
323 char key_loc[PROPERTY_VALUE_MAX];
324 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700325 int rc = -1;
326
327 if (!cached_data) {
328 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
329
330 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700331 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700332 SLOGE("Cannot open real block device %s\n", real_blkdev);
333 return -1;
334 }
335
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900336 unsigned long nr_sec = 0;
337 get_blkdev_size(fd, &nr_sec);
338 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700339 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
340 * encryption info footer and key, and plenty of bytes to spare for future
341 * growth.
342 */
343 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
344 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
345 cached_data = 1;
346 } else {
347 SLOGE("Cannot get size of block device %s\n", real_blkdev);
348 }
349 close(fd);
350 } else {
351 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
352 cached_off = 0;
353 cached_data = 1;
354 }
355 }
356
357 if (cached_data) {
358 if (metadata_fname) {
359 *metadata_fname = cached_metadata_fname;
360 }
361 if (off) {
362 *off = cached_off;
363 }
364 rc = 0;
365 }
366
367 return rc;
368}
369
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800370/* Set sha256 checksum in structure */
371static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
372{
373 SHA256_CTX c;
374 SHA256_Init(&c);
375 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
376 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
377 SHA256_Final(crypt_ftr->sha256, &c);
378}
379
Ken Sumralle8744072011-01-18 22:01:55 -0800380/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800381 * update the failed mount count but not change the key.
382 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700383static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800384{
385 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800386 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700387 /* starting_off is set to the SEEK_SET offset
388 * where the crypto structure starts
389 */
390 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800391 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700392 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700393 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800394
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800395 set_ftr_sha(crypt_ftr);
396
Ken Sumrall160b4d62013-04-22 12:15:39 -0700397 if (get_crypt_ftr_info(&fname, &starting_off)) {
398 SLOGE("Unable to get crypt_ftr_info\n");
399 return -1;
400 }
401 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700402 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700403 return -1;
404 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700405 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700406 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700407 return -1;
408 }
409
410 /* Seek to the start of the crypt footer */
411 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
412 SLOGE("Cannot seek to real block device footer\n");
413 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800414 }
415
416 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
417 SLOGE("Cannot write real block device footer\n");
418 goto errout;
419 }
420
Ken Sumrall3be890f2011-09-14 16:53:46 -0700421 fstat(fd, &statbuf);
422 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700423 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700424 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800425 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800426 goto errout;
427 }
428 }
429
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800430 /* Success! */
431 rc = 0;
432
433errout:
434 close(fd);
435 return rc;
436
437}
438
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800439static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
440{
441 struct crypt_mnt_ftr copy;
442 memcpy(&copy, crypt_ftr, sizeof(copy));
443 set_ftr_sha(&copy);
444 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
445}
446
Ken Sumrall160b4d62013-04-22 12:15:39 -0700447static inline int unix_read(int fd, void* buff, int len)
448{
449 return TEMP_FAILURE_RETRY(read(fd, buff, len));
450}
451
452static inline int unix_write(int fd, const void* buff, int len)
453{
454 return TEMP_FAILURE_RETRY(write(fd, buff, len));
455}
456
457static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
458{
459 memset(pdata, 0, len);
460 pdata->persist_magic = PERSIST_DATA_MAGIC;
461 pdata->persist_valid_entries = 0;
462}
463
464/* A routine to update the passed in crypt_ftr to the lastest version.
465 * fd is open read/write on the device that holds the crypto footer and persistent
466 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
467 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
468 */
469static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
470{
Kenny Root7434b312013-06-14 11:29:53 -0700471 int orig_major = crypt_ftr->major_version;
472 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700473
Kenny Root7434b312013-06-14 11:29:53 -0700474 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
475 struct crypt_persist_data *pdata;
476 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700477
Kenny Rootc4c70f12013-06-14 12:11:38 -0700478 SLOGW("upgrading crypto footer to 1.1");
479
Wei Wang4375f1b2017-02-24 17:43:01 -0800480 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700481 if (pdata == NULL) {
482 SLOGE("Cannot allocate persisent data\n");
483 return;
484 }
485 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
486
487 /* Need to initialize the persistent data area */
488 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
489 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100490 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700491 return;
492 }
493 /* Write all zeros to the first copy, making it invalid */
494 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
495
496 /* Write a valid but empty structure to the second copy */
497 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
498 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
499
500 /* Update the footer */
501 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
502 crypt_ftr->persist_data_offset[0] = pdata_offset;
503 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
504 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100505 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700506 }
507
Paul Lawrencef4faa572014-01-29 13:31:03 -0800508 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700509 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800510 /* But keep the old kdf_type.
511 * It will get updated later to KDF_SCRYPT after the password has been verified.
512 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700513 crypt_ftr->kdf_type = KDF_PBKDF2;
514 get_device_scrypt_params(crypt_ftr);
515 crypt_ftr->minor_version = 2;
516 }
517
Paul Lawrencef4faa572014-01-29 13:31:03 -0800518 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
519 SLOGW("upgrading crypto footer to 1.3");
520 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
521 crypt_ftr->minor_version = 3;
522 }
523
Kenny Root7434b312013-06-14 11:29:53 -0700524 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
525 if (lseek64(fd, offset, SEEK_SET) == -1) {
526 SLOGE("Cannot seek to crypt footer\n");
527 return;
528 }
529 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700530 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700531}
532
533
534static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800535{
536 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800537 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700538 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800539 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700540 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700541 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800542
Ken Sumrall160b4d62013-04-22 12:15:39 -0700543 if (get_crypt_ftr_info(&fname, &starting_off)) {
544 SLOGE("Unable to get crypt_ftr_info\n");
545 return -1;
546 }
547 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700548 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700549 return -1;
550 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700551 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700552 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700553 return -1;
554 }
555
556 /* Make sure it's 16 Kbytes in length */
557 fstat(fd, &statbuf);
558 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
559 SLOGE("footer file %s is not the expected size!\n", fname);
560 goto errout;
561 }
562
563 /* Seek to the start of the crypt footer */
564 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
565 SLOGE("Cannot seek to real block device footer\n");
566 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800567 }
568
569 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
570 SLOGE("Cannot read real block device footer\n");
571 goto errout;
572 }
573
574 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700575 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800576 goto errout;
577 }
578
Kenny Rootc96a5f82013-06-14 12:08:28 -0700579 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
580 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
581 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800582 goto errout;
583 }
584
Kenny Rootc96a5f82013-06-14 12:08:28 -0700585 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
586 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
587 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800588 }
589
Ken Sumrall160b4d62013-04-22 12:15:39 -0700590 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
591 * copy on disk before returning.
592 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700593 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700594 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800595 }
596
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800597 /* Success! */
598 rc = 0;
599
600errout:
601 close(fd);
602 return rc;
603}
604
Ken Sumrall160b4d62013-04-22 12:15:39 -0700605static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
606{
607 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
608 crypt_ftr->persist_data_offset[1]) {
609 SLOGE("Crypt_ftr persist data regions overlap");
610 return -1;
611 }
612
613 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
614 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
615 return -1;
616 }
617
618 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
619 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
620 CRYPT_FOOTER_OFFSET) {
621 SLOGE("Persistent data extends past crypto footer");
622 return -1;
623 }
624
625 return 0;
626}
627
628static int load_persistent_data(void)
629{
630 struct crypt_mnt_ftr crypt_ftr;
631 struct crypt_persist_data *pdata = NULL;
632 char encrypted_state[PROPERTY_VALUE_MAX];
633 char *fname;
634 int found = 0;
635 int fd;
636 int ret;
637 int i;
638
639 if (persist_data) {
640 /* Nothing to do, we've already loaded or initialized it */
641 return 0;
642 }
643
644
645 /* If not encrypted, just allocate an empty table and initialize it */
646 property_get("ro.crypto.state", encrypted_state, "");
647 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800648 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700649 if (pdata) {
650 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
651 persist_data = pdata;
652 return 0;
653 }
654 return -1;
655 }
656
657 if(get_crypt_ftr_and_key(&crypt_ftr)) {
658 return -1;
659 }
660
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700661 if ((crypt_ftr.major_version < 1)
662 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700663 SLOGE("Crypt_ftr version doesn't support persistent data");
664 return -1;
665 }
666
667 if (get_crypt_ftr_info(&fname, NULL)) {
668 return -1;
669 }
670
671 ret = validate_persistent_data_storage(&crypt_ftr);
672 if (ret) {
673 return -1;
674 }
675
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700676 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700677 if (fd < 0) {
678 SLOGE("Cannot open %s metadata file", fname);
679 return -1;
680 }
681
Wei Wang4375f1b2017-02-24 17:43:01 -0800682 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800683 if (pdata == NULL) {
684 SLOGE("Cannot allocate memory for persistent data");
685 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700686 }
687
688 for (i = 0; i < 2; i++) {
689 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
690 SLOGE("Cannot seek to read persistent data on %s", fname);
691 goto err2;
692 }
693 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
694 SLOGE("Error reading persistent data on iteration %d", i);
695 goto err2;
696 }
697 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
698 found = 1;
699 break;
700 }
701 }
702
703 if (!found) {
704 SLOGI("Could not find valid persistent data, creating");
705 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
706 }
707
708 /* Success */
709 persist_data = pdata;
710 close(fd);
711 return 0;
712
713err2:
714 free(pdata);
715
716err:
717 close(fd);
718 return -1;
719}
720
721static int save_persistent_data(void)
722{
723 struct crypt_mnt_ftr crypt_ftr;
724 struct crypt_persist_data *pdata;
725 char *fname;
726 off64_t write_offset;
727 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700728 int fd;
729 int ret;
730
731 if (persist_data == NULL) {
732 SLOGE("No persistent data to save");
733 return -1;
734 }
735
736 if(get_crypt_ftr_and_key(&crypt_ftr)) {
737 return -1;
738 }
739
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700740 if ((crypt_ftr.major_version < 1)
741 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700742 SLOGE("Crypt_ftr version doesn't support persistent data");
743 return -1;
744 }
745
746 ret = validate_persistent_data_storage(&crypt_ftr);
747 if (ret) {
748 return -1;
749 }
750
751 if (get_crypt_ftr_info(&fname, NULL)) {
752 return -1;
753 }
754
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700755 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700756 if (fd < 0) {
757 SLOGE("Cannot open %s metadata file", fname);
758 return -1;
759 }
760
Wei Wang4375f1b2017-02-24 17:43:01 -0800761 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700762 if (pdata == NULL) {
763 SLOGE("Cannot allocate persistant data");
764 goto err;
765 }
766
767 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
768 SLOGE("Cannot seek to read persistent data on %s", fname);
769 goto err2;
770 }
771
772 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
773 SLOGE("Error reading persistent data before save");
774 goto err2;
775 }
776
777 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
778 /* The first copy is the curent valid copy, so write to
779 * the second copy and erase this one */
780 write_offset = crypt_ftr.persist_data_offset[1];
781 erase_offset = crypt_ftr.persist_data_offset[0];
782 } else {
783 /* The second copy must be the valid copy, so write to
784 * the first copy, and erase the second */
785 write_offset = crypt_ftr.persist_data_offset[0];
786 erase_offset = crypt_ftr.persist_data_offset[1];
787 }
788
789 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100790 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700791 SLOGE("Cannot seek to write persistent data");
792 goto err2;
793 }
794 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
795 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100796 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700797 SLOGE("Cannot seek to erase previous persistent data");
798 goto err2;
799 }
800 fsync(fd);
801 memset(pdata, 0, crypt_ftr.persist_data_size);
802 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
803 (int) crypt_ftr.persist_data_size) {
804 SLOGE("Cannot write to erase previous persistent data");
805 goto err2;
806 }
807 fsync(fd);
808 } else {
809 SLOGE("Cannot write to save persistent data");
810 goto err2;
811 }
812
813 /* Success */
814 free(pdata);
815 close(fd);
816 return 0;
817
818err2:
819 free(pdata);
820err:
821 close(fd);
822 return -1;
823}
824
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800825/* Convert a binary key of specified length into an ascii hex string equivalent,
826 * without the leading 0x and with null termination
827 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700828static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700829 unsigned int keysize, char *master_key_ascii) {
830 unsigned int i, a;
831 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800832
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700833 for (i=0, a=0; i<keysize; i++, a+=2) {
834 /* For each byte, write out two ascii hex digits */
835 nibble = (master_key[i] >> 4) & 0xf;
836 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800837
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700838 nibble = master_key[i] & 0xf;
839 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
840 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800841
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700842 /* Add the null termination */
843 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800844
845}
846
Jeff Sharkey9c484982015-03-31 10:35:33 -0700847static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
848 const unsigned char *master_key, const char *real_blk_name,
849 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800850 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800851 struct dm_ioctl *io;
852 struct dm_target_spec *tgt;
853 char *crypt_params;
854 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800855 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800856 int i;
857
858 io = (struct dm_ioctl *) buffer;
859
860 /* Load the mapping table for this device */
861 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
862
863 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
864 io->target_count = 1;
865 tgt->status = 0;
866 tgt->sector_start = 0;
867 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700868 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800869
870 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
871 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800872
873 buff_offset = crypt_params - buffer;
874 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
875 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
876 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800877 crypt_params += strlen(crypt_params) + 1;
878 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
879 tgt->next = crypt_params - buffer;
880
881 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
882 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
883 break;
884 }
885 usleep(500000);
886 }
887
888 if (i == TABLE_LOAD_RETRIES) {
889 /* We failed to load the table, return an error */
890 return -1;
891 } else {
892 return i + 1;
893 }
894}
895
896
897static int get_dm_crypt_version(int fd, const char *name, int *version)
898{
899 char buffer[DM_CRYPT_BUF_SIZE];
900 struct dm_ioctl *io;
901 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800902
903 io = (struct dm_ioctl *) buffer;
904
905 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
906
907 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
908 return -1;
909 }
910
911 /* Iterate over the returned versions, looking for name of "crypt".
912 * When found, get and return the version.
913 */
914 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
915 while (v->next) {
916 if (! strcmp(v->name, "crypt")) {
917 /* We found the crypt driver, return the version, and get out */
918 version[0] = v->version[0];
919 version[1] = v->version[1];
920 version[2] = v->version[2];
921 return 0;
922 }
923 v = (struct dm_target_versions *)(((char *)v) + v->next);
924 }
925
926 return -1;
927}
928
Jeff Sharkey9c484982015-03-31 10:35:33 -0700929static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
930 const unsigned char *master_key, const char *real_blk_name,
931 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800932 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800933 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800934 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -0700935 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800936 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800937 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800938 int version[3];
Wei Wang4375f1b2017-02-24 17:43:01 -0800939 const char *extra_params;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800940 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700942 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800943 SLOGE("Cannot open device-mapper\n");
944 goto errout;
945 }
946
947 io = (struct dm_ioctl *) buffer;
948
949 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800950 err = ioctl(fd, DM_DEV_CREATE, io);
951 if (err) {
952 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800953 goto errout;
954 }
955
956 /* Get the device status, in particular, the name of it's device file */
957 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
958 if (ioctl(fd, DM_DEV_STATUS, io)) {
959 SLOGE("Cannot retrieve dm-crypt device status\n");
960 goto errout;
961 }
962 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
963 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
964
Ken Sumralldb5e0262013-02-05 17:39:48 -0800965 extra_params = "";
966 if (! get_dm_crypt_version(fd, name, version)) {
967 /* Support for allow_discards was added in version 1.11.0 */
968 if ((version[0] >= 2) ||
969 ((version[0] == 1) && (version[1] >= 11))) {
970 extra_params = "1 allow_discards";
971 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
972 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700973 }
974
Ken Sumralldb5e0262013-02-05 17:39:48 -0800975 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
976 fd, extra_params);
977 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800978 SLOGE("Cannot load dm-crypt mapping table.\n");
979 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800980 } else if (load_count > 1) {
981 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800982 }
983
984 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800985 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800986
987 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
988 SLOGE("Cannot resume the dm-crypt device\n");
989 goto errout;
990 }
991
992 /* We made it here with no errors. Woot! */
993 retval = 0;
994
995errout:
996 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
997
998 return retval;
999}
1000
Wei Wang4375f1b2017-02-24 17:43:01 -08001001static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001002{
1003 int fd;
1004 char buffer[DM_CRYPT_BUF_SIZE];
1005 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001006 int retval = -1;
1007
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001008 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001009 SLOGE("Cannot open device-mapper\n");
1010 goto errout;
1011 }
1012
1013 io = (struct dm_ioctl *) buffer;
1014
1015 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1016 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1017 SLOGE("Cannot remove dm-crypt device\n");
1018 goto errout;
1019 }
1020
1021 /* We made it here with no errors. Woot! */
1022 retval = 0;
1023
1024errout:
1025 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1026
1027 return retval;
1028
1029}
1030
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001031static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001032 unsigned char *ikey, void *params UNUSED)
1033{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001034 SLOGI("Using pbkdf2 for cryptfs KDF");
1035
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001036 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001037 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1038 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1039 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001040}
1041
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001042static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001043 unsigned char *ikey, void *params)
1044{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001045 SLOGI("Using scrypt for cryptfs KDF");
1046
Kenny Rootc4c70f12013-06-14 12:11:38 -07001047 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1048
1049 int N = 1 << ftr->N_factor;
1050 int r = 1 << ftr->r_factor;
1051 int p = 1 << ftr->p_factor;
1052
1053 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001054 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001055 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1056 salt, SALT_LEN, N, r, p, ikey,
1057 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001058
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001059 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001060}
1061
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001062static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1063 unsigned char *ikey, void *params)
1064{
1065 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1066
1067 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001068 size_t signature_size;
1069 unsigned char* signature;
1070 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1071
1072 int N = 1 << ftr->N_factor;
1073 int r = 1 << ftr->r_factor;
1074 int p = 1 << ftr->p_factor;
1075
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001076 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1077 salt, SALT_LEN, N, r, p, ikey,
1078 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001079
1080 if (rc) {
1081 SLOGE("scrypt failed");
1082 return -1;
1083 }
1084
Shawn Willdene17a9c42014-09-08 13:04:08 -06001085 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1086 &signature, &signature_size)) {
1087 SLOGE("Signing failed");
1088 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001089 }
1090
1091 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1092 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1093 free(signature);
1094
1095 if (rc) {
1096 SLOGE("scrypt failed");
1097 return -1;
1098 }
1099
1100 return 0;
1101}
1102
1103static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1104 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001105 unsigned char *encrypted_master_key,
1106 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001107{
1108 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1109 EVP_CIPHER_CTX e_ctx;
1110 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001111 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001112
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001113 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001114 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001115
1116 switch (crypt_ftr->kdf_type) {
1117 case KDF_SCRYPT_KEYMASTER:
1118 if (keymaster_create_key(crypt_ftr)) {
1119 SLOGE("keymaster_create_key failed");
1120 return -1;
1121 }
1122
1123 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1124 SLOGE("scrypt failed");
1125 return -1;
1126 }
1127 break;
1128
1129 case KDF_SCRYPT:
1130 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1131 SLOGE("scrypt failed");
1132 return -1;
1133 }
1134 break;
1135
1136 default:
1137 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001138 return -1;
1139 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001140
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001141 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001142 EVP_CIPHER_CTX_init(&e_ctx);
1143 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001144 SLOGE("EVP_EncryptInit failed\n");
1145 return -1;
1146 }
1147 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001148
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001150 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001151 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001152 SLOGE("EVP_EncryptUpdate failed\n");
1153 return -1;
1154 }
Adam Langley889c4f12014-09-03 14:23:13 -07001155 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 SLOGE("EVP_EncryptFinal failed\n");
1157 return -1;
1158 }
1159
1160 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1161 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1162 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001163 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001164
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001165 /* Store the scrypt of the intermediate key, so we can validate if it's a
1166 password error or mount error when things go wrong.
1167 Note there's no need to check for errors, since if this is incorrect, we
1168 simply won't wipe userdata, which is the correct default behavior
1169 */
1170 int N = 1 << crypt_ftr->N_factor;
1171 int r = 1 << crypt_ftr->r_factor;
1172 int p = 1 << crypt_ftr->p_factor;
1173
1174 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1175 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1176 crypt_ftr->scrypted_intermediate_key,
1177 sizeof(crypt_ftr->scrypted_intermediate_key));
1178
1179 if (rc) {
1180 SLOGE("encrypt_master_key: crypto_scrypt failed");
1181 }
1182
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001183 EVP_CIPHER_CTX_cleanup(&e_ctx);
1184
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001185 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001186}
1187
Paul Lawrence731a7a22015-04-28 22:14:15 +00001188static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001189 unsigned char *encrypted_master_key,
1190 unsigned char *decrypted_master_key,
1191 kdf_func kdf, void *kdf_params,
1192 unsigned char** intermediate_key,
1193 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001194{
1195 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 -08001196 EVP_CIPHER_CTX d_ctx;
1197 int decrypted_len, final_len;
1198
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001199 /* Turn the password into an intermediate key and IV that can decrypt the
1200 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001201 if (kdf(passwd, salt, ikey, kdf_params)) {
1202 SLOGE("kdf failed");
1203 return -1;
1204 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001205
1206 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001207 EVP_CIPHER_CTX_init(&d_ctx);
1208 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001209 return -1;
1210 }
1211 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1212 /* Decrypt the master key */
1213 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1214 encrypted_master_key, KEY_LEN_BYTES)) {
1215 return -1;
1216 }
Adam Langley889c4f12014-09-03 14:23:13 -07001217 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001218 return -1;
1219 }
1220
1221 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1222 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001224
1225 /* Copy intermediate key if needed by params */
1226 if (intermediate_key && intermediate_key_size) {
1227 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001228 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001229 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1230 *intermediate_key_size = KEY_LEN_BYTES;
1231 }
1232 }
1233
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001234 EVP_CIPHER_CTX_cleanup(&d_ctx);
1235
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001236 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001237}
1238
Kenny Rootc4c70f12013-06-14 12:11:38 -07001239static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001240{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001241 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001242 *kdf = scrypt_keymaster;
1243 *kdf_params = ftr;
1244 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001245 *kdf = scrypt;
1246 *kdf_params = ftr;
1247 } else {
1248 *kdf = pbkdf2;
1249 *kdf_params = NULL;
1250 }
1251}
1252
Paul Lawrence731a7a22015-04-28 22:14:15 +00001253static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001254 struct crypt_mnt_ftr *crypt_ftr,
1255 unsigned char** intermediate_key,
1256 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001257{
1258 kdf_func kdf;
1259 void *kdf_params;
1260 int ret;
1261
1262 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001263 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1264 decrypted_master_key, kdf, kdf_params,
1265 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001266 if (ret != 0) {
1267 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001268 }
1269
1270 return ret;
1271}
1272
Wei Wang4375f1b2017-02-24 17:43:01 -08001273static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001274 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001275 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001276 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001277
1278 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001279 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001280 read(fd, key_buf, sizeof(key_buf));
1281 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001282 close(fd);
1283
1284 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001285 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001286}
1287
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001288int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001289{
Greg Hackmann955653e2014-09-24 14:55:20 -07001290 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001291#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001292
1293 /* Now umount the tmpfs filesystem */
1294 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001295 if (umount(mountpoint) == 0) {
1296 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001297 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001298
1299 if (errno == EINVAL) {
1300 /* EINVAL is returned if the directory is not a mountpoint,
1301 * i.e. there is no filesystem mounted there. So just get out.
1302 */
1303 break;
1304 }
1305
1306 err = errno;
1307
1308 /* If allowed, be increasingly aggressive before the last two retries */
1309 if (kill) {
1310 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1311 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001312 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001313 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1314 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001315 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001316 }
1317 }
1318
1319 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001320 }
1321
1322 if (i < WAIT_UNMOUNT_COUNT) {
1323 SLOGD("unmounting %s succeeded\n", mountpoint);
1324 rc = 0;
1325 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001326 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001327 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001328 rc = -1;
1329 }
1330
1331 return rc;
1332}
1333
Wei Wang42e38102017-06-07 10:46:12 -07001334static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001335{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001336 // NOTE: post_fs_data results in init calling back around to vold, so all
1337 // callers to this method must be async
1338
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001339 /* Do the prep of the /data filesystem */
1340 property_set("vold.post_fs_data_done", "0");
1341 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001342 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001343
Ken Sumrallc5872692013-05-14 15:26:31 -07001344 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001345 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001346 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001347 std::chrono::seconds(15))) {
1348 /* We timed out to prep /data in time. Continue wait. */
1349 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001350 }
Wei Wang42e38102017-06-07 10:46:12 -07001351 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001352}
1353
Paul Lawrence74f29f12014-08-28 15:54:10 -07001354static void cryptfs_set_corrupt()
1355{
1356 // Mark the footer as bad
1357 struct crypt_mnt_ftr crypt_ftr;
1358 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1359 SLOGE("Failed to get crypto footer - panic");
1360 return;
1361 }
1362
1363 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1364 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1365 SLOGE("Failed to set crypto footer - panic");
1366 return;
1367 }
1368}
1369
1370static void cryptfs_trigger_restart_min_framework()
1371{
1372 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1373 SLOGE("Failed to mount tmpfs on data - panic");
1374 return;
1375 }
1376
1377 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1378 SLOGE("Failed to trigger post fs data - panic");
1379 return;
1380 }
1381
1382 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1383 SLOGE("Failed to trigger restart min framework - panic");
1384 return;
1385 }
1386}
1387
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001388/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001389static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001390{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001391 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001392 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001393 static int restart_successful = 0;
1394
1395 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001396 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001397 SLOGE("Encrypted filesystem not validated, aborting");
1398 return -1;
1399 }
1400
1401 if (restart_successful) {
1402 SLOGE("System already restarted with encrypted disk, aborting");
1403 return -1;
1404 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001405
Paul Lawrencef4faa572014-01-29 13:31:03 -08001406 if (restart_main) {
1407 /* Here is where we shut down the framework. The init scripts
1408 * start all services in one of three classes: core, main or late_start.
1409 * On boot, we start core and main. Now, we stop main, but not core,
1410 * as core includes vold and a few other really important things that
1411 * we need to keep running. Once main has stopped, we should be able
1412 * to umount the tmpfs /data, then mount the encrypted /data.
1413 * We then restart the class main, and also the class late_start.
1414 * At the moment, I've only put a few things in late_start that I know
1415 * are not needed to bring up the framework, and that also cause problems
1416 * with unmounting the tmpfs /data, but I hope to add add more services
1417 * to the late_start class as we optimize this to decrease the delay
1418 * till the user is asked for the password to the filesystem.
1419 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001420
Paul Lawrencef4faa572014-01-29 13:31:03 -08001421 /* The init files are setup to stop the class main when vold.decrypt is
1422 * set to trigger_reset_main.
1423 */
1424 property_set("vold.decrypt", "trigger_reset_main");
1425 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426
Paul Lawrencef4faa572014-01-29 13:31:03 -08001427 /* Ugh, shutting down the framework is not synchronous, so until it
1428 * can be fixed, this horrible hack will wait a moment for it all to
1429 * shut down before proceeding. Without it, some devices cannot
1430 * restart the graphics services.
1431 */
1432 sleep(2);
1433 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001434
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001435 /* Now that the framework is shutdown, we should be able to umount()
1436 * the tmpfs filesystem, and mount the real one.
1437 */
1438
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001439 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1440 if (strlen(crypto_blkdev) == 0) {
1441 SLOGE("fs_crypto_blkdev not set\n");
1442 return -1;
1443 }
1444
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001445 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001446 /* If ro.crypto.readonly is set to 1, mount the decrypted
1447 * filesystem readonly. This is used when /data is mounted by
1448 * recovery mode.
1449 */
1450 char ro_prop[PROPERTY_VALUE_MAX];
1451 property_get("ro.crypto.readonly", ro_prop, "");
1452 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1453 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1454 rec->flags |= MS_RDONLY;
1455 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001456
Ken Sumralle5032c42012-04-01 23:58:44 -07001457 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001458 int retries = RETRY_MOUNT_ATTEMPTS;
1459 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001460
1461 /*
1462 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1463 * partitions in the fsck domain.
1464 */
1465 if (setexeccon(secontextFsck())){
1466 SLOGE("Failed to setexeccon");
1467 return -1;
1468 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001469 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1470 crypto_blkdev, 0))
1471 != 0) {
1472 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1473 /* TODO: invoke something similar to
1474 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1475 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1476 SLOGI("Failed to mount %s because it is busy - waiting",
1477 crypto_blkdev);
1478 if (--retries) {
1479 sleep(RETRY_MOUNT_DELAY_SECONDS);
1480 } else {
1481 /* Let's hope that a reboot clears away whatever is keeping
1482 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001483 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001484 }
1485 } else {
1486 SLOGE("Failed to mount decrypted data");
1487 cryptfs_set_corrupt();
1488 cryptfs_trigger_restart_min_framework();
1489 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001490 if (setexeccon(NULL)) {
1491 SLOGE("Failed to setexeccon");
1492 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001493 return -1;
1494 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001495 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001496 if (setexeccon(NULL)) {
1497 SLOGE("Failed to setexeccon");
1498 return -1;
1499 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001500
Ken Sumralle5032c42012-04-01 23:58:44 -07001501 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001502 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001503 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001504
1505 /* startup service classes main and late_start */
1506 property_set("vold.decrypt", "trigger_restart_framework");
1507 SLOGD("Just triggered restart_framework\n");
1508
1509 /* Give it a few moments to get started */
1510 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001511 }
1512
Ken Sumrall0cc16632011-01-18 20:32:26 -08001513 if (rc == 0) {
1514 restart_successful = 1;
1515 }
1516
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001517 return rc;
1518}
1519
Paul Lawrencef4faa572014-01-29 13:31:03 -08001520int cryptfs_restart(void)
1521{
Paul Lawrence05335c32015-03-05 09:46:23 -08001522 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001523 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001524 SLOGE("cryptfs_restart not valid for file encryption:");
1525 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001526 }
1527
Paul Lawrencef4faa572014-01-29 13:31:03 -08001528 /* Call internal implementation forcing a restart of main service group */
1529 return cryptfs_restart_internal(1);
1530}
1531
Wei Wang4375f1b2017-02-24 17:43:01 -08001532static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001533{
1534 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001535 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001536 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001537
1538 property_get("ro.crypto.state", encrypted_state, "");
1539 if (strcmp(encrypted_state, "encrypted") ) {
1540 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001541 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001542 }
1543
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001544 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001545 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001546 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001547 }
1548
Ken Sumrall160b4d62013-04-22 12:15:39 -07001549 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001550 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001551
Ken Sumralle1a45852011-12-14 21:24:27 -08001552 /*
1553 * Only report this error if key_loc is a file and it exists.
1554 * If the device was never encrypted, and /data is not mountable for
1555 * some reason, returning 1 should prevent the UI from presenting the
1556 * a "enter password" screen, or worse, a "press button to wipe the
1557 * device" screen.
1558 */
1559 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1560 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001561 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001562 } else {
1563 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001564 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001565 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001566 }
1567
Paul Lawrence74f29f12014-08-28 15:54:10 -07001568 // Test for possible error flags
1569 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1570 SLOGE("Encryption process is partway completed\n");
1571 return CRYPTO_COMPLETE_PARTIAL;
1572 }
1573
1574 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1575 SLOGE("Encryption process was interrupted but cannot continue\n");
1576 return CRYPTO_COMPLETE_INCONSISTENT;
1577 }
1578
1579 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1580 SLOGE("Encryption is successful but data is corrupt\n");
1581 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001582 }
1583
1584 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001585 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001586}
1587
Paul Lawrencef4faa572014-01-29 13:31:03 -08001588static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001589 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001590{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001591 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001592 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001593 char crypto_blkdev[MAXPATHLEN];
1594 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001595 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596 unsigned int orig_failed_decrypt_count;
1597 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001598 int use_keymaster = 0;
1599 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001600 unsigned char* intermediate_key = 0;
1601 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001602 int N = 1 << crypt_ftr->N_factor;
1603 int r = 1 << crypt_ftr->r_factor;
1604 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001605
Paul Lawrencef4faa572014-01-29 13:31:03 -08001606 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1607 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001608
Paul Lawrencef4faa572014-01-29 13:31:03 -08001609 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001610 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1611 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001612 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001613 rc = -1;
1614 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001615 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001616 }
1617
Paul Lawrencef4faa572014-01-29 13:31:03 -08001618 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1619
Paul Lawrence74f29f12014-08-28 15:54:10 -07001620 // Create crypto block device - all (non fatal) code paths
1621 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001622 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1623 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001624 SLOGE("Error creating decrypted block device\n");
1625 rc = -1;
1626 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001627 }
1628
Paul Lawrence74f29f12014-08-28 15:54:10 -07001629 /* Work out if the problem is the password or the data */
1630 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1631 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001632
Paul Lawrence74f29f12014-08-28 15:54:10 -07001633 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1634 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1635 N, r, p, scrypted_intermediate_key,
1636 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001637
Paul Lawrence74f29f12014-08-28 15:54:10 -07001638 // Does the key match the crypto footer?
1639 if (rc == 0 && memcmp(scrypted_intermediate_key,
1640 crypt_ftr->scrypted_intermediate_key,
1641 sizeof(scrypted_intermediate_key)) == 0) {
1642 SLOGI("Password matches");
1643 rc = 0;
1644 } else {
1645 /* Try mounting the file system anyway, just in case the problem's with
1646 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001647 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1648 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001649 mkdir(tmp_mount_point, 0755);
1650 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1651 SLOGE("Error temp mounting decrypted block device\n");
1652 delete_crypto_blk_dev(label);
1653
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001654 rc = ++crypt_ftr->failed_decrypt_count;
1655 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001656 } else {
1657 /* Success! */
1658 SLOGI("Password did not match but decrypted drive mounted - continue");
1659 umount(tmp_mount_point);
1660 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001661 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001662 }
1663
1664 if (rc == 0) {
1665 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001666 if (orig_failed_decrypt_count != 0) {
1667 put_crypt_ftr_and_key(crypt_ftr);
1668 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001669
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001670 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001671 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001672 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001673
1674 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001675 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001676 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001677 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001678 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001679 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001680 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001681
Paul Lawrence74f29f12014-08-28 15:54:10 -07001682 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001683 use_keymaster = keymaster_check_compatibility();
1684 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001685 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001686 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1687 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1688 upgrade = 1;
1689 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001690 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001691 upgrade = 1;
1692 }
1693
1694 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001695 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1696 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001697 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001698 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001699 }
1700 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001701
1702 // Do not fail even if upgrade failed - machine is bootable
1703 // Note that if this code is ever hit, there is a *serious* problem
1704 // since KDFs should never fail. You *must* fix the kdf before
1705 // proceeding!
1706 if (rc) {
1707 SLOGW("Upgrade failed with error %d,"
1708 " but continuing with previous state",
1709 rc);
1710 rc = 0;
1711 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001712 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713 }
1714
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001715 errout:
1716 if (intermediate_key) {
1717 memset(intermediate_key, 0, intermediate_key_size);
1718 free(intermediate_key);
1719 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001720 return rc;
1721}
1722
Ken Sumrall29d8da82011-05-18 17:20:07 -07001723/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001724 * Called by vold when it's asked to mount an encrypted external
1725 * storage volume. The incoming partition has no crypto header/footer,
1726 * as any metadata is been stored in a separate, small partition.
1727 *
1728 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001729 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001730int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1731 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001732 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001733 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001734 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001735 return -1;
1736 }
1737
1738 unsigned long nr_sec = 0;
1739 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001740 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001741
Ken Sumrall29d8da82011-05-18 17:20:07 -07001742 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001743 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001744 return -1;
1745 }
1746
Jeff Sharkey9c484982015-03-31 10:35:33 -07001747 struct crypt_mnt_ftr ext_crypt_ftr;
1748 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1749 ext_crypt_ftr.fs_size = nr_sec;
1750 ext_crypt_ftr.keysize = keysize;
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001751 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
1752 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001753
Jeff Sharkey9c484982015-03-31 10:35:33 -07001754 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1755 out_crypto_blkdev, label);
1756}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001757
Jeff Sharkey9c484982015-03-31 10:35:33 -07001758/*
1759 * Called by vold when it's asked to unmount an encrypted external
1760 * storage volume.
1761 */
1762int cryptfs_revert_ext_volume(const char* label) {
1763 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001764}
1765
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001766int cryptfs_crypto_complete(void)
1767{
1768 return do_crypto_complete("/data");
1769}
1770
Paul Lawrencef4faa572014-01-29 13:31:03 -08001771int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1772{
1773 char encrypted_state[PROPERTY_VALUE_MAX];
1774 property_get("ro.crypto.state", encrypted_state, "");
1775 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1776 SLOGE("encrypted fs already validated or not running with encryption,"
1777 " aborting");
1778 return -1;
1779 }
1780
1781 if (get_crypt_ftr_and_key(crypt_ftr)) {
1782 SLOGE("Error getting crypt footer and key");
1783 return -1;
1784 }
1785
1786 return 0;
1787}
1788
Wei Wang4375f1b2017-02-24 17:43:01 -08001789int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001790{
Paul Lawrence05335c32015-03-05 09:46:23 -08001791 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001792 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001793 SLOGE("cryptfs_check_passwd not valid for file encryption");
1794 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001795 }
1796
Paul Lawrencef4faa572014-01-29 13:31:03 -08001797 struct crypt_mnt_ftr crypt_ftr;
1798 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001799
Paul Lawrencef4faa572014-01-29 13:31:03 -08001800 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001801 if (rc) {
1802 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001803 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001804 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001805
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001806 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001807 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1808 if (rc) {
1809 SLOGE("Password did not match");
1810 return rc;
1811 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001812
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001813 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1814 // Here we have a default actual password but a real password
1815 // we must test against the scrypted value
1816 // First, we must delete the crypto block device that
1817 // test_mount_encrypted_fs leaves behind as a side effect
1818 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1819 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1820 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1821 if (rc) {
1822 SLOGE("Default password did not match on reboot encryption");
1823 return rc;
1824 }
1825
1826 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1827 put_crypt_ftr_and_key(&crypt_ftr);
1828 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1829 if (rc) {
1830 SLOGE("Could not change password on reboot encryption");
1831 return rc;
1832 }
1833 }
1834
1835 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001836 cryptfs_clear_password();
1837 password = strdup(passwd);
1838 struct timespec now;
1839 clock_gettime(CLOCK_BOOTTIME, &now);
1840 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001841 }
1842
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001843 return rc;
1844}
1845
Ken Sumrall3ad90722011-10-04 20:38:29 -07001846int cryptfs_verify_passwd(char *passwd)
1847{
1848 struct crypt_mnt_ftr crypt_ftr;
1849 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001850 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001851 char encrypted_state[PROPERTY_VALUE_MAX];
1852 int rc;
1853
1854 property_get("ro.crypto.state", encrypted_state, "");
1855 if (strcmp(encrypted_state, "encrypted") ) {
1856 SLOGE("device not encrypted, aborting");
1857 return -2;
1858 }
1859
1860 if (!master_key_saved) {
1861 SLOGE("encrypted fs not yet mounted, aborting");
1862 return -1;
1863 }
1864
1865 if (!saved_mount_point) {
1866 SLOGE("encrypted fs failed to save mount point, aborting");
1867 return -1;
1868 }
1869
Ken Sumrall160b4d62013-04-22 12:15:39 -07001870 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001871 SLOGE("Error getting crypt footer and key\n");
1872 return -1;
1873 }
1874
1875 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1876 /* If the device has no password, then just say the password is valid */
1877 rc = 0;
1878 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001879 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001880 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1881 /* They match, the password is correct */
1882 rc = 0;
1883 } else {
1884 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1885 sleep(1);
1886 rc = 1;
1887 }
1888 }
1889
1890 return rc;
1891}
1892
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001893/* Initialize a crypt_mnt_ftr structure. The keysize is
1894 * defaulted to 16 bytes, and the filesystem size to 0.
1895 * Presumably, at a minimum, the caller will update the
1896 * filesystem size and crypto_type_name after calling this function.
1897 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001898static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001899{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001900 off64_t off;
1901
1902 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001904 ftr->major_version = CURRENT_MAJOR_VERSION;
1905 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001906 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001907 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001908
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001909 switch (keymaster_check_compatibility()) {
1910 case 1:
1911 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1912 break;
1913
1914 case 0:
1915 ftr->kdf_type = KDF_SCRYPT;
1916 break;
1917
1918 default:
1919 SLOGE("keymaster_check_compatibility failed");
1920 return -1;
1921 }
1922
Kenny Rootc4c70f12013-06-14 12:11:38 -07001923 get_device_scrypt_params(ftr);
1924
Ken Sumrall160b4d62013-04-22 12:15:39 -07001925 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1926 if (get_crypt_ftr_info(NULL, &off) == 0) {
1927 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1928 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1929 ftr->persist_data_size;
1930 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001931
1932 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001933}
1934
Ken Sumrall29d8da82011-05-18 17:20:07 -07001935static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001936{
Ken Sumralle550f782013-08-20 13:48:23 -07001937 const char *args[10];
1938 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1939 int num_args;
1940 int status;
1941 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001942 int rc = -1;
1943
Ken Sumrall29d8da82011-05-18 17:20:07 -07001944 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001945#ifdef TARGET_USES_MKE2FS
1946 args[0] = "/system/bin/mke2fs";
1947 args[1] = "-M";
1948 args[2] = "/data";
1949 args[3] = "-b";
1950 args[4] = "4096";
1951 args[5] = "-t";
1952 args[6] = "ext4";
1953 args[7] = crypto_blkdev;
1954 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1955 args[8] = size_str;
1956 num_args = 9;
1957#else
Ken Sumralle550f782013-08-20 13:48:23 -07001958 args[0] = "/system/bin/make_ext4fs";
1959 args[1] = "-a";
1960 args[2] = "/data";
1961 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07001962 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07001963 args[4] = size_str;
1964 args[5] = crypto_blkdev;
1965 num_args = 6;
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001966#endif
Ken Sumralle550f782013-08-20 13:48:23 -07001967 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1968 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001969 } else if (type == F2FS_FS) {
Jaegeuk Kim98651a22017-06-05 10:22:04 -07001970 args[0] = "/system/bin/make_f2fs";
Jaegeuk Kim8de9f062017-11-01 10:35:30 -07001971 args[1] = "-f";
JP Abgrall62c7af32014-06-16 13:01:23 -07001972 args[2] = "-d1";
Jaegeuk Kim8de9f062017-11-01 10:35:30 -07001973 args[3] = "-O";
1974 args[4] = "encrypt";
1975 args[5] = "-O";
1976 args[6] = "quota";
1977 args[7] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001978 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
Jaegeuk Kim8de9f062017-11-01 10:35:30 -07001979 args[8] = size_str;
1980 num_args = 9;
1981 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s\n",
1982 args[0], args[1], args[2], args[3], args[4], args[5],
1983 args[6], args[7], args[8]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001984 } else {
1985 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1986 return -1;
1987 }
1988
Ken Sumralle550f782013-08-20 13:48:23 -07001989 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1990
1991 if (tmp != 0) {
1992 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001993 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001994 if (WIFEXITED(status)) {
1995 if (WEXITSTATUS(status)) {
1996 SLOGE("Error creating filesystem on %s, exit status %d ",
1997 crypto_blkdev, WEXITSTATUS(status));
1998 } else {
1999 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2000 rc = 0;
2001 }
2002 } else {
2003 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2004 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002005 }
2006
2007 return rc;
2008}
2009
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002010#define CRYPTO_ENABLE_WIPE 1
2011#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002012
2013#define FRAMEWORK_BOOT_WAIT 60
2014
Paul Lawrence87999172014-02-20 12:21:31 -08002015static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2016{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002017 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002018 if (fd == -1) {
2019 SLOGE("Error opening file %s", filename);
2020 return -1;
2021 }
2022
2023 char block[CRYPT_INPLACE_BUFSIZE];
2024 memset(block, 0, sizeof(block));
2025 if (unix_read(fd, block, sizeof(block)) < 0) {
2026 SLOGE("Error reading file %s", filename);
2027 close(fd);
2028 return -1;
2029 }
2030
2031 close(fd);
2032
2033 SHA256_CTX c;
2034 SHA256_Init(&c);
2035 SHA256_Update(&c, block, sizeof(block));
2036 SHA256_Final(buf, &c);
2037
2038 return 0;
2039}
2040
JP Abgrall62c7af32014-06-16 13:01:23 -07002041static int get_fs_type(struct fstab_rec *rec)
2042{
2043 if (!strcmp(rec->fs_type, "ext4")) {
2044 return EXT4_FS;
2045 } else if (!strcmp(rec->fs_type, "f2fs")) {
2046 return F2FS_FS;
2047 } else {
2048 return -1;
2049 }
2050}
2051
Paul Lawrence87999172014-02-20 12:21:31 -08002052static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2053 char *crypto_blkdev, char *real_blkdev,
2054 int previously_encrypted_upto)
2055{
2056 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002057 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002058
Paul Lawrence87999172014-02-20 12:21:31 -08002059 /* The size of the userdata partition, and add in the vold volumes below */
2060 tot_encryption_size = crypt_ftr->fs_size;
2061
2062 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002063 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2064 int fs_type = get_fs_type(rec);
2065 if (fs_type < 0) {
2066 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2067 return -1;
2068 }
2069 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002070 } else if (how == CRYPTO_ENABLE_INPLACE) {
2071 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2072 crypt_ftr->fs_size, &cur_encryption_done,
2073 tot_encryption_size,
2074 previously_encrypted_upto);
2075
JP Abgrall7fc1de82014-10-10 18:43:41 -07002076 if (rc == ENABLE_INPLACE_ERR_DEV) {
2077 /* Hack for b/17898962 */
2078 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
Josh Gaofec44372017-08-28 13:22:55 -07002079 cryptfs_reboot(RebootType::reboot);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002080 }
2081
Paul Lawrence73d7a022014-06-09 14:10:09 -07002082 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002083 crypt_ftr->encrypted_upto = cur_encryption_done;
2084 }
2085
Paul Lawrence73d7a022014-06-09 14:10:09 -07002086 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002087 /* The inplace routine never actually sets the progress to 100% due
2088 * to the round down nature of integer division, so set it here */
2089 property_set("vold.encrypt_progress", "100");
2090 }
2091 } else {
2092 /* Shouldn't happen */
2093 SLOGE("cryptfs_enable: internal error, unknown option\n");
2094 rc = -1;
2095 }
2096
2097 return rc;
2098}
2099
Wei Wang4375f1b2017-02-24 17:43:01 -08002100int cryptfs_enable_internal(char *howarg, int crypt_type, const char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002101 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002102{
2103 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002104 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002105 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002106 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002107 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002108 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002109 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002110 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002111 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002112 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002113 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002114 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002115 bool onlyCreateHeader = false;
2116 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002117
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002118 if (!strcmp(howarg, "wipe")) {
2119 how = CRYPTO_ENABLE_WIPE;
2120 } else if (! strcmp(howarg, "inplace")) {
2121 how = CRYPTO_ENABLE_INPLACE;
2122 } else {
2123 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002124 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002125 }
2126
Paul Lawrence87999172014-02-20 12:21:31 -08002127 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002128 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2129 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2130 /* An encryption was underway and was interrupted */
2131 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2132 crypt_ftr.encrypted_upto = 0;
2133 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002134
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002135 /* At this point, we are in an inconsistent state. Until we successfully
2136 complete encryption, a reboot will leave us broken. So mark the
2137 encryption failed in case that happens.
2138 On successfully completing encryption, remove this flag */
2139 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002140
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002141 put_crypt_ftr_and_key(&crypt_ftr);
2142 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2143 if (!check_ftr_sha(&crypt_ftr)) {
2144 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2145 put_crypt_ftr_and_key(&crypt_ftr);
2146 goto error_unencrypted;
2147 }
2148
2149 /* Doing a reboot-encryption*/
2150 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2151 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2152 rebootEncryption = true;
2153 }
Paul Lawrence87999172014-02-20 12:21:31 -08002154 }
2155
2156 property_get("ro.crypto.state", encrypted_state, "");
2157 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2158 SLOGE("Device is already running encrypted, aborting");
2159 goto error_unencrypted;
2160 }
2161
2162 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2163 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002164 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002165
Ken Sumrall3ed82362011-01-28 23:31:16 -08002166 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002167 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002168 if (fd == -1) {
2169 SLOGE("Cannot open block device %s\n", real_blkdev);
2170 goto error_unencrypted;
2171 }
2172 unsigned long nr_sec;
2173 get_blkdev_size(fd, &nr_sec);
2174 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002175 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2176 goto error_unencrypted;
2177 }
2178 close(fd);
2179
2180 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002181 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002182 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002183 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002184 if (fs_size_sec == 0)
2185 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2186
Paul Lawrence87999172014-02-20 12:21:31 -08002187 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002188
2189 if (fs_size_sec > max_fs_size_sec) {
2190 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2191 goto error_unencrypted;
2192 }
2193 }
2194
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002195 /* Get a wakelock as this may take a while, and we don't want the
2196 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2197 * wants to keep the screen on, it can grab a full wakelock.
2198 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002199 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002200 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2201
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002202 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002203 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002204 */
2205 property_set("vold.decrypt", "trigger_shutdown_framework");
2206 SLOGD("Just asked init to shut down class main\n");
2207
Jeff Sharkey9c484982015-03-31 10:35:33 -07002208 /* Ask vold to unmount all devices that it manages */
2209 if (vold_unmountAll()) {
2210 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002211 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002212
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002213 /* no_ui means we are being called from init, not settings.
2214 Now we always reboot from settings, so !no_ui means reboot
2215 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002216 if (!no_ui) {
2217 /* Try fallback, which is to reboot and try there */
2218 onlyCreateHeader = true;
2219 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2220 if (breadcrumb == 0) {
2221 SLOGE("Failed to create breadcrumb file");
2222 goto error_shutting_down;
2223 }
2224 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002225 }
2226
2227 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002228 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002229 /* Now that /data is unmounted, we need to mount a tmpfs
2230 * /data, set a property saying we're doing inplace encryption,
2231 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002232 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002233 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002234 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002235 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002236 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002237 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002238
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002239 /* restart the framework. */
2240 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002241 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002242
Ken Sumrall92736ef2012-10-17 20:57:14 -07002243 /* Ugh, shutting down the framework is not synchronous, so until it
2244 * can be fixed, this horrible hack will wait a moment for it all to
2245 * shut down before proceeding. Without it, some devices cannot
2246 * restart the graphics services.
2247 */
2248 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002249 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002250
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002251 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002252 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002253 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002254 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2255 goto error_shutting_down;
2256 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002257
Paul Lawrence87999172014-02-20 12:21:31 -08002258 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2259 crypt_ftr.fs_size = nr_sec
2260 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2261 } else {
2262 crypt_ftr.fs_size = nr_sec;
2263 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002264 /* At this point, we are in an inconsistent state. Until we successfully
2265 complete encryption, a reboot will leave us broken. So mark the
2266 encryption failed in case that happens.
2267 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002268 if (onlyCreateHeader) {
2269 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2270 } else {
2271 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2272 }
Paul Lawrence87999172014-02-20 12:21:31 -08002273 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002274 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002275
Paul Lawrence87999172014-02-20 12:21:31 -08002276 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002277 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2278 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002279 SLOGE("Cannot create encrypted master key\n");
2280 goto error_shutting_down;
2281 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002282
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002283 /* Replace scrypted intermediate key if we are preparing for a reboot */
2284 if (onlyCreateHeader) {
2285 unsigned char fake_master_key[KEY_LEN_BYTES];
2286 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2287 memset(fake_master_key, 0, sizeof(fake_master_key));
2288 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2289 encrypted_fake_master_key, &crypt_ftr);
2290 }
2291
Paul Lawrence87999172014-02-20 12:21:31 -08002292 /* Write the key to the end of the partition */
2293 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002294
Paul Lawrence87999172014-02-20 12:21:31 -08002295 /* If any persistent data has been remembered, save it.
2296 * If none, create a valid empty table and save that.
2297 */
2298 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002299 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002300 if (pdata) {
2301 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2302 persist_data = pdata;
2303 }
2304 }
2305 if (persist_data) {
2306 save_persistent_data();
2307 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002308 }
2309
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002310 if (onlyCreateHeader) {
2311 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002312 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002313 }
2314
2315 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002316 /* startup service classes main and late_start */
2317 property_set("vold.decrypt", "trigger_restart_min_framework");
2318 SLOGD("Just triggered restart_min_framework\n");
2319
2320 /* OK, the framework is restarted and will soon be showing a
2321 * progress bar. Time to setup an encrypted mapping, and
2322 * either write a new filesystem, or encrypt in place updating
2323 * the progress bar as we work.
2324 */
2325 }
2326
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002327 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002328 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002329 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002330
Paul Lawrence87999172014-02-20 12:21:31 -08002331 /* If we are continuing, check checksums match */
2332 rc = 0;
2333 if (previously_encrypted_upto) {
2334 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2335 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002336
Paul Lawrence87999172014-02-20 12:21:31 -08002337 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2338 sizeof(hash_first_block)) != 0) {
2339 SLOGE("Checksums do not match - trigger wipe");
2340 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002341 }
2342 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002343
Paul Lawrence87999172014-02-20 12:21:31 -08002344 if (!rc) {
2345 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2346 crypto_blkdev, real_blkdev,
2347 previously_encrypted_upto);
2348 }
2349
2350 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002351 if (!rc && how == CRYPTO_ENABLE_INPLACE
2352 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002353 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2354 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002355 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002356 SLOGE("Error calculating checksum for continuing encryption");
2357 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002358 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002359 }
2360
2361 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002362 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002363
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002364 if (! rc) {
2365 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002366 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002367
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002368 if (how == CRYPTO_ENABLE_INPLACE
2369 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002370 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2371 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002372 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002373 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002374
Paul Lawrence6bfed202014-07-28 12:47:22 -07002375 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002376
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002377 if (how == CRYPTO_ENABLE_WIPE
2378 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002379 char value[PROPERTY_VALUE_MAX];
2380 property_get("ro.crypto.state", value, "");
2381 if (!strcmp(value, "")) {
2382 /* default encryption - continue first boot sequence */
2383 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08002384 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002385 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002386 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2387 // Bring up cryptkeeper that will check the password and set it
2388 property_set("vold.decrypt", "trigger_shutdown_framework");
2389 sleep(2);
2390 property_set("vold.encrypt_progress", "");
2391 cryptfs_trigger_restart_min_framework();
2392 } else {
2393 cryptfs_check_passwd(DEFAULT_PASSWORD);
2394 cryptfs_restart_internal(1);
2395 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002396 return 0;
2397 } else {
2398 sleep(2); /* Give the UI a chance to show 100% progress */
Josh Gaofec44372017-08-28 13:22:55 -07002399 cryptfs_reboot(RebootType::reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002400 }
Paul Lawrence87999172014-02-20 12:21:31 -08002401 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002402 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002403 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002404 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002405 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002406 char value[PROPERTY_VALUE_MAX];
2407
Ken Sumrall319369a2012-06-27 16:30:18 -07002408 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002409 if (!strcmp(value, "1")) {
2410 /* wipe data if encryption failed */
2411 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002412 std::string err;
2413 const std::vector<std::string> options = {
2414 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2415 };
2416 if (!write_bootloader_message(options, &err)) {
2417 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002418 }
Josh Gaofec44372017-08-28 13:22:55 -07002419 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002420 } else {
2421 /* set property to trigger dialog */
2422 property_set("vold.encrypt_progress", "error_partially_encrypted");
2423 release_wake_lock(lockid);
2424 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002425 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002426 }
2427
Ken Sumrall3ed82362011-01-28 23:31:16 -08002428 /* hrm, the encrypt step claims success, but the reboot failed.
2429 * This should not happen.
2430 * Set the property and return. Hope the framework can deal with it.
2431 */
2432 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002433 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002434 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002435
2436error_unencrypted:
2437 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002438 if (lockid[0]) {
2439 release_wake_lock(lockid);
2440 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002441 return -1;
2442
2443error_shutting_down:
2444 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2445 * but the framework is stopped and not restarted to show the error, so it's up to
2446 * vold to restart the system.
2447 */
2448 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002449 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002450
2451 /* shouldn't get here */
2452 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002453 if (lockid[0]) {
2454 release_wake_lock(lockid);
2455 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002456 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002457}
2458
Paul Lawrence569649f2015-09-09 12:13:00 -07002459int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002460{
Paul Lawrence569649f2015-09-09 12:13:00 -07002461 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002462}
2463
Paul Lawrence569649f2015-09-09 12:13:00 -07002464int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002465{
2466 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07002467 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002468}
2469
2470int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002471{
Paul Crowley38132a12016-02-09 09:50:32 +00002472 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002473 SLOGE("cryptfs_changepw not valid for file encryption");
2474 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002475 }
2476
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002477 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002478 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002479
2480 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002481 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002482 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002483 return -1;
2484 }
2485
Paul Lawrencef4faa572014-01-29 13:31:03 -08002486 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2487 SLOGE("Invalid crypt_type %d", crypt_type);
2488 return -1;
2489 }
2490
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002491 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002492 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002493 SLOGE("Error getting crypt footer and key");
2494 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002495 }
2496
Paul Lawrencef4faa572014-01-29 13:31:03 -08002497 crypt_ftr.crypt_type = crypt_type;
2498
JP Abgrall933216c2015-02-11 13:44:32 -08002499 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002500 : newpw,
2501 crypt_ftr.salt,
2502 saved_master_key,
2503 crypt_ftr.master_key,
2504 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002505 if (rc) {
2506 SLOGE("Encrypt master key failed: %d", rc);
2507 return -1;
2508 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002509 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002510 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002511
2512 return 0;
2513}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002514
Rubin Xu85c01f92014-10-13 12:49:54 +01002515static unsigned int persist_get_max_entries(int encrypted) {
2516 struct crypt_mnt_ftr crypt_ftr;
2517 unsigned int dsize;
2518 unsigned int max_persistent_entries;
2519
2520 /* If encrypted, use the values from the crypt_ftr, otherwise
2521 * use the values for the current spec.
2522 */
2523 if (encrypted) {
2524 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2525 return -1;
2526 }
2527 dsize = crypt_ftr.persist_data_size;
2528 } else {
2529 dsize = CRYPT_PERSIST_DATA_SIZE;
2530 }
2531
2532 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2533 sizeof(struct crypt_persist_entry);
2534
2535 return max_persistent_entries;
2536}
2537
2538static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002539{
2540 unsigned int i;
2541
2542 if (persist_data == NULL) {
2543 return -1;
2544 }
2545 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2546 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2547 /* We found it! */
2548 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2549 return 0;
2550 }
2551 }
2552
2553 return -1;
2554}
2555
Rubin Xu85c01f92014-10-13 12:49:54 +01002556static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002557{
2558 unsigned int i;
2559 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002560 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002561
2562 if (persist_data == NULL) {
2563 return -1;
2564 }
2565
Rubin Xu85c01f92014-10-13 12:49:54 +01002566 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002567
2568 num = persist_data->persist_valid_entries;
2569
2570 for (i = 0; i < num; i++) {
2571 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2572 /* We found an existing entry, update it! */
2573 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2574 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2575 return 0;
2576 }
2577 }
2578
2579 /* We didn't find it, add it to the end, if there is room */
2580 if (persist_data->persist_valid_entries < max_persistent_entries) {
2581 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2582 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2583 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2584 persist_data->persist_valid_entries++;
2585 return 0;
2586 }
2587
2588 return -1;
2589}
2590
Rubin Xu85c01f92014-10-13 12:49:54 +01002591/**
2592 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2593 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2594 */
2595static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002596 unsigned int field_len;
2597 unsigned int key_index;
2598 field_len = strlen(field);
2599
2600 if (index == 0) {
2601 // The first key in a multi-entry field is just the filedname itself.
2602 if (!strcmp(key, field)) {
2603 return 1;
2604 }
2605 }
2606 // Match key against "%s_%d" % (field, index)
2607 if (strlen(key) < field_len + 1 + 1) {
2608 // Need at least a '_' and a digit.
2609 return 0;
2610 }
2611 if (strncmp(key, field, field_len)) {
2612 // If the key does not begin with field, it's not a match.
2613 return 0;
2614 }
2615 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
2616 return 0;
2617 }
2618 return key_index >= index;
2619}
2620
2621/*
2622 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2623 * remaining entries starting from index will be deleted.
2624 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2625 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2626 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2627 *
2628 */
2629static int persist_del_keys(const char *fieldname, unsigned index)
2630{
2631 unsigned int i;
2632 unsigned int j;
2633 unsigned int num;
2634
2635 if (persist_data == NULL) {
2636 return PERSIST_DEL_KEY_ERROR_OTHER;
2637 }
2638
2639 num = persist_data->persist_valid_entries;
2640
2641 j = 0; // points to the end of non-deleted entries.
2642 // Filter out to-be-deleted entries in place.
2643 for (i = 0; i < num; i++) {
2644 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2645 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2646 j++;
2647 }
2648 }
2649
2650 if (j < num) {
2651 persist_data->persist_valid_entries = j;
2652 // Zeroise the remaining entries
2653 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2654 return PERSIST_DEL_KEY_OK;
2655 } else {
2656 // Did not find an entry matching the given fieldname
2657 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2658 }
2659}
2660
2661static int persist_count_keys(const char *fieldname)
2662{
2663 unsigned int i;
2664 unsigned int count;
2665
2666 if (persist_data == NULL) {
2667 return -1;
2668 }
2669
2670 count = 0;
2671 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2672 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2673 count++;
2674 }
2675 }
2676
2677 return count;
2678}
2679
Ken Sumrall160b4d62013-04-22 12:15:39 -07002680/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002681int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002682{
Paul Crowley38132a12016-02-09 09:50:32 +00002683 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002684 SLOGE("Cannot get field when file encrypted");
2685 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002686 }
2687
Ken Sumrall160b4d62013-04-22 12:15:39 -07002688 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002689 /* CRYPTO_GETFIELD_OK is success,
2690 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2691 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2692 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002693 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002694 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2695 int i;
2696 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002697
2698 if (persist_data == NULL) {
2699 load_persistent_data();
2700 if (persist_data == NULL) {
2701 SLOGE("Getfield error, cannot load persistent data");
2702 goto out;
2703 }
2704 }
2705
Rubin Xu85c01f92014-10-13 12:49:54 +01002706 // Read value from persistent entries. If the original value is split into multiple entries,
2707 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002708 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002709 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2710 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2711 // value too small
2712 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2713 goto out;
2714 }
2715 rc = CRYPTO_GETFIELD_OK;
2716
2717 for (i = 1; /* break explicitly */; i++) {
2718 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2719 (int) sizeof(temp_field)) {
2720 // If the fieldname is very long, we stop as soon as it begins to overflow the
2721 // maximum field length. At this point we have in fact fully read out the original
2722 // value because cryptfs_setfield would not allow fields with longer names to be
2723 // written in the first place.
2724 break;
2725 }
2726 if (!persist_get_key(temp_field, temp_value)) {
2727 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2728 // value too small.
2729 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2730 goto out;
2731 }
2732 } else {
2733 // Exhaust all entries.
2734 break;
2735 }
2736 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002737 } else {
2738 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002739 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002740 }
2741
2742out:
2743 return rc;
2744}
2745
2746/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002747int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002748{
Paul Crowley38132a12016-02-09 09:50:32 +00002749 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002750 SLOGE("Cannot set field when file encrypted");
2751 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002752 }
2753
Ken Sumrall160b4d62013-04-22 12:15:39 -07002754 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002755 /* 0 is success, negative values are error */
2756 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002757 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002758 unsigned int field_id;
2759 char temp_field[PROPERTY_KEY_MAX];
2760 unsigned int num_entries;
2761 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002762
2763 if (persist_data == NULL) {
2764 load_persistent_data();
2765 if (persist_data == NULL) {
2766 SLOGE("Setfield error, cannot load persistent data");
2767 goto out;
2768 }
2769 }
2770
2771 property_get("ro.crypto.state", encrypted_state, "");
2772 if (!strcmp(encrypted_state, "encrypted") ) {
2773 encrypted = 1;
2774 }
2775
Rubin Xu85c01f92014-10-13 12:49:54 +01002776 // Compute the number of entries required to store value, each entry can store up to
2777 // (PROPERTY_VALUE_MAX - 1) chars
2778 if (strlen(value) == 0) {
2779 // Empty value also needs one entry to store.
2780 num_entries = 1;
2781 } else {
2782 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2783 }
2784
2785 max_keylen = strlen(fieldname);
2786 if (num_entries > 1) {
2787 // Need an extra "_%d" suffix.
2788 max_keylen += 1 + log10(num_entries);
2789 }
2790 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2791 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002792 goto out;
2793 }
2794
Rubin Xu85c01f92014-10-13 12:49:54 +01002795 // Make sure we have enough space to write the new value
2796 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2797 persist_get_max_entries(encrypted)) {
2798 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2799 goto out;
2800 }
2801
2802 // Now that we know persist_data has enough space for value, let's delete the old field first
2803 // to make up space.
2804 persist_del_keys(fieldname, 0);
2805
2806 if (persist_set_key(fieldname, value, encrypted)) {
2807 // fail to set key, should not happen as we have already checked the available space
2808 SLOGE("persist_set_key() error during setfield()");
2809 goto out;
2810 }
2811
2812 for (field_id = 1; field_id < num_entries; field_id++) {
2813 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
2814
2815 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2816 // fail to set key, should not happen as we have already checked the available space.
2817 SLOGE("persist_set_key() error during setfield()");
2818 goto out;
2819 }
2820 }
2821
Ken Sumrall160b4d62013-04-22 12:15:39 -07002822 /* If we are running encrypted, save the persistent data now */
2823 if (encrypted) {
2824 if (save_persistent_data()) {
2825 SLOGE("Setfield error, cannot save persistent data");
2826 goto out;
2827 }
2828 }
2829
Rubin Xu85c01f92014-10-13 12:49:54 +01002830 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002831
2832out:
2833 return rc;
2834}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002835
2836/* Checks userdata. Attempt to mount the volume if default-
2837 * encrypted.
2838 * On success trigger next init phase and return 0.
2839 * Currently do not handle failure - see TODO below.
2840 */
2841int cryptfs_mount_default_encrypted(void)
2842{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002843 int crypt_type = cryptfs_get_password_type();
2844 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2845 SLOGE("Bad crypt type - error");
2846 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2847 SLOGD("Password is not default - "
2848 "starting min framework to prompt");
2849 property_set("vold.decrypt", "trigger_restart_min_framework");
2850 return 0;
2851 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2852 SLOGD("Password is default - restarting filesystem");
2853 cryptfs_restart_internal(0);
2854 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002855 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002856 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002857 }
2858
Paul Lawrence6bfed202014-07-28 12:47:22 -07002859 /** Corrupt. Allow us to boot into framework, which will detect bad
2860 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002861 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002862 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002863 return 0;
2864}
2865
2866/* Returns type of the password, default, pattern, pin or password.
2867 */
2868int cryptfs_get_password_type(void)
2869{
Paul Crowley38132a12016-02-09 09:50:32 +00002870 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002871 SLOGE("cryptfs_get_password_type not valid for file encryption");
2872 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002873 }
2874
Paul Lawrencef4faa572014-01-29 13:31:03 -08002875 struct crypt_mnt_ftr crypt_ftr;
2876
2877 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2878 SLOGE("Error getting crypt footer and key\n");
2879 return -1;
2880 }
2881
Paul Lawrence6bfed202014-07-28 12:47:22 -07002882 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2883 return -1;
2884 }
2885
Paul Lawrencef4faa572014-01-29 13:31:03 -08002886 return crypt_ftr.crypt_type;
2887}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002888
Paul Lawrence05335c32015-03-05 09:46:23 -08002889const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002890{
Paul Crowley38132a12016-02-09 09:50:32 +00002891 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002892 SLOGE("cryptfs_get_password not valid for file encryption");
2893 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002894 }
2895
Paul Lawrence399317e2014-03-10 13:20:50 -07002896 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002897 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002898 if (now.tv_sec < password_expiry_time) {
2899 return password;
2900 } else {
2901 cryptfs_clear_password();
2902 return 0;
2903 }
2904}
2905
2906void cryptfs_clear_password()
2907{
2908 if (password) {
2909 size_t len = strlen(password);
2910 memset(password, 0, len);
2911 free(password);
2912 password = 0;
2913 password_expiry_time = 0;
2914 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002915}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002916
Paul Lawrence0c247462015-10-29 10:30:57 -07002917int cryptfs_isConvertibleToFBE()
2918{
2919 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2920 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2921}
2922
Paul Lawrence731a7a22015-04-28 22:14:15 +00002923int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
2924{
2925 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
2926 SLOGE("Failed to initialize crypt_ftr");
2927 return -1;
2928 }
2929
2930 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
2931 crypt_ftr->salt, crypt_ftr)) {
2932 SLOGE("Cannot create encrypted master key\n");
2933 return -1;
2934 }
2935
2936 //crypt_ftr->keysize = key_length / 8;
2937 return 0;
2938}
2939
2940int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
2941 unsigned char* master_key)
2942{
2943 int rc;
2944
Paul Lawrence731a7a22015-04-28 22:14:15 +00002945 unsigned char* intermediate_key = 0;
2946 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002947
2948 if (password == 0 || *password == 0) {
2949 password = DEFAULT_PASSWORD;
2950 }
2951
Paul Lawrence731a7a22015-04-28 22:14:15 +00002952 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
2953 &intermediate_key_size);
2954
Paul Lawrence300dae72016-03-11 11:02:52 -08002955 if (rc) {
2956 SLOGE("Can't calculate intermediate key");
2957 return rc;
2958 }
2959
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002960 int N = 1 << ftr->N_factor;
2961 int r = 1 << ftr->r_factor;
2962 int p = 1 << ftr->p_factor;
2963
2964 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
2965
2966 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
2967 ftr->salt, sizeof(ftr->salt), N, r, p,
2968 scrypted_intermediate_key,
2969 sizeof(scrypted_intermediate_key));
2970
2971 free(intermediate_key);
2972
2973 if (rc) {
Paul Lawrence300dae72016-03-11 11:02:52 -08002974 SLOGE("Can't scrypt intermediate key");
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002975 return rc;
2976 }
2977
2978 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
2979 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00002980}
2981
2982int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
2983 const unsigned char* master_key)
2984{
2985 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
2986 ftr);
2987}
Paul Lawrence6e410592016-05-24 14:20:38 -07002988
Eric Biggersb45caaf2017-02-02 14:52:12 -08002989void cryptfs_get_file_encryption_modes(const char **contents_mode_ret,
2990 const char **filenames_mode_ret)
Paul Lawrence6e410592016-05-24 14:20:38 -07002991{
2992 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
Eric Biggersb45caaf2017-02-02 14:52:12 -08002993 fs_mgr_get_file_encryption_modes(rec, contents_mode_ret, filenames_mode_ret);
Paul Lawrence6e410592016-05-24 14:20:38 -07002994}