blob: 465fd602dbf55e1130a9e6f1e7f073679f8ef488 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Paul Crowley3b71fc52017-10-09 10:55:21 -070041#include <ext4_utils/ext4_crypt.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070042#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070058#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000059#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000060#include "f2fs_sparseblock.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070061#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080062#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000063#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080064#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070065#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080066extern "C" {
67#include <crypto_scrypt.h>
68}
Mark Salyzyn3e971272014-01-21 13:27:04 -080069
Mark Salyzyn5eecc442014-02-12 14:16:14 -080070#define UNUSED __attribute__((unused))
71
Ken Sumrall8f869aa2010-12-03 03:47:09 -080072#define DM_CRYPT_BUF_SIZE 4096
73
Jason parks70a4b3f2011-01-28 10:10:47 -060074#define HASH_COUNT 2000
Greg Kaiserfa099612018-02-14 11:26:00 -080075#define KEY_LEN_BYTES 16
Jason parks70a4b3f2011-01-28 10:10:47 -060076#define IV_LEN_BYTES 16
77
Ken Sumrall29d8da82011-05-18 17:20:07 -070078#define KEY_IN_FOOTER "footer"
79
Paul Lawrence3bd36d52015-06-09 13:37:44 -070080#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080081
Paul Lawrence3d99eba2015-11-20 07:07:19 -080082#define CRYPTO_BLOCK_DEVICE "userdata"
83
84#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
85
Ken Sumrall29d8da82011-05-18 17:20:07 -070086#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070087#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070088
Ken Sumralle919efe2012-09-29 17:07:41 -070089#define TABLE_LOAD_RETRIES 10
90
Shawn Willden47ba10d2014-09-03 17:07:06 -060091#define RSA_KEY_SIZE 2048
92#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
93#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060094#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070095
Paul Lawrence8e3f4512014-09-08 10:11:17 -070096#define RETRY_MOUNT_ATTEMPTS 10
97#define RETRY_MOUNT_DELAY_SECONDS 1
98
Paul Crowley5afbc622017-11-27 09:42:17 -080099#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
100
Paul Crowley73473332017-11-21 15:43:51 -0800101static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
102
Greg Kaiserfa099612018-02-14 11:26:00 -0800103static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700104static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600105static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700106static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800107
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700108/* Should we use keymaster? */
109static int keymaster_check_compatibility()
110{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000111 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700112}
113
114/* Create a new keymaster key and store it in this footer */
115static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
116{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800117 if (ftr->keymaster_blob_size) {
118 SLOGI("Already have key");
119 return 0;
120 }
121
Janis Danisevskis015ec302017-01-31 11:31:08 +0000122 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
123 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
124 &ftr->keymaster_blob_size);
125 if (rc) {
126 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800127 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000128 ftr->keymaster_blob_size = 0;
129 }
130 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700131 return -1;
132 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000133 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700134}
135
Shawn Willdene17a9c42014-09-08 13:04:08 -0600136/* This signs the given object using the keymaster key. */
137static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600138 const unsigned char *object,
139 const size_t object_size,
140 unsigned char **signature,
141 size_t *signature_size)
142{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600143 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600144 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600145 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600146
Shawn Willdene17a9c42014-09-08 13:04:08 -0600147 // To sign a message with RSA, the message must satisfy two
148 // constraints:
149 //
150 // 1. The message, when interpreted as a big-endian numeric value, must
151 // be strictly less than the public modulus of the RSA key. Note
152 // that because the most significant bit of the public modulus is
153 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
154 // key), an n-bit message with most significant bit 0 always
155 // satisfies this requirement.
156 //
157 // 2. The message must have the same length in bits as the public
158 // modulus of the RSA key. This requirement isn't mathematically
159 // necessary, but is necessary to ensure consistency in
160 // implementations.
161 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600162 case KDF_SCRYPT_KEYMASTER:
163 // This ensures the most significant byte of the signed message
164 // is zero. We could have zero-padded to the left instead, but
165 // this approach is slightly more robust against changes in
166 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600167 // so) because we really should be using a proper deterministic
168 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800169 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600170 SLOGI("Signing safely-padded object");
171 break;
172 default:
173 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000174 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600175 }
Paul Crowley73473332017-11-21 15:43:51 -0800176 for (;;) {
177 auto result = keymaster_sign_object_for_cryptfs_scrypt(
178 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
179 to_sign_size, signature, signature_size);
180 switch (result) {
181 case KeymasterSignResult::ok:
182 return 0;
183 case KeymasterSignResult::upgrade:
184 break;
185 default:
186 return -1;
187 }
188 SLOGD("Upgrading key");
189 if (keymaster_upgrade_key_for_cryptfs_scrypt(
190 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
191 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
192 &ftr->keymaster_blob_size) != 0) {
193 SLOGE("Failed to upgrade key");
194 return -1;
195 }
196 if (put_crypt_ftr_and_key(ftr) != 0) {
197 SLOGE("Failed to write upgraded key to disk");
198 }
199 SLOGD("Key upgraded successfully");
200 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600201}
202
Paul Lawrence399317e2014-03-10 13:20:50 -0700203/* Store password when userdata is successfully decrypted and mounted.
204 * Cleared by cryptfs_clear_password
205 *
206 * To avoid a double prompt at boot, we need to store the CryptKeeper
207 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
208 * Since the entire framework is torn down and rebuilt after encryption,
209 * we have to use a daemon or similar to store the password. Since vold
210 * is secured against IPC except from system processes, it seems a reasonable
211 * place to store this.
212 *
213 * password should be cleared once it has been used.
214 *
215 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800216 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700217static char* password = 0;
218static int password_expiry_time = 0;
219static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800220
Josh Gaofec44372017-08-28 13:22:55 -0700221enum class RebootType {reboot, recovery, shutdown};
222static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700223{
Josh Gaofec44372017-08-28 13:22:55 -0700224 switch (rt) {
225 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800226 property_set(ANDROID_RB_PROPERTY, "reboot");
227 break;
228
Josh Gaofec44372017-08-28 13:22:55 -0700229 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800230 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
231 break;
232
Josh Gaofec44372017-08-28 13:22:55 -0700233 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800234 property_set(ANDROID_RB_PROPERTY, "shutdown");
235 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700236 }
Paul Lawrence87999172014-02-20 12:21:31 -0800237
Ken Sumralladfba362013-06-04 16:37:52 -0700238 sleep(20);
239
240 /* Shouldn't get here, reboot should happen before sleep times out */
241 return;
242}
243
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800244static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
245{
246 memset(io, 0, dataSize);
247 io->data_size = dataSize;
248 io->data_start = sizeof(struct dm_ioctl);
249 io->version[0] = 4;
250 io->version[1] = 0;
251 io->version[2] = 0;
252 io->flags = flags;
253 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100254 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800255 }
256}
257
Kenny Rootc4c70f12013-06-14 12:11:38 -0700258/**
259 * Gets the default device scrypt parameters for key derivation time tuning.
260 * The parameters should lead to about one second derivation time for the
261 * given device.
262 */
263static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700264 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000265 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700266
Paul Crowley63c18d32016-02-10 14:02:47 +0000267 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
268 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
269 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
270 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700271 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000272 ftr->N_factor = Nf;
273 ftr->r_factor = rf;
274 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700275}
276
Ken Sumrall3ed82362011-01-28 23:31:16 -0800277static unsigned int get_fs_size(char *dev)
278{
279 int fd, block_size;
280 struct ext4_super_block sb;
281 off64_t len;
282
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700283 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800284 SLOGE("Cannot open device to get filesystem size ");
285 return 0;
286 }
287
288 if (lseek64(fd, 1024, SEEK_SET) < 0) {
289 SLOGE("Cannot seek to superblock");
290 return 0;
291 }
292
293 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
294 SLOGE("Cannot read superblock");
295 return 0;
296 }
297
298 close(fd);
299
Daniel Rosenberge82df162014-08-15 22:19:23 +0000300 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
301 SLOGE("Not a valid ext4 superblock");
302 return 0;
303 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800304 block_size = 1024 << sb.s_log_block_size;
305 /* compute length in bytes */
306 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
307
308 /* return length in sectors */
309 return (unsigned int) (len / 512);
310}
311
Ken Sumrall160b4d62013-04-22 12:15:39 -0700312static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
313{
314 static int cached_data = 0;
315 static off64_t cached_off = 0;
316 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
317 int fd;
318 char key_loc[PROPERTY_VALUE_MAX];
319 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700320 int rc = -1;
321
322 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700323 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700324
325 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700326 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700327 SLOGE("Cannot open real block device %s\n", real_blkdev);
328 return -1;
329 }
330
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900331 unsigned long nr_sec = 0;
332 get_blkdev_size(fd, &nr_sec);
333 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700334 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
335 * encryption info footer and key, and plenty of bytes to spare for future
336 * growth.
337 */
338 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
339 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
340 cached_data = 1;
341 } else {
342 SLOGE("Cannot get size of block device %s\n", real_blkdev);
343 }
344 close(fd);
345 } else {
346 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
347 cached_off = 0;
348 cached_data = 1;
349 }
350 }
351
352 if (cached_data) {
353 if (metadata_fname) {
354 *metadata_fname = cached_metadata_fname;
355 }
356 if (off) {
357 *off = cached_off;
358 }
359 rc = 0;
360 }
361
362 return rc;
363}
364
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800365/* Set sha256 checksum in structure */
366static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
367{
368 SHA256_CTX c;
369 SHA256_Init(&c);
370 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
371 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
372 SHA256_Final(crypt_ftr->sha256, &c);
373}
374
Ken Sumralle8744072011-01-18 22:01:55 -0800375/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800376 * update the failed mount count but not change the key.
377 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800379{
380 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800381 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700382 /* starting_off is set to the SEEK_SET offset
383 * where the crypto structure starts
384 */
385 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800386 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700387 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700388 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800389
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800390 set_ftr_sha(crypt_ftr);
391
Ken Sumrall160b4d62013-04-22 12:15:39 -0700392 if (get_crypt_ftr_info(&fname, &starting_off)) {
393 SLOGE("Unable to get crypt_ftr_info\n");
394 return -1;
395 }
396 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700397 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700398 return -1;
399 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700400 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700401 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700402 return -1;
403 }
404
405 /* Seek to the start of the crypt footer */
406 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
407 SLOGE("Cannot seek to real block device footer\n");
408 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800409 }
410
411 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
412 SLOGE("Cannot write real block device footer\n");
413 goto errout;
414 }
415
Ken Sumrall3be890f2011-09-14 16:53:46 -0700416 fstat(fd, &statbuf);
417 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700418 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700419 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800420 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800421 goto errout;
422 }
423 }
424
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800425 /* Success! */
426 rc = 0;
427
428errout:
429 close(fd);
430 return rc;
431
432}
433
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800434static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
435{
436 struct crypt_mnt_ftr copy;
437 memcpy(&copy, crypt_ftr, sizeof(copy));
438 set_ftr_sha(&copy);
439 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
440}
441
Ken Sumrall160b4d62013-04-22 12:15:39 -0700442static inline int unix_read(int fd, void* buff, int len)
443{
444 return TEMP_FAILURE_RETRY(read(fd, buff, len));
445}
446
447static inline int unix_write(int fd, const void* buff, int len)
448{
449 return TEMP_FAILURE_RETRY(write(fd, buff, len));
450}
451
452static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
453{
454 memset(pdata, 0, len);
455 pdata->persist_magic = PERSIST_DATA_MAGIC;
456 pdata->persist_valid_entries = 0;
457}
458
459/* A routine to update the passed in crypt_ftr to the lastest version.
460 * fd is open read/write on the device that holds the crypto footer and persistent
461 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
462 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
463 */
464static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
465{
Kenny Root7434b312013-06-14 11:29:53 -0700466 int orig_major = crypt_ftr->major_version;
467 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700468
Kenny Root7434b312013-06-14 11:29:53 -0700469 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
470 struct crypt_persist_data *pdata;
471 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700472
Kenny Rootc4c70f12013-06-14 12:11:38 -0700473 SLOGW("upgrading crypto footer to 1.1");
474
Wei Wang4375f1b2017-02-24 17:43:01 -0800475 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700476 if (pdata == NULL) {
477 SLOGE("Cannot allocate persisent data\n");
478 return;
479 }
480 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
481
482 /* Need to initialize the persistent data area */
483 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
484 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100485 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700486 return;
487 }
488 /* Write all zeros to the first copy, making it invalid */
489 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
490
491 /* Write a valid but empty structure to the second copy */
492 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
493 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
494
495 /* Update the footer */
496 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
497 crypt_ftr->persist_data_offset[0] = pdata_offset;
498 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
499 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100500 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700501 }
502
Paul Lawrencef4faa572014-01-29 13:31:03 -0800503 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700504 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800505 /* But keep the old kdf_type.
506 * It will get updated later to KDF_SCRYPT after the password has been verified.
507 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700508 crypt_ftr->kdf_type = KDF_PBKDF2;
509 get_device_scrypt_params(crypt_ftr);
510 crypt_ftr->minor_version = 2;
511 }
512
Paul Lawrencef4faa572014-01-29 13:31:03 -0800513 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
514 SLOGW("upgrading crypto footer to 1.3");
515 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
516 crypt_ftr->minor_version = 3;
517 }
518
Kenny Root7434b312013-06-14 11:29:53 -0700519 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
520 if (lseek64(fd, offset, SEEK_SET) == -1) {
521 SLOGE("Cannot seek to crypt footer\n");
522 return;
523 }
524 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700525 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700526}
527
528
529static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800530{
531 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800532 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800534 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700535 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700536 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800537
Ken Sumrall160b4d62013-04-22 12:15:39 -0700538 if (get_crypt_ftr_info(&fname, &starting_off)) {
539 SLOGE("Unable to get crypt_ftr_info\n");
540 return -1;
541 }
542 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700543 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700544 return -1;
545 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700546 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700547 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700548 return -1;
549 }
550
551 /* Make sure it's 16 Kbytes in length */
552 fstat(fd, &statbuf);
553 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
554 SLOGE("footer file %s is not the expected size!\n", fname);
555 goto errout;
556 }
557
558 /* Seek to the start of the crypt footer */
559 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
560 SLOGE("Cannot seek to real block device footer\n");
561 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800562 }
563
564 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
565 SLOGE("Cannot read real block device footer\n");
566 goto errout;
567 }
568
569 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700570 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800571 goto errout;
572 }
573
Kenny Rootc96a5f82013-06-14 12:08:28 -0700574 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
575 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
576 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800577 goto errout;
578 }
579
Kenny Rootc96a5f82013-06-14 12:08:28 -0700580 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
581 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
582 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800583 }
584
Ken Sumrall160b4d62013-04-22 12:15:39 -0700585 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
586 * copy on disk before returning.
587 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700588 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700589 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800590 }
591
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800592 /* Success! */
593 rc = 0;
594
595errout:
596 close(fd);
597 return rc;
598}
599
Ken Sumrall160b4d62013-04-22 12:15:39 -0700600static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
601{
602 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
603 crypt_ftr->persist_data_offset[1]) {
604 SLOGE("Crypt_ftr persist data regions overlap");
605 return -1;
606 }
607
608 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
609 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
610 return -1;
611 }
612
613 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
614 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
615 CRYPT_FOOTER_OFFSET) {
616 SLOGE("Persistent data extends past crypto footer");
617 return -1;
618 }
619
620 return 0;
621}
622
623static int load_persistent_data(void)
624{
625 struct crypt_mnt_ftr crypt_ftr;
626 struct crypt_persist_data *pdata = NULL;
627 char encrypted_state[PROPERTY_VALUE_MAX];
628 char *fname;
629 int found = 0;
630 int fd;
631 int ret;
632 int i;
633
634 if (persist_data) {
635 /* Nothing to do, we've already loaded or initialized it */
636 return 0;
637 }
638
639
640 /* If not encrypted, just allocate an empty table and initialize it */
641 property_get("ro.crypto.state", encrypted_state, "");
642 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800643 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700644 if (pdata) {
645 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
646 persist_data = pdata;
647 return 0;
648 }
649 return -1;
650 }
651
652 if(get_crypt_ftr_and_key(&crypt_ftr)) {
653 return -1;
654 }
655
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700656 if ((crypt_ftr.major_version < 1)
657 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700658 SLOGE("Crypt_ftr version doesn't support persistent data");
659 return -1;
660 }
661
662 if (get_crypt_ftr_info(&fname, NULL)) {
663 return -1;
664 }
665
666 ret = validate_persistent_data_storage(&crypt_ftr);
667 if (ret) {
668 return -1;
669 }
670
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700671 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700672 if (fd < 0) {
673 SLOGE("Cannot open %s metadata file", fname);
674 return -1;
675 }
676
Wei Wang4375f1b2017-02-24 17:43:01 -0800677 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800678 if (pdata == NULL) {
679 SLOGE("Cannot allocate memory for persistent data");
680 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700681 }
682
683 for (i = 0; i < 2; i++) {
684 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
685 SLOGE("Cannot seek to read persistent data on %s", fname);
686 goto err2;
687 }
688 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
689 SLOGE("Error reading persistent data on iteration %d", i);
690 goto err2;
691 }
692 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
693 found = 1;
694 break;
695 }
696 }
697
698 if (!found) {
699 SLOGI("Could not find valid persistent data, creating");
700 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
701 }
702
703 /* Success */
704 persist_data = pdata;
705 close(fd);
706 return 0;
707
708err2:
709 free(pdata);
710
711err:
712 close(fd);
713 return -1;
714}
715
716static int save_persistent_data(void)
717{
718 struct crypt_mnt_ftr crypt_ftr;
719 struct crypt_persist_data *pdata;
720 char *fname;
721 off64_t write_offset;
722 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700723 int fd;
724 int ret;
725
726 if (persist_data == NULL) {
727 SLOGE("No persistent data to save");
728 return -1;
729 }
730
731 if(get_crypt_ftr_and_key(&crypt_ftr)) {
732 return -1;
733 }
734
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700735 if ((crypt_ftr.major_version < 1)
736 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700737 SLOGE("Crypt_ftr version doesn't support persistent data");
738 return -1;
739 }
740
741 ret = validate_persistent_data_storage(&crypt_ftr);
742 if (ret) {
743 return -1;
744 }
745
746 if (get_crypt_ftr_info(&fname, NULL)) {
747 return -1;
748 }
749
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700750 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700751 if (fd < 0) {
752 SLOGE("Cannot open %s metadata file", fname);
753 return -1;
754 }
755
Wei Wang4375f1b2017-02-24 17:43:01 -0800756 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700757 if (pdata == NULL) {
758 SLOGE("Cannot allocate persistant data");
759 goto err;
760 }
761
762 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
763 SLOGE("Cannot seek to read persistent data on %s", fname);
764 goto err2;
765 }
766
767 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
768 SLOGE("Error reading persistent data before save");
769 goto err2;
770 }
771
772 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
773 /* The first copy is the curent valid copy, so write to
774 * the second copy and erase this one */
775 write_offset = crypt_ftr.persist_data_offset[1];
776 erase_offset = crypt_ftr.persist_data_offset[0];
777 } else {
778 /* The second copy must be the valid copy, so write to
779 * the first copy, and erase the second */
780 write_offset = crypt_ftr.persist_data_offset[0];
781 erase_offset = crypt_ftr.persist_data_offset[1];
782 }
783
784 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100785 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700786 SLOGE("Cannot seek to write persistent data");
787 goto err2;
788 }
789 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
790 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100791 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700792 SLOGE("Cannot seek to erase previous persistent data");
793 goto err2;
794 }
795 fsync(fd);
796 memset(pdata, 0, crypt_ftr.persist_data_size);
797 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
798 (int) crypt_ftr.persist_data_size) {
799 SLOGE("Cannot write to erase previous persistent data");
800 goto err2;
801 }
802 fsync(fd);
803 } else {
804 SLOGE("Cannot write to save persistent data");
805 goto err2;
806 }
807
808 /* Success */
809 free(pdata);
810 close(fd);
811 return 0;
812
813err2:
814 free(pdata);
815err:
816 close(fd);
817 return -1;
818}
819
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800820/* Convert a binary key of specified length into an ascii hex string equivalent,
821 * without the leading 0x and with null termination
822 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700823static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700824 unsigned int keysize, char *master_key_ascii) {
825 unsigned int i, a;
826 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800827
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700828 for (i=0, a=0; i<keysize; i++, a+=2) {
829 /* For each byte, write out two ascii hex digits */
830 nibble = (master_key[i] >> 4) & 0xf;
831 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800832
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700833 nibble = master_key[i] & 0xf;
834 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
835 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800836
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700837 /* Add the null termination */
838 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800839
840}
841
Jeff Sharkey9c484982015-03-31 10:35:33 -0700842static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
843 const unsigned char *master_key, const char *real_blk_name,
844 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800845 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800846 struct dm_ioctl *io;
847 struct dm_target_spec *tgt;
848 char *crypt_params;
Greg Kaiserfa099612018-02-14 11:26:00 -0800849 // We can't assume the key is only KEY_LEN_BYTES. But we do know its limit
Greg Kaiser1452b272018-02-09 16:11:38 -0800850 // due to the crypt_mnt_ftr struct. We need two ASCII characters to represent
851 // each byte, and need space for the '\0' terminator.
852 char master_key_ascii[sizeof(crypt_ftr->master_key) * 2 + 1];
George Burgess IV605d7ae2016-02-29 13:39:17 -0800853 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800854 int i;
855
856 io = (struct dm_ioctl *) buffer;
857
858 /* Load the mapping table for this device */
859 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
860
861 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
862 io->target_count = 1;
863 tgt->status = 0;
864 tgt->sector_start = 0;
865 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700866 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800867
868 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
869 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800870
871 buff_offset = crypt_params - buffer;
Paul Crowley5afbc622017-11-27 09:42:17 -0800872 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800873 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
874 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
875 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800876 crypt_params += strlen(crypt_params) + 1;
877 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
878 tgt->next = crypt_params - buffer;
879
880 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
881 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
882 break;
883 }
884 usleep(500000);
885 }
886
887 if (i == TABLE_LOAD_RETRIES) {
888 /* We failed to load the table, return an error */
889 return -1;
890 } else {
891 return i + 1;
892 }
893}
894
895
896static int get_dm_crypt_version(int fd, const char *name, int *version)
897{
898 char buffer[DM_CRYPT_BUF_SIZE];
899 struct dm_ioctl *io;
900 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800901
902 io = (struct dm_ioctl *) buffer;
903
904 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
905
906 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
907 return -1;
908 }
909
910 /* Iterate over the returned versions, looking for name of "crypt".
911 * When found, get and return the version.
912 */
913 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
914 while (v->next) {
915 if (! strcmp(v->name, "crypt")) {
916 /* We found the crypt driver, return the version, and get out */
917 version[0] = v->version[0];
918 version[1] = v->version[1];
919 version[2] = v->version[2];
920 return 0;
921 }
922 v = (struct dm_target_versions *)(((char *)v) + v->next);
923 }
924
925 return -1;
926}
927
Paul Crowley5afbc622017-11-27 09:42:17 -0800928static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
929 if (extra_params_vec.empty()) return "";
930 std::string extra_params = std::to_string(extra_params_vec.size());
931 for (const auto& p : extra_params_vec) {
932 extra_params.append(" ");
933 extra_params.append(p);
934 }
935 return extra_params;
936}
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800937
Paul Crowley5afbc622017-11-27 09:42:17 -0800938static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
939 const char* real_blk_name, char* crypto_blk_name, const char* name,
940 uint32_t flags) {
941 char buffer[DM_CRYPT_BUF_SIZE];
942 struct dm_ioctl* io;
943 unsigned int minor;
944 int fd = 0;
945 int err;
946 int retval = -1;
947 int version[3];
948 int load_count;
949 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800950
Paul Crowley5afbc622017-11-27 09:42:17 -0800951 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
952 SLOGE("Cannot open device-mapper\n");
953 goto errout;
954 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800955
Paul Crowley5afbc622017-11-27 09:42:17 -0800956 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800957
Paul Crowley5afbc622017-11-27 09:42:17 -0800958 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
959 err = ioctl(fd, DM_DEV_CREATE, io);
960 if (err) {
961 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
962 goto errout;
963 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800964
Paul Crowley5afbc622017-11-27 09:42:17 -0800965 /* Get the device status, in particular, the name of it's device file */
966 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
967 if (ioctl(fd, DM_DEV_STATUS, io)) {
968 SLOGE("Cannot retrieve dm-crypt device status\n");
969 goto errout;
970 }
971 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
972 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -0700973
Paul Crowley5afbc622017-11-27 09:42:17 -0800974 if (!get_dm_crypt_version(fd, name, version)) {
975 /* Support for allow_discards was added in version 1.11.0 */
976 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
977 extra_params_vec.emplace_back("allow_discards");
978 }
979 }
980 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
981 extra_params_vec.emplace_back("allow_encrypt_override");
982 }
983 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
984 extra_params_as_string(extra_params_vec).c_str());
985 if (load_count < 0) {
986 SLOGE("Cannot load dm-crypt mapping table.\n");
987 goto errout;
988 } else if (load_count > 1) {
989 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
990 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800991
Paul Crowley5afbc622017-11-27 09:42:17 -0800992 /* Resume this device to activate it */
993 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800994
Paul Crowley5afbc622017-11-27 09:42:17 -0800995 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
996 SLOGE("Cannot resume the dm-crypt device\n");
997 goto errout;
998 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800999
Paul Crowley5afbc622017-11-27 09:42:17 -08001000 /* We made it here with no errors. Woot! */
1001 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001002
1003errout:
1004 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1005
1006 return retval;
1007}
1008
Wei Wang4375f1b2017-02-24 17:43:01 -08001009static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001010{
1011 int fd;
1012 char buffer[DM_CRYPT_BUF_SIZE];
1013 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001014 int retval = -1;
1015
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001016 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001017 SLOGE("Cannot open device-mapper\n");
1018 goto errout;
1019 }
1020
1021 io = (struct dm_ioctl *) buffer;
1022
1023 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1024 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1025 SLOGE("Cannot remove dm-crypt device\n");
1026 goto errout;
1027 }
1028
1029 /* We made it here with no errors. Woot! */
1030 retval = 0;
1031
1032errout:
1033 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1034
1035 return retval;
1036
1037}
1038
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001039static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001040 unsigned char *ikey, void *params UNUSED)
1041{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001042 SLOGI("Using pbkdf2 for cryptfs KDF");
1043
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001044 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001045 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Greg Kaiserfa099612018-02-14 11:26:00 -08001046 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
Adam Langleybf0d9722015-11-04 14:51:39 -08001047 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001048}
1049
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001050static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001051 unsigned char *ikey, void *params)
1052{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001053 SLOGI("Using scrypt for cryptfs KDF");
1054
Kenny Rootc4c70f12013-06-14 12:11:38 -07001055 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1056
1057 int N = 1 << ftr->N_factor;
1058 int r = 1 << ftr->r_factor;
1059 int p = 1 << ftr->p_factor;
1060
1061 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001062 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1063 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserfa099612018-02-14 11:26:00 -08001064 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001065
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001066 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001067}
1068
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001069static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1070 unsigned char *ikey, void *params)
1071{
1072 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1073
1074 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001075 size_t signature_size;
1076 unsigned char* signature;
1077 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1078
1079 int N = 1 << ftr->N_factor;
1080 int r = 1 << ftr->r_factor;
1081 int p = 1 << ftr->p_factor;
1082
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001083 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1084 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserfa099612018-02-14 11:26:00 -08001085 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001086
1087 if (rc) {
1088 SLOGE("scrypt failed");
1089 return -1;
1090 }
1091
Greg Kaiserfa099612018-02-14 11:26:00 -08001092 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
Shawn Willdene17a9c42014-09-08 13:04:08 -06001093 &signature, &signature_size)) {
1094 SLOGE("Signing failed");
1095 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001096 }
1097
1098 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
Greg Kaiserfa099612018-02-14 11:26:00 -08001099 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001100 free(signature);
1101
1102 if (rc) {
1103 SLOGE("scrypt failed");
1104 return -1;
1105 }
1106
1107 return 0;
1108}
1109
1110static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1111 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001112 unsigned char *encrypted_master_key,
1113 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001114{
Greg Kaiserb8020782018-02-14 11:26:12 -08001115 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001116 EVP_CIPHER_CTX e_ctx;
1117 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001118 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001119
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001120 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001121 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001122
1123 switch (crypt_ftr->kdf_type) {
1124 case KDF_SCRYPT_KEYMASTER:
1125 if (keymaster_create_key(crypt_ftr)) {
1126 SLOGE("keymaster_create_key failed");
1127 return -1;
1128 }
1129
1130 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1131 SLOGE("scrypt failed");
1132 return -1;
1133 }
1134 break;
1135
1136 case KDF_SCRYPT:
1137 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1138 SLOGE("scrypt failed");
1139 return -1;
1140 }
1141 break;
1142
1143 default:
1144 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001145 return -1;
1146 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001147
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001148 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001149 EVP_CIPHER_CTX_init(&e_ctx);
Greg Kaiserfa099612018-02-14 11:26:00 -08001150 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001151 SLOGE("EVP_EncryptInit failed\n");
1152 return -1;
1153 }
1154 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001155
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001157 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Greg Kaiserfa099612018-02-14 11:26:00 -08001158 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001159 SLOGE("EVP_EncryptUpdate failed\n");
1160 return -1;
1161 }
Adam Langley889c4f12014-09-03 14:23:13 -07001162 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001163 SLOGE("EVP_EncryptFinal failed\n");
1164 return -1;
1165 }
1166
Greg Kaiserfa099612018-02-14 11:26:00 -08001167 if (encrypted_len + final_len != KEY_LEN_BYTES) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001168 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1169 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001170 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001171
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001172 /* Store the scrypt of the intermediate key, so we can validate if it's a
1173 password error or mount error when things go wrong.
1174 Note there's no need to check for errors, since if this is incorrect, we
1175 simply won't wipe userdata, which is the correct default behavior
1176 */
1177 int N = 1 << crypt_ftr->N_factor;
1178 int r = 1 << crypt_ftr->r_factor;
1179 int p = 1 << crypt_ftr->p_factor;
1180
Greg Kaiserfa099612018-02-14 11:26:00 -08001181 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001182 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1183 crypt_ftr->scrypted_intermediate_key,
1184 sizeof(crypt_ftr->scrypted_intermediate_key));
1185
1186 if (rc) {
1187 SLOGE("encrypt_master_key: crypto_scrypt failed");
1188 }
1189
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001190 EVP_CIPHER_CTX_cleanup(&e_ctx);
1191
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001192 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001193}
1194
Paul Lawrence731a7a22015-04-28 22:14:15 +00001195static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001196 unsigned char *encrypted_master_key,
1197 unsigned char *decrypted_master_key,
1198 kdf_func kdf, void *kdf_params,
1199 unsigned char** intermediate_key,
1200 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001201{
Greg Kaiserb8020782018-02-14 11:26:12 -08001202 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 -08001203 EVP_CIPHER_CTX d_ctx;
1204 int decrypted_len, final_len;
1205
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001206 /* Turn the password into an intermediate key and IV that can decrypt the
1207 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001208 if (kdf(passwd, salt, ikey, kdf_params)) {
1209 SLOGE("kdf failed");
1210 return -1;
1211 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212
1213 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001214 EVP_CIPHER_CTX_init(&d_ctx);
Greg Kaiserfa099612018-02-14 11:26:00 -08001215 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001216 return -1;
1217 }
1218 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1219 /* Decrypt the master key */
1220 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
Greg Kaiserfa099612018-02-14 11:26:00 -08001221 encrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001222 return -1;
1223 }
Adam Langley889c4f12014-09-03 14:23:13 -07001224 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001225 return -1;
1226 }
1227
Greg Kaiserfa099612018-02-14 11:26:00 -08001228 if (decrypted_len + final_len != KEY_LEN_BYTES) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001229 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001231
1232 /* Copy intermediate key if needed by params */
1233 if (intermediate_key && intermediate_key_size) {
Greg Kaiserfa099612018-02-14 11:26:00 -08001234 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001235 if (*intermediate_key) {
Greg Kaiserfa099612018-02-14 11:26:00 -08001236 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1237 *intermediate_key_size = KEY_LEN_BYTES;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001238 }
1239 }
1240
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001241 EVP_CIPHER_CTX_cleanup(&d_ctx);
1242
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001243 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001244}
1245
Kenny Rootc4c70f12013-06-14 12:11:38 -07001246static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001247{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001248 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001249 *kdf = scrypt_keymaster;
1250 *kdf_params = ftr;
1251 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001252 *kdf = scrypt;
1253 *kdf_params = ftr;
1254 } else {
1255 *kdf = pbkdf2;
1256 *kdf_params = NULL;
1257 }
1258}
1259
Paul Lawrence731a7a22015-04-28 22:14:15 +00001260static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001261 struct crypt_mnt_ftr *crypt_ftr,
1262 unsigned char** intermediate_key,
1263 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001264{
1265 kdf_func kdf;
1266 void *kdf_params;
1267 int ret;
1268
1269 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001270 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1271 decrypted_master_key, kdf, kdf_params,
1272 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001273 if (ret != 0) {
1274 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001275 }
1276
1277 return ret;
1278}
1279
Wei Wang4375f1b2017-02-24 17:43:01 -08001280static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001281 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001282 int fd;
Greg Kaiserfa099612018-02-14 11:26:00 -08001283 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001284
1285 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001286 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001287 read(fd, key_buf, sizeof(key_buf));
1288 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001289 close(fd);
1290
1291 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001292 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001293}
1294
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001295int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001296{
Greg Hackmann955653e2014-09-24 14:55:20 -07001297 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001298#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001299
1300 /* Now umount the tmpfs filesystem */
1301 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001302 if (umount(mountpoint) == 0) {
1303 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001304 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001305
1306 if (errno == EINVAL) {
1307 /* EINVAL is returned if the directory is not a mountpoint,
1308 * i.e. there is no filesystem mounted there. So just get out.
1309 */
1310 break;
1311 }
1312
1313 err = errno;
1314
1315 /* If allowed, be increasingly aggressive before the last two retries */
1316 if (kill) {
1317 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1318 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001319 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001320 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1321 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001322 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001323 }
1324 }
1325
1326 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001327 }
1328
1329 if (i < WAIT_UNMOUNT_COUNT) {
1330 SLOGD("unmounting %s succeeded\n", mountpoint);
1331 rc = 0;
1332 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001333 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001334 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001335 rc = -1;
1336 }
1337
1338 return rc;
1339}
1340
Wei Wang42e38102017-06-07 10:46:12 -07001341static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001342{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001343 // NOTE: post_fs_data results in init calling back around to vold, so all
1344 // callers to this method must be async
1345
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001346 /* Do the prep of the /data filesystem */
1347 property_set("vold.post_fs_data_done", "0");
1348 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001349 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001350
Ken Sumrallc5872692013-05-14 15:26:31 -07001351 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001352 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001353 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001354 std::chrono::seconds(15))) {
1355 /* We timed out to prep /data in time. Continue wait. */
1356 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001357 }
Wei Wang42e38102017-06-07 10:46:12 -07001358 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001359}
1360
Paul Lawrence74f29f12014-08-28 15:54:10 -07001361static void cryptfs_set_corrupt()
1362{
1363 // Mark the footer as bad
1364 struct crypt_mnt_ftr crypt_ftr;
1365 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1366 SLOGE("Failed to get crypto footer - panic");
1367 return;
1368 }
1369
1370 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1371 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1372 SLOGE("Failed to set crypto footer - panic");
1373 return;
1374 }
1375}
1376
1377static void cryptfs_trigger_restart_min_framework()
1378{
1379 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1380 SLOGE("Failed to mount tmpfs on data - panic");
1381 return;
1382 }
1383
1384 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1385 SLOGE("Failed to trigger post fs data - panic");
1386 return;
1387 }
1388
1389 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1390 SLOGE("Failed to trigger restart min framework - panic");
1391 return;
1392 }
1393}
1394
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001395/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001396static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001397{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001398 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001399 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001400 static int restart_successful = 0;
1401
1402 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001403 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001404 SLOGE("Encrypted filesystem not validated, aborting");
1405 return -1;
1406 }
1407
1408 if (restart_successful) {
1409 SLOGE("System already restarted with encrypted disk, aborting");
1410 return -1;
1411 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001412
Paul Lawrencef4faa572014-01-29 13:31:03 -08001413 if (restart_main) {
1414 /* Here is where we shut down the framework. The init scripts
1415 * start all services in one of three classes: core, main or late_start.
1416 * On boot, we start core and main. Now, we stop main, but not core,
1417 * as core includes vold and a few other really important things that
1418 * we need to keep running. Once main has stopped, we should be able
1419 * to umount the tmpfs /data, then mount the encrypted /data.
1420 * We then restart the class main, and also the class late_start.
1421 * At the moment, I've only put a few things in late_start that I know
1422 * are not needed to bring up the framework, and that also cause problems
1423 * with unmounting the tmpfs /data, but I hope to add add more services
1424 * to the late_start class as we optimize this to decrease the delay
1425 * till the user is asked for the password to the filesystem.
1426 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427
Paul Lawrencef4faa572014-01-29 13:31:03 -08001428 /* The init files are setup to stop the class main when vold.decrypt is
1429 * set to trigger_reset_main.
1430 */
1431 property_set("vold.decrypt", "trigger_reset_main");
1432 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001433
Paul Lawrencef4faa572014-01-29 13:31:03 -08001434 /* Ugh, shutting down the framework is not synchronous, so until it
1435 * can be fixed, this horrible hack will wait a moment for it all to
1436 * shut down before proceeding. Without it, some devices cannot
1437 * restart the graphics services.
1438 */
1439 sleep(2);
1440 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001441
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001442 /* Now that the framework is shutdown, we should be able to umount()
1443 * the tmpfs filesystem, and mount the real one.
1444 */
1445
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001446 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1447 if (strlen(crypto_blkdev) == 0) {
1448 SLOGE("fs_crypto_blkdev not set\n");
1449 return -1;
1450 }
1451
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001452 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001453 /* If ro.crypto.readonly is set to 1, mount the decrypted
1454 * filesystem readonly. This is used when /data is mounted by
1455 * recovery mode.
1456 */
1457 char ro_prop[PROPERTY_VALUE_MAX];
1458 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001459 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001460 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001461 rec->flags |= MS_RDONLY;
1462 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001463
Ken Sumralle5032c42012-04-01 23:58:44 -07001464 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001465 int retries = RETRY_MOUNT_ATTEMPTS;
1466 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001467
1468 /*
1469 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1470 * partitions in the fsck domain.
1471 */
1472 if (setexeccon(secontextFsck())){
1473 SLOGE("Failed to setexeccon");
1474 return -1;
1475 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001476 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001477 crypto_blkdev, 0))
1478 != 0) {
1479 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1480 /* TODO: invoke something similar to
1481 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1482 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1483 SLOGI("Failed to mount %s because it is busy - waiting",
1484 crypto_blkdev);
1485 if (--retries) {
1486 sleep(RETRY_MOUNT_DELAY_SECONDS);
1487 } else {
1488 /* Let's hope that a reboot clears away whatever is keeping
1489 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001490 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001491 }
1492 } else {
1493 SLOGE("Failed to mount decrypted data");
1494 cryptfs_set_corrupt();
1495 cryptfs_trigger_restart_min_framework();
1496 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001497 if (setexeccon(NULL)) {
1498 SLOGE("Failed to setexeccon");
1499 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001500 return -1;
1501 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001502 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001503 if (setexeccon(NULL)) {
1504 SLOGE("Failed to setexeccon");
1505 return -1;
1506 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001507
Ken Sumralle5032c42012-04-01 23:58:44 -07001508 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001509 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001510 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001511
1512 /* startup service classes main and late_start */
1513 property_set("vold.decrypt", "trigger_restart_framework");
1514 SLOGD("Just triggered restart_framework\n");
1515
1516 /* Give it a few moments to get started */
1517 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001518 }
1519
Ken Sumrall0cc16632011-01-18 20:32:26 -08001520 if (rc == 0) {
1521 restart_successful = 1;
1522 }
1523
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001524 return rc;
1525}
1526
Paul Lawrencef4faa572014-01-29 13:31:03 -08001527int cryptfs_restart(void)
1528{
Paul Lawrence05335c32015-03-05 09:46:23 -08001529 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001530 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001531 SLOGE("cryptfs_restart not valid for file encryption:");
1532 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001533 }
1534
Paul Lawrencef4faa572014-01-29 13:31:03 -08001535 /* Call internal implementation forcing a restart of main service group */
1536 return cryptfs_restart_internal(1);
1537}
1538
Wei Wang4375f1b2017-02-24 17:43:01 -08001539static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001540{
1541 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001542 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001543 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001544
1545 property_get("ro.crypto.state", encrypted_state, "");
1546 if (strcmp(encrypted_state, "encrypted") ) {
1547 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001548 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001549 }
1550
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001551 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001552 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001553 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001554 }
1555
Ken Sumrall160b4d62013-04-22 12:15:39 -07001556 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001557 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001558
Ken Sumralle1a45852011-12-14 21:24:27 -08001559 /*
1560 * Only report this error if key_loc is a file and it exists.
1561 * If the device was never encrypted, and /data is not mountable for
1562 * some reason, returning 1 should prevent the UI from presenting the
1563 * a "enter password" screen, or worse, a "press button to wipe the
1564 * device" screen.
1565 */
1566 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1567 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001568 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001569 } else {
1570 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001571 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001572 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001573 }
1574
Paul Lawrence74f29f12014-08-28 15:54:10 -07001575 // Test for possible error flags
1576 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1577 SLOGE("Encryption process is partway completed\n");
1578 return CRYPTO_COMPLETE_PARTIAL;
1579 }
1580
1581 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1582 SLOGE("Encryption process was interrupted but cannot continue\n");
1583 return CRYPTO_COMPLETE_INCONSISTENT;
1584 }
1585
1586 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1587 SLOGE("Encryption is successful but data is corrupt\n");
1588 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001589 }
1590
1591 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001592 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001593}
1594
Paul Lawrencef4faa572014-01-29 13:31:03 -08001595static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001596 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001597{
Greg Kaiser2c92d7b2018-02-14 11:26:08 -08001598 /* Allocate enough space for a 256 bit key, but we may use less */
1599 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001600 char crypto_blkdev[MAXPATHLEN];
1601 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001602 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001603 unsigned int orig_failed_decrypt_count;
1604 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001605 int use_keymaster = 0;
1606 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001607 unsigned char* intermediate_key = 0;
1608 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001609 int N = 1 << crypt_ftr->N_factor;
1610 int r = 1 << crypt_ftr->r_factor;
1611 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001612
Paul Lawrencef4faa572014-01-29 13:31:03 -08001613 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1614 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001615
Paul Lawrencef4faa572014-01-29 13:31:03 -08001616 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001617 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1618 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001619 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001620 rc = -1;
1621 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001622 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001623 }
1624
Paul Crowleye2ee1522017-09-26 14:05:26 -07001625 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001626
Paul Lawrence74f29f12014-08-28 15:54:10 -07001627 // Create crypto block device - all (non fatal) code paths
1628 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001629 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1630 SLOGE("Error creating decrypted block device\n");
1631 rc = -1;
1632 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001633 }
1634
Paul Lawrence74f29f12014-08-28 15:54:10 -07001635 /* Work out if the problem is the password or the data */
1636 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1637 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001638
Paul Lawrence74f29f12014-08-28 15:54:10 -07001639 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1640 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1641 N, r, p, scrypted_intermediate_key,
1642 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001643
Paul Lawrence74f29f12014-08-28 15:54:10 -07001644 // Does the key match the crypto footer?
1645 if (rc == 0 && memcmp(scrypted_intermediate_key,
1646 crypt_ftr->scrypted_intermediate_key,
1647 sizeof(scrypted_intermediate_key)) == 0) {
1648 SLOGI("Password matches");
1649 rc = 0;
1650 } else {
1651 /* Try mounting the file system anyway, just in case the problem's with
1652 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001653 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1654 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001655 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001656 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001657 SLOGE("Error temp mounting decrypted block device\n");
1658 delete_crypto_blk_dev(label);
1659
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001660 rc = ++crypt_ftr->failed_decrypt_count;
1661 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001662 } else {
1663 /* Success! */
1664 SLOGI("Password did not match but decrypted drive mounted - continue");
1665 umount(tmp_mount_point);
1666 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001667 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001668 }
1669
1670 if (rc == 0) {
1671 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001672 if (orig_failed_decrypt_count != 0) {
1673 put_crypt_ftr_and_key(crypt_ftr);
1674 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001675
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001676 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001677 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001678 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001679
1680 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001681 * the key when we want to change the password on it. */
Greg Kaiserfa099612018-02-14 11:26:00 -08001682 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001683 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001684 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001685 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001686 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001687
Paul Lawrence74f29f12014-08-28 15:54:10 -07001688 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001689 use_keymaster = keymaster_check_compatibility();
1690 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001691 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001692 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1693 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1694 upgrade = 1;
1695 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001696 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001697 upgrade = 1;
1698 }
1699
1700 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001701 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1702 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001703 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001704 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001705 }
1706 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001707
1708 // Do not fail even if upgrade failed - machine is bootable
1709 // Note that if this code is ever hit, there is a *serious* problem
1710 // since KDFs should never fail. You *must* fix the kdf before
1711 // proceeding!
1712 if (rc) {
1713 SLOGW("Upgrade failed with error %d,"
1714 " but continuing with previous state",
1715 rc);
1716 rc = 0;
1717 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001718 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001719 }
1720
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001721 errout:
1722 if (intermediate_key) {
1723 memset(intermediate_key, 0, intermediate_key_size);
1724 free(intermediate_key);
1725 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001726 return rc;
1727}
1728
Ken Sumrall29d8da82011-05-18 17:20:07 -07001729/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001730 * Called by vold when it's asked to mount an encrypted external
1731 * storage volume. The incoming partition has no crypto header/footer,
1732 * as any metadata is been stored in a separate, small partition.
1733 *
1734 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001735 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001736int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1737 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001738 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001739 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001740 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001741 return -1;
1742 }
1743
1744 unsigned long nr_sec = 0;
1745 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001746 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001747
Ken Sumrall29d8da82011-05-18 17:20:07 -07001748 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001749 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001750 return -1;
1751 }
1752
Jeff Sharkey9c484982015-03-31 10:35:33 -07001753 struct crypt_mnt_ftr ext_crypt_ftr;
1754 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1755 ext_crypt_ftr.fs_size = nr_sec;
1756 ext_crypt_ftr.keysize = keysize;
Greg Kaiserfa099612018-02-14 11:26:00 -08001757 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001758 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001759
Paul Crowley5afbc622017-11-27 09:42:17 -08001760 return create_crypto_blk_dev(
1761 &ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label,
1762 e4crypt_is_native() ? CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE : 0);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001763}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001764
Jeff Sharkey9c484982015-03-31 10:35:33 -07001765/*
1766 * Called by vold when it's asked to unmount an encrypted external
1767 * storage volume.
1768 */
1769int cryptfs_revert_ext_volume(const char* label) {
1770 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001771}
1772
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001773int cryptfs_crypto_complete(void)
1774{
1775 return do_crypto_complete("/data");
1776}
1777
Paul Lawrencef4faa572014-01-29 13:31:03 -08001778int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1779{
1780 char encrypted_state[PROPERTY_VALUE_MAX];
1781 property_get("ro.crypto.state", encrypted_state, "");
1782 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1783 SLOGE("encrypted fs already validated or not running with encryption,"
1784 " aborting");
1785 return -1;
1786 }
1787
1788 if (get_crypt_ftr_and_key(crypt_ftr)) {
1789 SLOGE("Error getting crypt footer and key");
1790 return -1;
1791 }
1792
1793 return 0;
1794}
1795
Wei Wang4375f1b2017-02-24 17:43:01 -08001796int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001797{
Paul Lawrence05335c32015-03-05 09:46:23 -08001798 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001799 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001800 SLOGE("cryptfs_check_passwd not valid for file encryption");
1801 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001802 }
1803
Paul Lawrencef4faa572014-01-29 13:31:03 -08001804 struct crypt_mnt_ftr crypt_ftr;
1805 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001806
Paul Lawrencef4faa572014-01-29 13:31:03 -08001807 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001808 if (rc) {
1809 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001810 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001811 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001812
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001813 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001814 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1815 if (rc) {
1816 SLOGE("Password did not match");
1817 return rc;
1818 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001819
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001820 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1821 // Here we have a default actual password but a real password
1822 // we must test against the scrypted value
1823 // First, we must delete the crypto block device that
1824 // test_mount_encrypted_fs leaves behind as a side effect
1825 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1826 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1827 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1828 if (rc) {
1829 SLOGE("Default password did not match on reboot encryption");
1830 return rc;
1831 }
1832
1833 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1834 put_crypt_ftr_and_key(&crypt_ftr);
1835 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1836 if (rc) {
1837 SLOGE("Could not change password on reboot encryption");
1838 return rc;
1839 }
1840 }
1841
1842 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001843 cryptfs_clear_password();
1844 password = strdup(passwd);
1845 struct timespec now;
1846 clock_gettime(CLOCK_BOOTTIME, &now);
1847 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001848 }
1849
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001850 return rc;
1851}
1852
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001853int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001854{
1855 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser2c92d7b2018-02-14 11:26:08 -08001856 /* Allocate enough space for a 256 bit key, but we may use less */
1857 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001858 char encrypted_state[PROPERTY_VALUE_MAX];
1859 int rc;
1860
1861 property_get("ro.crypto.state", encrypted_state, "");
1862 if (strcmp(encrypted_state, "encrypted") ) {
1863 SLOGE("device not encrypted, aborting");
1864 return -2;
1865 }
1866
1867 if (!master_key_saved) {
1868 SLOGE("encrypted fs not yet mounted, aborting");
1869 return -1;
1870 }
1871
1872 if (!saved_mount_point) {
1873 SLOGE("encrypted fs failed to save mount point, aborting");
1874 return -1;
1875 }
1876
Ken Sumrall160b4d62013-04-22 12:15:39 -07001877 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001878 SLOGE("Error getting crypt footer and key\n");
1879 return -1;
1880 }
1881
1882 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1883 /* If the device has no password, then just say the password is valid */
1884 rc = 0;
1885 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001886 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001887 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1888 /* They match, the password is correct */
1889 rc = 0;
1890 } else {
1891 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1892 sleep(1);
1893 rc = 1;
1894 }
1895 }
1896
1897 return rc;
1898}
1899
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001900/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiserfa099612018-02-14 11:26:00 -08001901 * defaulted to 16 bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001902 * Presumably, at a minimum, the caller will update the
1903 * filesystem size and crypto_type_name after calling this function.
1904 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001905static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001906{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001907 off64_t off;
1908
1909 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001910 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001911 ftr->major_version = CURRENT_MAJOR_VERSION;
1912 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001913 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiserfa099612018-02-14 11:26:00 -08001914 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001915
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001916 switch (keymaster_check_compatibility()) {
1917 case 1:
1918 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1919 break;
1920
1921 case 0:
1922 ftr->kdf_type = KDF_SCRYPT;
1923 break;
1924
1925 default:
1926 SLOGE("keymaster_check_compatibility failed");
1927 return -1;
1928 }
1929
Kenny Rootc4c70f12013-06-14 12:11:38 -07001930 get_device_scrypt_params(ftr);
1931
Ken Sumrall160b4d62013-04-22 12:15:39 -07001932 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1933 if (get_crypt_ftr_info(NULL, &off) == 0) {
1934 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1935 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1936 ftr->persist_data_size;
1937 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001938
1939 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001940}
1941
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001942#define FRAMEWORK_BOOT_WAIT 60
1943
Paul Lawrence87999172014-02-20 12:21:31 -08001944static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1945{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001946 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001947 if (fd == -1) {
1948 SLOGE("Error opening file %s", filename);
1949 return -1;
1950 }
1951
1952 char block[CRYPT_INPLACE_BUFSIZE];
1953 memset(block, 0, sizeof(block));
1954 if (unix_read(fd, block, sizeof(block)) < 0) {
1955 SLOGE("Error reading file %s", filename);
1956 close(fd);
1957 return -1;
1958 }
1959
1960 close(fd);
1961
1962 SHA256_CTX c;
1963 SHA256_Init(&c);
1964 SHA256_Update(&c, block, sizeof(block));
1965 SHA256_Final(buf, &c);
1966
1967 return 0;
1968}
1969
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001970static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
1971 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08001972 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08001973 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001974
Paul Lawrence87999172014-02-20 12:21:31 -08001975 /* The size of the userdata partition, and add in the vold volumes below */
1976 tot_encryption_size = crypt_ftr->fs_size;
1977
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001978 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08001979 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08001980
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001981 if (rc == ENABLE_INPLACE_ERR_DEV) {
1982 /* Hack for b/17898962 */
1983 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
1984 cryptfs_reboot(RebootType::reboot);
1985 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07001986
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001987 if (!rc) {
1988 crypt_ftr->encrypted_upto = cur_encryption_done;
1989 }
Paul Lawrence87999172014-02-20 12:21:31 -08001990
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001991 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
1992 /* The inplace routine never actually sets the progress to 100% due
1993 * to the round down nature of integer division, so set it here */
1994 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08001995 }
1996
1997 return rc;
1998}
1999
Paul Crowleyb64933a2017-10-31 08:25:55 -07002000static int vold_unmountAll(void) {
2001 VolumeManager* vm = VolumeManager::Instance();
2002 return vm->unmountAll();
2003}
2004
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002005int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002006 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser2c92d7b2018-02-14 11:26:08 -08002007 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002008 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002009 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002010 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002011 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002012 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002013 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002014 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002015 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002016 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002017 bool onlyCreateHeader = false;
2018 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002019
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002020 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002021 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2022 /* An encryption was underway and was interrupted */
2023 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2024 crypt_ftr.encrypted_upto = 0;
2025 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002026
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002027 /* At this point, we are in an inconsistent state. Until we successfully
2028 complete encryption, a reboot will leave us broken. So mark the
2029 encryption failed in case that happens.
2030 On successfully completing encryption, remove this flag */
2031 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002032
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002033 put_crypt_ftr_and_key(&crypt_ftr);
2034 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2035 if (!check_ftr_sha(&crypt_ftr)) {
2036 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2037 put_crypt_ftr_and_key(&crypt_ftr);
2038 goto error_unencrypted;
2039 }
2040
2041 /* Doing a reboot-encryption*/
2042 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2043 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2044 rebootEncryption = true;
2045 }
Paul Lawrence87999172014-02-20 12:21:31 -08002046 }
2047
2048 property_get("ro.crypto.state", encrypted_state, "");
2049 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2050 SLOGE("Device is already running encrypted, aborting");
2051 goto error_unencrypted;
2052 }
2053
2054 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002055 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2056 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002057
Ken Sumrall3ed82362011-01-28 23:31:16 -08002058 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002059 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002060 if (fd == -1) {
2061 SLOGE("Cannot open block device %s\n", real_blkdev);
2062 goto error_unencrypted;
2063 }
2064 unsigned long nr_sec;
2065 get_blkdev_size(fd, &nr_sec);
2066 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002067 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2068 goto error_unencrypted;
2069 }
2070 close(fd);
2071
2072 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002073 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002074 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002075 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002076 if (fs_size_sec == 0)
2077 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2078
Paul Lawrence87999172014-02-20 12:21:31 -08002079 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002080
2081 if (fs_size_sec > max_fs_size_sec) {
2082 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2083 goto error_unencrypted;
2084 }
2085 }
2086
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002087 /* Get a wakelock as this may take a while, and we don't want the
2088 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2089 * wants to keep the screen on, it can grab a full wakelock.
2090 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002091 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002092 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2093
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002094 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002095 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002096 */
2097 property_set("vold.decrypt", "trigger_shutdown_framework");
2098 SLOGD("Just asked init to shut down class main\n");
2099
Jeff Sharkey9c484982015-03-31 10:35:33 -07002100 /* Ask vold to unmount all devices that it manages */
2101 if (vold_unmountAll()) {
2102 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002103 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002104
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002105 /* no_ui means we are being called from init, not settings.
2106 Now we always reboot from settings, so !no_ui means reboot
2107 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002108 if (!no_ui) {
2109 /* Try fallback, which is to reboot and try there */
2110 onlyCreateHeader = true;
2111 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2112 if (breadcrumb == 0) {
2113 SLOGE("Failed to create breadcrumb file");
2114 goto error_shutting_down;
2115 }
2116 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002117 }
2118
2119 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002120 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002121 /* Now that /data is unmounted, we need to mount a tmpfs
2122 * /data, set a property saying we're doing inplace encryption,
2123 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002124 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002125 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002126 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002127 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002128 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002129 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002130
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002131 /* restart the framework. */
2132 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002133 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002134
Ken Sumrall92736ef2012-10-17 20:57:14 -07002135 /* Ugh, shutting down the framework is not synchronous, so until it
2136 * can be fixed, this horrible hack will wait a moment for it all to
2137 * shut down before proceeding. Without it, some devices cannot
2138 * restart the graphics services.
2139 */
2140 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002141 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002142
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002143 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002144 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002145 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002146 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2147 goto error_shutting_down;
2148 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002149
Paul Lawrence87999172014-02-20 12:21:31 -08002150 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2151 crypt_ftr.fs_size = nr_sec
2152 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2153 } else {
2154 crypt_ftr.fs_size = nr_sec;
2155 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002156 /* At this point, we are in an inconsistent state. Until we successfully
2157 complete encryption, a reboot will leave us broken. So mark the
2158 encryption failed in case that happens.
2159 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002160 if (onlyCreateHeader) {
2161 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2162 } else {
2163 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2164 }
Paul Lawrence87999172014-02-20 12:21:31 -08002165 crypt_ftr.crypt_type = crypt_type;
Greg Kaiserfa099612018-02-14 11:26:00 -08002166 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002167
Paul Lawrence87999172014-02-20 12:21:31 -08002168 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002169 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2170 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002171 SLOGE("Cannot create encrypted master key\n");
2172 goto error_shutting_down;
2173 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002174
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002175 /* Replace scrypted intermediate key if we are preparing for a reboot */
2176 if (onlyCreateHeader) {
Greg Kaiserfa099612018-02-14 11:26:00 -08002177 unsigned char fake_master_key[KEY_LEN_BYTES];
2178 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002179 memset(fake_master_key, 0, sizeof(fake_master_key));
2180 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2181 encrypted_fake_master_key, &crypt_ftr);
2182 }
2183
Paul Lawrence87999172014-02-20 12:21:31 -08002184 /* Write the key to the end of the partition */
2185 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002186
Paul Lawrence87999172014-02-20 12:21:31 -08002187 /* If any persistent data has been remembered, save it.
2188 * If none, create a valid empty table and save that.
2189 */
2190 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002191 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002192 if (pdata) {
2193 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2194 persist_data = pdata;
2195 }
2196 }
2197 if (persist_data) {
2198 save_persistent_data();
2199 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002200 }
2201
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002202 if (onlyCreateHeader) {
2203 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002204 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002205 }
2206
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002207 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002208 /* startup service classes main and late_start */
2209 property_set("vold.decrypt", "trigger_restart_min_framework");
2210 SLOGD("Just triggered restart_min_framework\n");
2211
2212 /* OK, the framework is restarted and will soon be showing a
2213 * progress bar. Time to setup an encrypted mapping, and
2214 * either write a new filesystem, or encrypt in place updating
2215 * the progress bar as we work.
2216 */
2217 }
2218
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002219 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002220 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002221 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002222
Paul Lawrence87999172014-02-20 12:21:31 -08002223 /* If we are continuing, check checksums match */
2224 rc = 0;
2225 if (previously_encrypted_upto) {
2226 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2227 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002228
Paul Lawrence87999172014-02-20 12:21:31 -08002229 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2230 sizeof(hash_first_block)) != 0) {
2231 SLOGE("Checksums do not match - trigger wipe");
2232 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002233 }
2234 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002235
Paul Lawrence87999172014-02-20 12:21:31 -08002236 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002237 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002238 previously_encrypted_upto);
2239 }
2240
2241 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002242 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002243 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2244 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002245 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002246 SLOGE("Error calculating checksum for continuing encryption");
2247 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002248 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002249 }
2250
2251 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002252 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002253
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002254 if (! rc) {
2255 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002256 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002257
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002258 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002259 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2260 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002261 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002262 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002263
Paul Lawrence6bfed202014-07-28 12:47:22 -07002264 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002265
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002266 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2267 char value[PROPERTY_VALUE_MAX];
2268 property_get("ro.crypto.state", value, "");
2269 if (!strcmp(value, "")) {
2270 /* default encryption - continue first boot sequence */
2271 property_set("ro.crypto.state", "encrypted");
2272 property_set("ro.crypto.type", "block");
2273 release_wake_lock(lockid);
2274 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2275 // Bring up cryptkeeper that will check the password and set it
2276 property_set("vold.decrypt", "trigger_shutdown_framework");
2277 sleep(2);
2278 property_set("vold.encrypt_progress", "");
2279 cryptfs_trigger_restart_min_framework();
2280 } else {
2281 cryptfs_check_passwd(DEFAULT_PASSWORD);
2282 cryptfs_restart_internal(1);
2283 }
2284 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002285 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002286 sleep(2); /* Give the UI a chance to show 100% progress */
2287 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002288 }
Paul Lawrence87999172014-02-20 12:21:31 -08002289 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002290 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002291 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002292 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002293 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002294 char value[PROPERTY_VALUE_MAX];
2295
Ken Sumrall319369a2012-06-27 16:30:18 -07002296 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002297 if (!strcmp(value, "1")) {
2298 /* wipe data if encryption failed */
2299 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002300 std::string err;
2301 const std::vector<std::string> options = {
2302 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2303 };
2304 if (!write_bootloader_message(options, &err)) {
2305 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002306 }
Josh Gaofec44372017-08-28 13:22:55 -07002307 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002308 } else {
2309 /* set property to trigger dialog */
2310 property_set("vold.encrypt_progress", "error_partially_encrypted");
2311 release_wake_lock(lockid);
2312 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002313 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002314 }
2315
Ken Sumrall3ed82362011-01-28 23:31:16 -08002316 /* hrm, the encrypt step claims success, but the reboot failed.
2317 * This should not happen.
2318 * Set the property and return. Hope the framework can deal with it.
2319 */
2320 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002321 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002322 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002323
2324error_unencrypted:
2325 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002326 if (lockid[0]) {
2327 release_wake_lock(lockid);
2328 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002329 return -1;
2330
2331error_shutting_down:
2332 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2333 * but the framework is stopped and not restarted to show the error, so it's up to
2334 * vold to restart the system.
2335 */
2336 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002337 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002338
2339 /* shouldn't get here */
2340 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002341 if (lockid[0]) {
2342 release_wake_lock(lockid);
2343 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002344 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002345}
2346
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002347int cryptfs_enable(int type, const char* passwd, int no_ui) {
2348 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002349}
2350
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002351int cryptfs_enable_default(int no_ui) {
2352 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002353}
2354
2355int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002356{
Paul Crowley38132a12016-02-09 09:50:32 +00002357 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002358 SLOGE("cryptfs_changepw not valid for file encryption");
2359 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002360 }
2361
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002362 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002363 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002364
2365 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002366 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002367 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002368 return -1;
2369 }
2370
Paul Lawrencef4faa572014-01-29 13:31:03 -08002371 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2372 SLOGE("Invalid crypt_type %d", crypt_type);
2373 return -1;
2374 }
2375
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002376 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002377 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002378 SLOGE("Error getting crypt footer and key");
2379 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002380 }
2381
Paul Lawrencef4faa572014-01-29 13:31:03 -08002382 crypt_ftr.crypt_type = crypt_type;
2383
JP Abgrall933216c2015-02-11 13:44:32 -08002384 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002385 : newpw,
2386 crypt_ftr.salt,
2387 saved_master_key,
2388 crypt_ftr.master_key,
2389 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002390 if (rc) {
2391 SLOGE("Encrypt master key failed: %d", rc);
2392 return -1;
2393 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002394 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002395 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002396
2397 return 0;
2398}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002399
Rubin Xu85c01f92014-10-13 12:49:54 +01002400static unsigned int persist_get_max_entries(int encrypted) {
2401 struct crypt_mnt_ftr crypt_ftr;
2402 unsigned int dsize;
2403 unsigned int max_persistent_entries;
2404
2405 /* If encrypted, use the values from the crypt_ftr, otherwise
2406 * use the values for the current spec.
2407 */
2408 if (encrypted) {
2409 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2410 return -1;
2411 }
2412 dsize = crypt_ftr.persist_data_size;
2413 } else {
2414 dsize = CRYPT_PERSIST_DATA_SIZE;
2415 }
2416
2417 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2418 sizeof(struct crypt_persist_entry);
2419
2420 return max_persistent_entries;
2421}
2422
2423static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002424{
2425 unsigned int i;
2426
2427 if (persist_data == NULL) {
2428 return -1;
2429 }
2430 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2431 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2432 /* We found it! */
2433 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2434 return 0;
2435 }
2436 }
2437
2438 return -1;
2439}
2440
Rubin Xu85c01f92014-10-13 12:49:54 +01002441static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002442{
2443 unsigned int i;
2444 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002445 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002446
2447 if (persist_data == NULL) {
2448 return -1;
2449 }
2450
Rubin Xu85c01f92014-10-13 12:49:54 +01002451 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002452
2453 num = persist_data->persist_valid_entries;
2454
2455 for (i = 0; i < num; i++) {
2456 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2457 /* We found an existing entry, update it! */
2458 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2459 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2460 return 0;
2461 }
2462 }
2463
2464 /* We didn't find it, add it to the end, if there is room */
2465 if (persist_data->persist_valid_entries < max_persistent_entries) {
2466 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2467 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2468 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2469 persist_data->persist_valid_entries++;
2470 return 0;
2471 }
2472
2473 return -1;
2474}
2475
Rubin Xu85c01f92014-10-13 12:49:54 +01002476/**
2477 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2478 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2479 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002480int match_multi_entry(const char *key, const char *field, unsigned index) {
2481 std::string key_ = key;
2482 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002483
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002484 std::string parsed_field;
2485 unsigned parsed_index;
2486
2487 std::string::size_type split = key_.find_last_of('_');
2488 if (split == std::string::npos) {
2489 parsed_field = key_;
2490 parsed_index = 0;
2491 } else {
2492 parsed_field = key_.substr(0, split);
2493 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002494 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002495
2496 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002497}
2498
2499/*
2500 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2501 * remaining entries starting from index will be deleted.
2502 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2503 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2504 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2505 *
2506 */
2507static int persist_del_keys(const char *fieldname, unsigned index)
2508{
2509 unsigned int i;
2510 unsigned int j;
2511 unsigned int num;
2512
2513 if (persist_data == NULL) {
2514 return PERSIST_DEL_KEY_ERROR_OTHER;
2515 }
2516
2517 num = persist_data->persist_valid_entries;
2518
2519 j = 0; // points to the end of non-deleted entries.
2520 // Filter out to-be-deleted entries in place.
2521 for (i = 0; i < num; i++) {
2522 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2523 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2524 j++;
2525 }
2526 }
2527
2528 if (j < num) {
2529 persist_data->persist_valid_entries = j;
2530 // Zeroise the remaining entries
2531 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2532 return PERSIST_DEL_KEY_OK;
2533 } else {
2534 // Did not find an entry matching the given fieldname
2535 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2536 }
2537}
2538
2539static int persist_count_keys(const char *fieldname)
2540{
2541 unsigned int i;
2542 unsigned int count;
2543
2544 if (persist_data == NULL) {
2545 return -1;
2546 }
2547
2548 count = 0;
2549 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2550 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2551 count++;
2552 }
2553 }
2554
2555 return count;
2556}
2557
Ken Sumrall160b4d62013-04-22 12:15:39 -07002558/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002559int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002560{
Paul Crowley38132a12016-02-09 09:50:32 +00002561 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002562 SLOGE("Cannot get field when file encrypted");
2563 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002564 }
2565
Ken Sumrall160b4d62013-04-22 12:15:39 -07002566 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002567 /* CRYPTO_GETFIELD_OK is success,
2568 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2569 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2570 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002571 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002572 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2573 int i;
2574 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002575
2576 if (persist_data == NULL) {
2577 load_persistent_data();
2578 if (persist_data == NULL) {
2579 SLOGE("Getfield error, cannot load persistent data");
2580 goto out;
2581 }
2582 }
2583
Rubin Xu85c01f92014-10-13 12:49:54 +01002584 // Read value from persistent entries. If the original value is split into multiple entries,
2585 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002586 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002587 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2588 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2589 // value too small
2590 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2591 goto out;
2592 }
2593 rc = CRYPTO_GETFIELD_OK;
2594
2595 for (i = 1; /* break explicitly */; i++) {
2596 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2597 (int) sizeof(temp_field)) {
2598 // If the fieldname is very long, we stop as soon as it begins to overflow the
2599 // maximum field length. At this point we have in fact fully read out the original
2600 // value because cryptfs_setfield would not allow fields with longer names to be
2601 // written in the first place.
2602 break;
2603 }
2604 if (!persist_get_key(temp_field, temp_value)) {
2605 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2606 // value too small.
2607 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2608 goto out;
2609 }
2610 } else {
2611 // Exhaust all entries.
2612 break;
2613 }
2614 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002615 } else {
2616 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002617 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002618 }
2619
2620out:
2621 return rc;
2622}
2623
2624/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002625int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002626{
Paul Crowley38132a12016-02-09 09:50:32 +00002627 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002628 SLOGE("Cannot set field when file encrypted");
2629 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002630 }
2631
Ken Sumrall160b4d62013-04-22 12:15:39 -07002632 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002633 /* 0 is success, negative values are error */
2634 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002635 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002636 unsigned int field_id;
2637 char temp_field[PROPERTY_KEY_MAX];
2638 unsigned int num_entries;
2639 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002640
2641 if (persist_data == NULL) {
2642 load_persistent_data();
2643 if (persist_data == NULL) {
2644 SLOGE("Setfield error, cannot load persistent data");
2645 goto out;
2646 }
2647 }
2648
2649 property_get("ro.crypto.state", encrypted_state, "");
2650 if (!strcmp(encrypted_state, "encrypted") ) {
2651 encrypted = 1;
2652 }
2653
Rubin Xu85c01f92014-10-13 12:49:54 +01002654 // Compute the number of entries required to store value, each entry can store up to
2655 // (PROPERTY_VALUE_MAX - 1) chars
2656 if (strlen(value) == 0) {
2657 // Empty value also needs one entry to store.
2658 num_entries = 1;
2659 } else {
2660 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2661 }
2662
2663 max_keylen = strlen(fieldname);
2664 if (num_entries > 1) {
2665 // Need an extra "_%d" suffix.
2666 max_keylen += 1 + log10(num_entries);
2667 }
2668 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2669 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002670 goto out;
2671 }
2672
Rubin Xu85c01f92014-10-13 12:49:54 +01002673 // Make sure we have enough space to write the new value
2674 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2675 persist_get_max_entries(encrypted)) {
2676 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2677 goto out;
2678 }
2679
2680 // Now that we know persist_data has enough space for value, let's delete the old field first
2681 // to make up space.
2682 persist_del_keys(fieldname, 0);
2683
2684 if (persist_set_key(fieldname, value, encrypted)) {
2685 // fail to set key, should not happen as we have already checked the available space
2686 SLOGE("persist_set_key() error during setfield()");
2687 goto out;
2688 }
2689
2690 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002691 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002692
2693 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2694 // fail to set key, should not happen as we have already checked the available space.
2695 SLOGE("persist_set_key() error during setfield()");
2696 goto out;
2697 }
2698 }
2699
Ken Sumrall160b4d62013-04-22 12:15:39 -07002700 /* If we are running encrypted, save the persistent data now */
2701 if (encrypted) {
2702 if (save_persistent_data()) {
2703 SLOGE("Setfield error, cannot save persistent data");
2704 goto out;
2705 }
2706 }
2707
Rubin Xu85c01f92014-10-13 12:49:54 +01002708 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002709
2710out:
2711 return rc;
2712}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002713
2714/* Checks userdata. Attempt to mount the volume if default-
2715 * encrypted.
2716 * On success trigger next init phase and return 0.
2717 * Currently do not handle failure - see TODO below.
2718 */
2719int cryptfs_mount_default_encrypted(void)
2720{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002721 int crypt_type = cryptfs_get_password_type();
2722 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2723 SLOGE("Bad crypt type - error");
2724 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2725 SLOGD("Password is not default - "
2726 "starting min framework to prompt");
2727 property_set("vold.decrypt", "trigger_restart_min_framework");
2728 return 0;
2729 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2730 SLOGD("Password is default - restarting filesystem");
2731 cryptfs_restart_internal(0);
2732 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002733 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002734 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002735 }
2736
Paul Lawrence6bfed202014-07-28 12:47:22 -07002737 /** Corrupt. Allow us to boot into framework, which will detect bad
2738 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002739 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002740 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002741 return 0;
2742}
2743
2744/* Returns type of the password, default, pattern, pin or password.
2745 */
2746int cryptfs_get_password_type(void)
2747{
Paul Crowley38132a12016-02-09 09:50:32 +00002748 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002749 SLOGE("cryptfs_get_password_type not valid for file encryption");
2750 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002751 }
2752
Paul Lawrencef4faa572014-01-29 13:31:03 -08002753 struct crypt_mnt_ftr crypt_ftr;
2754
2755 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2756 SLOGE("Error getting crypt footer and key\n");
2757 return -1;
2758 }
2759
Paul Lawrence6bfed202014-07-28 12:47:22 -07002760 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2761 return -1;
2762 }
2763
Paul Lawrencef4faa572014-01-29 13:31:03 -08002764 return crypt_ftr.crypt_type;
2765}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002766
Paul Lawrence05335c32015-03-05 09:46:23 -08002767const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002768{
Paul Crowley38132a12016-02-09 09:50:32 +00002769 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002770 SLOGE("cryptfs_get_password not valid for file encryption");
2771 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002772 }
2773
Paul Lawrence399317e2014-03-10 13:20:50 -07002774 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002775 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002776 if (now.tv_sec < password_expiry_time) {
2777 return password;
2778 } else {
2779 cryptfs_clear_password();
2780 return 0;
2781 }
2782}
2783
2784void cryptfs_clear_password()
2785{
2786 if (password) {
2787 size_t len = strlen(password);
2788 memset(password, 0, len);
2789 free(password);
2790 password = 0;
2791 password_expiry_time = 0;
2792 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002793}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002794
Paul Lawrence0c247462015-10-29 10:30:57 -07002795int cryptfs_isConvertibleToFBE()
2796{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002797 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002798 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2799}