blob: f500a15e9ccbfac5d88d5cabd7fa5e9784dc963e [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
Greg Kaiser4a35ef02018-02-09 17:01:06 -0800101// EVP_DecryptUpdate() requires not just our key length, but up to
102// block length - 1 additional bytes for its work. We provide a buffer
103// size that will work for all possible ciphers.
Greg Kaiserfa099612018-02-14 11:26:00 -0800104#define DECRYPTED_MASTER_KEY_BUF_SIZE (KEY_LEN_BYTES + EVP_MAX_BLOCK_LENGTH - 1)
Greg Kaiser4a35ef02018-02-09 17:01:06 -0800105
Paul Crowley73473332017-11-21 15:43:51 -0800106static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
107
Greg Kaiserfa099612018-02-14 11:26:00 -0800108static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700109static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600110static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700111static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800112
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700113/* Should we use keymaster? */
114static int keymaster_check_compatibility()
115{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000116 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700117}
118
119/* Create a new keymaster key and store it in this footer */
120static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
121{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800122 if (ftr->keymaster_blob_size) {
123 SLOGI("Already have key");
124 return 0;
125 }
126
Janis Danisevskis015ec302017-01-31 11:31:08 +0000127 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
128 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
129 &ftr->keymaster_blob_size);
130 if (rc) {
131 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800132 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000133 ftr->keymaster_blob_size = 0;
134 }
135 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700136 return -1;
137 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000138 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700139}
140
Shawn Willdene17a9c42014-09-08 13:04:08 -0600141/* This signs the given object using the keymaster key. */
142static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600143 const unsigned char *object,
144 const size_t object_size,
145 unsigned char **signature,
146 size_t *signature_size)
147{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600148 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600149 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600150 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600151
Shawn Willdene17a9c42014-09-08 13:04:08 -0600152 // To sign a message with RSA, the message must satisfy two
153 // constraints:
154 //
155 // 1. The message, when interpreted as a big-endian numeric value, must
156 // be strictly less than the public modulus of the RSA key. Note
157 // that because the most significant bit of the public modulus is
158 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
159 // key), an n-bit message with most significant bit 0 always
160 // satisfies this requirement.
161 //
162 // 2. The message must have the same length in bits as the public
163 // modulus of the RSA key. This requirement isn't mathematically
164 // necessary, but is necessary to ensure consistency in
165 // implementations.
166 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600167 case KDF_SCRYPT_KEYMASTER:
168 // This ensures the most significant byte of the signed message
169 // is zero. We could have zero-padded to the left instead, but
170 // this approach is slightly more robust against changes in
171 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600172 // so) because we really should be using a proper deterministic
173 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800174 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600175 SLOGI("Signing safely-padded object");
176 break;
177 default:
178 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000179 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600180 }
Paul Crowley73473332017-11-21 15:43:51 -0800181 for (;;) {
182 auto result = keymaster_sign_object_for_cryptfs_scrypt(
183 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
184 to_sign_size, signature, signature_size);
185 switch (result) {
186 case KeymasterSignResult::ok:
187 return 0;
188 case KeymasterSignResult::upgrade:
189 break;
190 default:
191 return -1;
192 }
193 SLOGD("Upgrading key");
194 if (keymaster_upgrade_key_for_cryptfs_scrypt(
195 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
196 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
197 &ftr->keymaster_blob_size) != 0) {
198 SLOGE("Failed to upgrade key");
199 return -1;
200 }
201 if (put_crypt_ftr_and_key(ftr) != 0) {
202 SLOGE("Failed to write upgraded key to disk");
203 }
204 SLOGD("Key upgraded successfully");
205 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600206}
207
Paul Lawrence399317e2014-03-10 13:20:50 -0700208/* Store password when userdata is successfully decrypted and mounted.
209 * Cleared by cryptfs_clear_password
210 *
211 * To avoid a double prompt at boot, we need to store the CryptKeeper
212 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
213 * Since the entire framework is torn down and rebuilt after encryption,
214 * we have to use a daemon or similar to store the password. Since vold
215 * is secured against IPC except from system processes, it seems a reasonable
216 * place to store this.
217 *
218 * password should be cleared once it has been used.
219 *
220 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800221 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700222static char* password = 0;
223static int password_expiry_time = 0;
224static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800225
Josh Gaofec44372017-08-28 13:22:55 -0700226enum class RebootType {reboot, recovery, shutdown};
227static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700228{
Josh Gaofec44372017-08-28 13:22:55 -0700229 switch (rt) {
230 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800231 property_set(ANDROID_RB_PROPERTY, "reboot");
232 break;
233
Josh Gaofec44372017-08-28 13:22:55 -0700234 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800235 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
236 break;
237
Josh Gaofec44372017-08-28 13:22:55 -0700238 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800239 property_set(ANDROID_RB_PROPERTY, "shutdown");
240 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700241 }
Paul Lawrence87999172014-02-20 12:21:31 -0800242
Ken Sumralladfba362013-06-04 16:37:52 -0700243 sleep(20);
244
245 /* Shouldn't get here, reboot should happen before sleep times out */
246 return;
247}
248
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800249static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
250{
251 memset(io, 0, dataSize);
252 io->data_size = dataSize;
253 io->data_start = sizeof(struct dm_ioctl);
254 io->version[0] = 4;
255 io->version[1] = 0;
256 io->version[2] = 0;
257 io->flags = flags;
258 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100259 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800260 }
261}
262
Kenny Rootc4c70f12013-06-14 12:11:38 -0700263/**
264 * Gets the default device scrypt parameters for key derivation time tuning.
265 * The parameters should lead to about one second derivation time for the
266 * given device.
267 */
268static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700269 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000270 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700271
Paul Crowley63c18d32016-02-10 14:02:47 +0000272 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
273 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
274 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
275 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700276 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000277 ftr->N_factor = Nf;
278 ftr->r_factor = rf;
279 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700280}
281
Ken Sumrall3ed82362011-01-28 23:31:16 -0800282static unsigned int get_fs_size(char *dev)
283{
284 int fd, block_size;
285 struct ext4_super_block sb;
286 off64_t len;
287
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700288 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800289 SLOGE("Cannot open device to get filesystem size ");
290 return 0;
291 }
292
293 if (lseek64(fd, 1024, SEEK_SET) < 0) {
294 SLOGE("Cannot seek to superblock");
295 return 0;
296 }
297
298 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
299 SLOGE("Cannot read superblock");
300 return 0;
301 }
302
303 close(fd);
304
Daniel Rosenberge82df162014-08-15 22:19:23 +0000305 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
306 SLOGE("Not a valid ext4 superblock");
307 return 0;
308 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800309 block_size = 1024 << sb.s_log_block_size;
310 /* compute length in bytes */
311 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
312
313 /* return length in sectors */
314 return (unsigned int) (len / 512);
315}
316
Ken Sumrall160b4d62013-04-22 12:15:39 -0700317static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
318{
319 static int cached_data = 0;
320 static off64_t cached_off = 0;
321 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
322 int fd;
323 char key_loc[PROPERTY_VALUE_MAX];
324 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700325 int rc = -1;
326
327 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700328 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700329
330 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700331 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700332 SLOGE("Cannot open real block device %s\n", real_blkdev);
333 return -1;
334 }
335
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900336 unsigned long nr_sec = 0;
337 get_blkdev_size(fd, &nr_sec);
338 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700339 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
340 * encryption info footer and key, and plenty of bytes to spare for future
341 * growth.
342 */
343 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
344 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
345 cached_data = 1;
346 } else {
347 SLOGE("Cannot get size of block device %s\n", real_blkdev);
348 }
349 close(fd);
350 } else {
351 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
352 cached_off = 0;
353 cached_data = 1;
354 }
355 }
356
357 if (cached_data) {
358 if (metadata_fname) {
359 *metadata_fname = cached_metadata_fname;
360 }
361 if (off) {
362 *off = cached_off;
363 }
364 rc = 0;
365 }
366
367 return rc;
368}
369
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800370/* Set sha256 checksum in structure */
371static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
372{
373 SHA256_CTX c;
374 SHA256_Init(&c);
375 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
376 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
377 SHA256_Final(crypt_ftr->sha256, &c);
378}
379
Ken Sumralle8744072011-01-18 22:01:55 -0800380/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800381 * update the failed mount count but not change the key.
382 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700383static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800384{
385 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800386 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700387 /* starting_off is set to the SEEK_SET offset
388 * where the crypto structure starts
389 */
390 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800391 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700392 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700393 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800394
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800395 set_ftr_sha(crypt_ftr);
396
Ken Sumrall160b4d62013-04-22 12:15:39 -0700397 if (get_crypt_ftr_info(&fname, &starting_off)) {
398 SLOGE("Unable to get crypt_ftr_info\n");
399 return -1;
400 }
401 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700402 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700403 return -1;
404 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700405 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700406 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700407 return -1;
408 }
409
410 /* Seek to the start of the crypt footer */
411 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
412 SLOGE("Cannot seek to real block device footer\n");
413 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800414 }
415
416 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
417 SLOGE("Cannot write real block device footer\n");
418 goto errout;
419 }
420
Ken Sumrall3be890f2011-09-14 16:53:46 -0700421 fstat(fd, &statbuf);
422 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700423 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700424 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800425 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800426 goto errout;
427 }
428 }
429
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800430 /* Success! */
431 rc = 0;
432
433errout:
434 close(fd);
435 return rc;
436
437}
438
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800439static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
440{
441 struct crypt_mnt_ftr copy;
442 memcpy(&copy, crypt_ftr, sizeof(copy));
443 set_ftr_sha(&copy);
444 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
445}
446
Ken Sumrall160b4d62013-04-22 12:15:39 -0700447static inline int unix_read(int fd, void* buff, int len)
448{
449 return TEMP_FAILURE_RETRY(read(fd, buff, len));
450}
451
452static inline int unix_write(int fd, const void* buff, int len)
453{
454 return TEMP_FAILURE_RETRY(write(fd, buff, len));
455}
456
457static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
458{
459 memset(pdata, 0, len);
460 pdata->persist_magic = PERSIST_DATA_MAGIC;
461 pdata->persist_valid_entries = 0;
462}
463
464/* A routine to update the passed in crypt_ftr to the lastest version.
465 * fd is open read/write on the device that holds the crypto footer and persistent
466 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
467 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
468 */
469static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
470{
Kenny Root7434b312013-06-14 11:29:53 -0700471 int orig_major = crypt_ftr->major_version;
472 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700473
Kenny Root7434b312013-06-14 11:29:53 -0700474 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
475 struct crypt_persist_data *pdata;
476 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700477
Kenny Rootc4c70f12013-06-14 12:11:38 -0700478 SLOGW("upgrading crypto footer to 1.1");
479
Wei Wang4375f1b2017-02-24 17:43:01 -0800480 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700481 if (pdata == NULL) {
482 SLOGE("Cannot allocate persisent data\n");
483 return;
484 }
485 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
486
487 /* Need to initialize the persistent data area */
488 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
489 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100490 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700491 return;
492 }
493 /* Write all zeros to the first copy, making it invalid */
494 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
495
496 /* Write a valid but empty structure to the second copy */
497 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
498 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
499
500 /* Update the footer */
501 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
502 crypt_ftr->persist_data_offset[0] = pdata_offset;
503 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
504 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100505 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700506 }
507
Paul Lawrencef4faa572014-01-29 13:31:03 -0800508 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700509 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800510 /* But keep the old kdf_type.
511 * It will get updated later to KDF_SCRYPT after the password has been verified.
512 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700513 crypt_ftr->kdf_type = KDF_PBKDF2;
514 get_device_scrypt_params(crypt_ftr);
515 crypt_ftr->minor_version = 2;
516 }
517
Paul Lawrencef4faa572014-01-29 13:31:03 -0800518 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
519 SLOGW("upgrading crypto footer to 1.3");
520 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
521 crypt_ftr->minor_version = 3;
522 }
523
Kenny Root7434b312013-06-14 11:29:53 -0700524 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
525 if (lseek64(fd, offset, SEEK_SET) == -1) {
526 SLOGE("Cannot seek to crypt footer\n");
527 return;
528 }
529 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700530 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700531}
532
533
534static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800535{
536 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800537 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700538 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800539 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700540 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700541 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800542
Ken Sumrall160b4d62013-04-22 12:15:39 -0700543 if (get_crypt_ftr_info(&fname, &starting_off)) {
544 SLOGE("Unable to get crypt_ftr_info\n");
545 return -1;
546 }
547 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700548 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700549 return -1;
550 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700551 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700552 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700553 return -1;
554 }
555
556 /* Make sure it's 16 Kbytes in length */
557 fstat(fd, &statbuf);
558 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
559 SLOGE("footer file %s is not the expected size!\n", fname);
560 goto errout;
561 }
562
563 /* Seek to the start of the crypt footer */
564 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
565 SLOGE("Cannot seek to real block device footer\n");
566 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800567 }
568
569 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
570 SLOGE("Cannot read real block device footer\n");
571 goto errout;
572 }
573
574 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700575 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800576 goto errout;
577 }
578
Kenny Rootc96a5f82013-06-14 12:08:28 -0700579 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
580 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
581 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800582 goto errout;
583 }
584
Kenny Rootc96a5f82013-06-14 12:08:28 -0700585 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
586 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
587 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800588 }
589
Ken Sumrall160b4d62013-04-22 12:15:39 -0700590 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
591 * copy on disk before returning.
592 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700593 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700594 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800595 }
596
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800597 /* Success! */
598 rc = 0;
599
600errout:
601 close(fd);
602 return rc;
603}
604
Ken Sumrall160b4d62013-04-22 12:15:39 -0700605static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
606{
607 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
608 crypt_ftr->persist_data_offset[1]) {
609 SLOGE("Crypt_ftr persist data regions overlap");
610 return -1;
611 }
612
613 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
614 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
615 return -1;
616 }
617
618 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
619 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
620 CRYPT_FOOTER_OFFSET) {
621 SLOGE("Persistent data extends past crypto footer");
622 return -1;
623 }
624
625 return 0;
626}
627
628static int load_persistent_data(void)
629{
630 struct crypt_mnt_ftr crypt_ftr;
631 struct crypt_persist_data *pdata = NULL;
632 char encrypted_state[PROPERTY_VALUE_MAX];
633 char *fname;
634 int found = 0;
635 int fd;
636 int ret;
637 int i;
638
639 if (persist_data) {
640 /* Nothing to do, we've already loaded or initialized it */
641 return 0;
642 }
643
644
645 /* If not encrypted, just allocate an empty table and initialize it */
646 property_get("ro.crypto.state", encrypted_state, "");
647 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800648 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700649 if (pdata) {
650 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
651 persist_data = pdata;
652 return 0;
653 }
654 return -1;
655 }
656
657 if(get_crypt_ftr_and_key(&crypt_ftr)) {
658 return -1;
659 }
660
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700661 if ((crypt_ftr.major_version < 1)
662 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700663 SLOGE("Crypt_ftr version doesn't support persistent data");
664 return -1;
665 }
666
667 if (get_crypt_ftr_info(&fname, NULL)) {
668 return -1;
669 }
670
671 ret = validate_persistent_data_storage(&crypt_ftr);
672 if (ret) {
673 return -1;
674 }
675
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700676 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700677 if (fd < 0) {
678 SLOGE("Cannot open %s metadata file", fname);
679 return -1;
680 }
681
Wei Wang4375f1b2017-02-24 17:43:01 -0800682 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800683 if (pdata == NULL) {
684 SLOGE("Cannot allocate memory for persistent data");
685 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700686 }
687
688 for (i = 0; i < 2; i++) {
689 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
690 SLOGE("Cannot seek to read persistent data on %s", fname);
691 goto err2;
692 }
693 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
694 SLOGE("Error reading persistent data on iteration %d", i);
695 goto err2;
696 }
697 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
698 found = 1;
699 break;
700 }
701 }
702
703 if (!found) {
704 SLOGI("Could not find valid persistent data, creating");
705 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
706 }
707
708 /* Success */
709 persist_data = pdata;
710 close(fd);
711 return 0;
712
713err2:
714 free(pdata);
715
716err:
717 close(fd);
718 return -1;
719}
720
721static int save_persistent_data(void)
722{
723 struct crypt_mnt_ftr crypt_ftr;
724 struct crypt_persist_data *pdata;
725 char *fname;
726 off64_t write_offset;
727 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700728 int fd;
729 int ret;
730
731 if (persist_data == NULL) {
732 SLOGE("No persistent data to save");
733 return -1;
734 }
735
736 if(get_crypt_ftr_and_key(&crypt_ftr)) {
737 return -1;
738 }
739
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700740 if ((crypt_ftr.major_version < 1)
741 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700742 SLOGE("Crypt_ftr version doesn't support persistent data");
743 return -1;
744 }
745
746 ret = validate_persistent_data_storage(&crypt_ftr);
747 if (ret) {
748 return -1;
749 }
750
751 if (get_crypt_ftr_info(&fname, NULL)) {
752 return -1;
753 }
754
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700755 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700756 if (fd < 0) {
757 SLOGE("Cannot open %s metadata file", fname);
758 return -1;
759 }
760
Wei Wang4375f1b2017-02-24 17:43:01 -0800761 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700762 if (pdata == NULL) {
763 SLOGE("Cannot allocate persistant data");
764 goto err;
765 }
766
767 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
768 SLOGE("Cannot seek to read persistent data on %s", fname);
769 goto err2;
770 }
771
772 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
773 SLOGE("Error reading persistent data before save");
774 goto err2;
775 }
776
777 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
778 /* The first copy is the curent valid copy, so write to
779 * the second copy and erase this one */
780 write_offset = crypt_ftr.persist_data_offset[1];
781 erase_offset = crypt_ftr.persist_data_offset[0];
782 } else {
783 /* The second copy must be the valid copy, so write to
784 * the first copy, and erase the second */
785 write_offset = crypt_ftr.persist_data_offset[0];
786 erase_offset = crypt_ftr.persist_data_offset[1];
787 }
788
789 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100790 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700791 SLOGE("Cannot seek to write persistent data");
792 goto err2;
793 }
794 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
795 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100796 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700797 SLOGE("Cannot seek to erase previous persistent data");
798 goto err2;
799 }
800 fsync(fd);
801 memset(pdata, 0, crypt_ftr.persist_data_size);
802 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
803 (int) crypt_ftr.persist_data_size) {
804 SLOGE("Cannot write to erase previous persistent data");
805 goto err2;
806 }
807 fsync(fd);
808 } else {
809 SLOGE("Cannot write to save persistent data");
810 goto err2;
811 }
812
813 /* Success */
814 free(pdata);
815 close(fd);
816 return 0;
817
818err2:
819 free(pdata);
820err:
821 close(fd);
822 return -1;
823}
824
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800825/* Convert a binary key of specified length into an ascii hex string equivalent,
826 * without the leading 0x and with null termination
827 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700828static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700829 unsigned int keysize, char *master_key_ascii) {
830 unsigned int i, a;
831 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800832
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700833 for (i=0, a=0; i<keysize; i++, a+=2) {
834 /* For each byte, write out two ascii hex digits */
835 nibble = (master_key[i] >> 4) & 0xf;
836 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800837
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700838 nibble = master_key[i] & 0xf;
839 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
840 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800841
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700842 /* Add the null termination */
843 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800844
845}
846
Jeff Sharkey9c484982015-03-31 10:35:33 -0700847static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
848 const unsigned char *master_key, const char *real_blk_name,
849 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800850 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800851 struct dm_ioctl *io;
852 struct dm_target_spec *tgt;
853 char *crypt_params;
Greg Kaiserfa099612018-02-14 11:26:00 -0800854 // We can't assume the key is only KEY_LEN_BYTES. But we do know its limit
Greg Kaiser1452b272018-02-09 16:11:38 -0800855 // due to the crypt_mnt_ftr struct. We need two ASCII characters to represent
856 // each byte, and need space for the '\0' terminator.
857 char master_key_ascii[sizeof(crypt_ftr->master_key) * 2 + 1];
George Burgess IV605d7ae2016-02-29 13:39:17 -0800858 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800859 int i;
860
861 io = (struct dm_ioctl *) buffer;
862
863 /* Load the mapping table for this device */
864 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
865
866 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
867 io->target_count = 1;
868 tgt->status = 0;
869 tgt->sector_start = 0;
870 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700871 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800872
873 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
874 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800875
876 buff_offset = crypt_params - buffer;
Paul Crowley5afbc622017-11-27 09:42:17 -0800877 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800878 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
879 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
880 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800881 crypt_params += strlen(crypt_params) + 1;
882 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
883 tgt->next = crypt_params - buffer;
884
885 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
886 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
887 break;
888 }
889 usleep(500000);
890 }
891
892 if (i == TABLE_LOAD_RETRIES) {
893 /* We failed to load the table, return an error */
894 return -1;
895 } else {
896 return i + 1;
897 }
898}
899
900
901static int get_dm_crypt_version(int fd, const char *name, int *version)
902{
903 char buffer[DM_CRYPT_BUF_SIZE];
904 struct dm_ioctl *io;
905 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800906
907 io = (struct dm_ioctl *) buffer;
908
909 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
910
911 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
912 return -1;
913 }
914
915 /* Iterate over the returned versions, looking for name of "crypt".
916 * When found, get and return the version.
917 */
918 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
919 while (v->next) {
920 if (! strcmp(v->name, "crypt")) {
921 /* We found the crypt driver, return the version, and get out */
922 version[0] = v->version[0];
923 version[1] = v->version[1];
924 version[2] = v->version[2];
925 return 0;
926 }
927 v = (struct dm_target_versions *)(((char *)v) + v->next);
928 }
929
930 return -1;
931}
932
Paul Crowley5afbc622017-11-27 09:42:17 -0800933static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
934 if (extra_params_vec.empty()) return "";
935 std::string extra_params = std::to_string(extra_params_vec.size());
936 for (const auto& p : extra_params_vec) {
937 extra_params.append(" ");
938 extra_params.append(p);
939 }
940 return extra_params;
941}
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800942
Paul Crowley5afbc622017-11-27 09:42:17 -0800943static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
944 const char* real_blk_name, char* crypto_blk_name, const char* name,
945 uint32_t flags) {
946 char buffer[DM_CRYPT_BUF_SIZE];
947 struct dm_ioctl* io;
948 unsigned int minor;
949 int fd = 0;
950 int err;
951 int retval = -1;
952 int version[3];
953 int load_count;
954 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800955
Paul Crowley5afbc622017-11-27 09:42:17 -0800956 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
957 SLOGE("Cannot open device-mapper\n");
958 goto errout;
959 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800960
Paul Crowley5afbc622017-11-27 09:42:17 -0800961 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800962
Paul Crowley5afbc622017-11-27 09:42:17 -0800963 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
964 err = ioctl(fd, DM_DEV_CREATE, io);
965 if (err) {
966 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
967 goto errout;
968 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800969
Paul Crowley5afbc622017-11-27 09:42:17 -0800970 /* Get the device status, in particular, the name of it's device file */
971 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
972 if (ioctl(fd, DM_DEV_STATUS, io)) {
973 SLOGE("Cannot retrieve dm-crypt device status\n");
974 goto errout;
975 }
976 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
977 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -0700978
Paul Crowley5afbc622017-11-27 09:42:17 -0800979 if (!get_dm_crypt_version(fd, name, version)) {
980 /* Support for allow_discards was added in version 1.11.0 */
981 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
982 extra_params_vec.emplace_back("allow_discards");
983 }
984 }
985 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
986 extra_params_vec.emplace_back("allow_encrypt_override");
987 }
988 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
989 extra_params_as_string(extra_params_vec).c_str());
990 if (load_count < 0) {
991 SLOGE("Cannot load dm-crypt mapping table.\n");
992 goto errout;
993 } else if (load_count > 1) {
994 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
995 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800996
Paul Crowley5afbc622017-11-27 09:42:17 -0800997 /* Resume this device to activate it */
998 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800999
Paul Crowley5afbc622017-11-27 09:42:17 -08001000 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1001 SLOGE("Cannot resume the dm-crypt device\n");
1002 goto errout;
1003 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001004
Paul Crowley5afbc622017-11-27 09:42:17 -08001005 /* We made it here with no errors. Woot! */
1006 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001007
1008errout:
1009 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1010
1011 return retval;
1012}
1013
Wei Wang4375f1b2017-02-24 17:43:01 -08001014static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001015{
1016 int fd;
1017 char buffer[DM_CRYPT_BUF_SIZE];
1018 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001019 int retval = -1;
1020
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001021 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001022 SLOGE("Cannot open device-mapper\n");
1023 goto errout;
1024 }
1025
1026 io = (struct dm_ioctl *) buffer;
1027
1028 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1029 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1030 SLOGE("Cannot remove dm-crypt device\n");
1031 goto errout;
1032 }
1033
1034 /* We made it here with no errors. Woot! */
1035 retval = 0;
1036
1037errout:
1038 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1039
1040 return retval;
1041
1042}
1043
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001044static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001045 unsigned char *ikey, void *params UNUSED)
1046{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001047 SLOGI("Using pbkdf2 for cryptfs KDF");
1048
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001049 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001050 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Greg Kaiserfa099612018-02-14 11:26:00 -08001051 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
Adam Langleybf0d9722015-11-04 14:51:39 -08001052 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001053}
1054
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001055static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001056 unsigned char *ikey, void *params)
1057{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001058 SLOGI("Using scrypt for cryptfs KDF");
1059
Kenny Rootc4c70f12013-06-14 12:11:38 -07001060 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1061
1062 int N = 1 << ftr->N_factor;
1063 int r = 1 << ftr->r_factor;
1064 int p = 1 << ftr->p_factor;
1065
1066 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001067 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1068 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserfa099612018-02-14 11:26:00 -08001069 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001070
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001071 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001072}
1073
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001074static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1075 unsigned char *ikey, void *params)
1076{
1077 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1078
1079 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001080 size_t signature_size;
1081 unsigned char* signature;
1082 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1083
1084 int N = 1 << ftr->N_factor;
1085 int r = 1 << ftr->r_factor;
1086 int p = 1 << ftr->p_factor;
1087
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001088 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1089 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserfa099612018-02-14 11:26:00 -08001090 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001091
1092 if (rc) {
1093 SLOGE("scrypt failed");
1094 return -1;
1095 }
1096
Greg Kaiserfa099612018-02-14 11:26:00 -08001097 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
Shawn Willdene17a9c42014-09-08 13:04:08 -06001098 &signature, &signature_size)) {
1099 SLOGE("Signing failed");
1100 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001101 }
1102
1103 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
Greg Kaiserfa099612018-02-14 11:26:00 -08001104 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001105 free(signature);
1106
1107 if (rc) {
1108 SLOGE("scrypt failed");
1109 return -1;
1110 }
1111
1112 return 0;
1113}
1114
1115static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1116 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001117 unsigned char *encrypted_master_key,
1118 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001119{
Greg Kaiserfa099612018-02-14 11:26:00 -08001120 unsigned char ikey[KEY_LEN_BYTES+IV_LEN_BYTES] = { 0 };
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001121 EVP_CIPHER_CTX e_ctx;
1122 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001123 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001124
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001125 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001126 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001127
1128 switch (crypt_ftr->kdf_type) {
1129 case KDF_SCRYPT_KEYMASTER:
1130 if (keymaster_create_key(crypt_ftr)) {
1131 SLOGE("keymaster_create_key failed");
1132 return -1;
1133 }
1134
1135 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1136 SLOGE("scrypt failed");
1137 return -1;
1138 }
1139 break;
1140
1141 case KDF_SCRYPT:
1142 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1143 SLOGE("scrypt failed");
1144 return -1;
1145 }
1146 break;
1147
1148 default:
1149 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001150 return -1;
1151 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001152
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001153 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001154 EVP_CIPHER_CTX_init(&e_ctx);
Greg Kaiserfa099612018-02-14 11:26:00 -08001155 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 SLOGE("EVP_EncryptInit failed\n");
1157 return -1;
1158 }
1159 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001160
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001162 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Greg Kaiserfa099612018-02-14 11:26:00 -08001163 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001164 SLOGE("EVP_EncryptUpdate failed\n");
1165 return -1;
1166 }
Adam Langley889c4f12014-09-03 14:23:13 -07001167 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001168 SLOGE("EVP_EncryptFinal failed\n");
1169 return -1;
1170 }
1171
Greg Kaiserfa099612018-02-14 11:26:00 -08001172 if (encrypted_len + final_len != KEY_LEN_BYTES) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001173 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1174 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001175 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001176
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001177 /* Store the scrypt of the intermediate key, so we can validate if it's a
1178 password error or mount error when things go wrong.
1179 Note there's no need to check for errors, since if this is incorrect, we
1180 simply won't wipe userdata, which is the correct default behavior
1181 */
1182 int N = 1 << crypt_ftr->N_factor;
1183 int r = 1 << crypt_ftr->r_factor;
1184 int p = 1 << crypt_ftr->p_factor;
1185
Greg Kaiserfa099612018-02-14 11:26:00 -08001186 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001187 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1188 crypt_ftr->scrypted_intermediate_key,
1189 sizeof(crypt_ftr->scrypted_intermediate_key));
1190
1191 if (rc) {
1192 SLOGE("encrypt_master_key: crypto_scrypt failed");
1193 }
1194
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001195 EVP_CIPHER_CTX_cleanup(&e_ctx);
1196
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001197 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001198}
1199
Paul Lawrence731a7a22015-04-28 22:14:15 +00001200static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001201 unsigned char *encrypted_master_key,
1202 unsigned char *decrypted_master_key,
1203 kdf_func kdf, void *kdf_params,
1204 unsigned char** intermediate_key,
1205 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001206{
Greg Kaiserfa099612018-02-14 11:26:00 -08001207 unsigned char ikey[KEY_LEN_BYTES+IV_LEN_BYTES] = { 0 };
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001208 EVP_CIPHER_CTX d_ctx;
1209 int decrypted_len, final_len;
1210
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001211 /* Turn the password into an intermediate key and IV that can decrypt the
1212 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001213 if (kdf(passwd, salt, ikey, kdf_params)) {
1214 SLOGE("kdf failed");
1215 return -1;
1216 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001217
1218 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001219 EVP_CIPHER_CTX_init(&d_ctx);
Greg Kaiserfa099612018-02-14 11:26:00 -08001220 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001221 return -1;
1222 }
1223 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1224 /* Decrypt the master key */
1225 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
Greg Kaiserfa099612018-02-14 11:26:00 -08001226 encrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001227 return -1;
1228 }
Adam Langley889c4f12014-09-03 14:23:13 -07001229 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230 return -1;
1231 }
1232
Greg Kaiserfa099612018-02-14 11:26:00 -08001233 if (decrypted_len + final_len != KEY_LEN_BYTES) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001234 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001235 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001236
1237 /* Copy intermediate key if needed by params */
1238 if (intermediate_key && intermediate_key_size) {
Greg Kaiserfa099612018-02-14 11:26:00 -08001239 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001240 if (*intermediate_key) {
Greg Kaiserfa099612018-02-14 11:26:00 -08001241 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1242 *intermediate_key_size = KEY_LEN_BYTES;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001243 }
1244 }
1245
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001246 EVP_CIPHER_CTX_cleanup(&d_ctx);
1247
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001248 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001249}
1250
Kenny Rootc4c70f12013-06-14 12:11:38 -07001251static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001252{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001253 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001254 *kdf = scrypt_keymaster;
1255 *kdf_params = ftr;
1256 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001257 *kdf = scrypt;
1258 *kdf_params = ftr;
1259 } else {
1260 *kdf = pbkdf2;
1261 *kdf_params = NULL;
1262 }
1263}
1264
Paul Lawrence731a7a22015-04-28 22:14:15 +00001265static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001266 struct crypt_mnt_ftr *crypt_ftr,
1267 unsigned char** intermediate_key,
1268 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001269{
1270 kdf_func kdf;
1271 void *kdf_params;
1272 int ret;
1273
1274 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001275 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1276 decrypted_master_key, kdf, kdf_params,
1277 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001278 if (ret != 0) {
1279 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001280 }
1281
1282 return ret;
1283}
1284
Wei Wang4375f1b2017-02-24 17:43:01 -08001285static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001286 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001287 int fd;
Greg Kaiserfa099612018-02-14 11:26:00 -08001288 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001289
1290 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001291 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001292 read(fd, key_buf, sizeof(key_buf));
1293 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001294 close(fd);
1295
1296 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001297 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001298}
1299
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001300int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001301{
Greg Hackmann955653e2014-09-24 14:55:20 -07001302 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001303#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001304
1305 /* Now umount the tmpfs filesystem */
1306 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001307 if (umount(mountpoint) == 0) {
1308 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001309 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001310
1311 if (errno == EINVAL) {
1312 /* EINVAL is returned if the directory is not a mountpoint,
1313 * i.e. there is no filesystem mounted there. So just get out.
1314 */
1315 break;
1316 }
1317
1318 err = errno;
1319
1320 /* If allowed, be increasingly aggressive before the last two retries */
1321 if (kill) {
1322 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1323 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001324 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001325 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1326 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001327 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001328 }
1329 }
1330
1331 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001332 }
1333
1334 if (i < WAIT_UNMOUNT_COUNT) {
1335 SLOGD("unmounting %s succeeded\n", mountpoint);
1336 rc = 0;
1337 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001338 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001339 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001340 rc = -1;
1341 }
1342
1343 return rc;
1344}
1345
Wei Wang42e38102017-06-07 10:46:12 -07001346static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001347{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001348 // NOTE: post_fs_data results in init calling back around to vold, so all
1349 // callers to this method must be async
1350
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001351 /* Do the prep of the /data filesystem */
1352 property_set("vold.post_fs_data_done", "0");
1353 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001354 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001355
Ken Sumrallc5872692013-05-14 15:26:31 -07001356 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001357 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001358 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001359 std::chrono::seconds(15))) {
1360 /* We timed out to prep /data in time. Continue wait. */
1361 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001362 }
Wei Wang42e38102017-06-07 10:46:12 -07001363 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001364}
1365
Paul Lawrence74f29f12014-08-28 15:54:10 -07001366static void cryptfs_set_corrupt()
1367{
1368 // Mark the footer as bad
1369 struct crypt_mnt_ftr crypt_ftr;
1370 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1371 SLOGE("Failed to get crypto footer - panic");
1372 return;
1373 }
1374
1375 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1376 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1377 SLOGE("Failed to set crypto footer - panic");
1378 return;
1379 }
1380}
1381
1382static void cryptfs_trigger_restart_min_framework()
1383{
1384 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1385 SLOGE("Failed to mount tmpfs on data - panic");
1386 return;
1387 }
1388
1389 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1390 SLOGE("Failed to trigger post fs data - panic");
1391 return;
1392 }
1393
1394 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1395 SLOGE("Failed to trigger restart min framework - panic");
1396 return;
1397 }
1398}
1399
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001400/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001401static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001402{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001403 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001404 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001405 static int restart_successful = 0;
1406
1407 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001408 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001409 SLOGE("Encrypted filesystem not validated, aborting");
1410 return -1;
1411 }
1412
1413 if (restart_successful) {
1414 SLOGE("System already restarted with encrypted disk, aborting");
1415 return -1;
1416 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001417
Paul Lawrencef4faa572014-01-29 13:31:03 -08001418 if (restart_main) {
1419 /* Here is where we shut down the framework. The init scripts
1420 * start all services in one of three classes: core, main or late_start.
1421 * On boot, we start core and main. Now, we stop main, but not core,
1422 * as core includes vold and a few other really important things that
1423 * we need to keep running. Once main has stopped, we should be able
1424 * to umount the tmpfs /data, then mount the encrypted /data.
1425 * We then restart the class main, and also the class late_start.
1426 * At the moment, I've only put a few things in late_start that I know
1427 * are not needed to bring up the framework, and that also cause problems
1428 * with unmounting the tmpfs /data, but I hope to add add more services
1429 * to the late_start class as we optimize this to decrease the delay
1430 * till the user is asked for the password to the filesystem.
1431 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001432
Paul Lawrencef4faa572014-01-29 13:31:03 -08001433 /* The init files are setup to stop the class main when vold.decrypt is
1434 * set to trigger_reset_main.
1435 */
1436 property_set("vold.decrypt", "trigger_reset_main");
1437 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001438
Paul Lawrencef4faa572014-01-29 13:31:03 -08001439 /* Ugh, shutting down the framework is not synchronous, so until it
1440 * can be fixed, this horrible hack will wait a moment for it all to
1441 * shut down before proceeding. Without it, some devices cannot
1442 * restart the graphics services.
1443 */
1444 sleep(2);
1445 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001446
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001447 /* Now that the framework is shutdown, we should be able to umount()
1448 * the tmpfs filesystem, and mount the real one.
1449 */
1450
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001451 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1452 if (strlen(crypto_blkdev) == 0) {
1453 SLOGE("fs_crypto_blkdev not set\n");
1454 return -1;
1455 }
1456
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001457 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001458 /* If ro.crypto.readonly is set to 1, mount the decrypted
1459 * filesystem readonly. This is used when /data is mounted by
1460 * recovery mode.
1461 */
1462 char ro_prop[PROPERTY_VALUE_MAX];
1463 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001464 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001465 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001466 rec->flags |= MS_RDONLY;
1467 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001468
Ken Sumralle5032c42012-04-01 23:58:44 -07001469 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001470 int retries = RETRY_MOUNT_ATTEMPTS;
1471 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001472
1473 /*
1474 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1475 * partitions in the fsck domain.
1476 */
1477 if (setexeccon(secontextFsck())){
1478 SLOGE("Failed to setexeccon");
1479 return -1;
1480 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001481 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001482 crypto_blkdev, 0))
1483 != 0) {
1484 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1485 /* TODO: invoke something similar to
1486 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1487 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1488 SLOGI("Failed to mount %s because it is busy - waiting",
1489 crypto_blkdev);
1490 if (--retries) {
1491 sleep(RETRY_MOUNT_DELAY_SECONDS);
1492 } else {
1493 /* Let's hope that a reboot clears away whatever is keeping
1494 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001495 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001496 }
1497 } else {
1498 SLOGE("Failed to mount decrypted data");
1499 cryptfs_set_corrupt();
1500 cryptfs_trigger_restart_min_framework();
1501 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001502 if (setexeccon(NULL)) {
1503 SLOGE("Failed to setexeccon");
1504 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001505 return -1;
1506 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001507 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001508 if (setexeccon(NULL)) {
1509 SLOGE("Failed to setexeccon");
1510 return -1;
1511 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001512
Ken Sumralle5032c42012-04-01 23:58:44 -07001513 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001514 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001515 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001516
1517 /* startup service classes main and late_start */
1518 property_set("vold.decrypt", "trigger_restart_framework");
1519 SLOGD("Just triggered restart_framework\n");
1520
1521 /* Give it a few moments to get started */
1522 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001523 }
1524
Ken Sumrall0cc16632011-01-18 20:32:26 -08001525 if (rc == 0) {
1526 restart_successful = 1;
1527 }
1528
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001529 return rc;
1530}
1531
Paul Lawrencef4faa572014-01-29 13:31:03 -08001532int cryptfs_restart(void)
1533{
Paul Lawrence05335c32015-03-05 09:46:23 -08001534 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001535 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001536 SLOGE("cryptfs_restart not valid for file encryption:");
1537 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001538 }
1539
Paul Lawrencef4faa572014-01-29 13:31:03 -08001540 /* Call internal implementation forcing a restart of main service group */
1541 return cryptfs_restart_internal(1);
1542}
1543
Wei Wang4375f1b2017-02-24 17:43:01 -08001544static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001545{
1546 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001547 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001548 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001549
1550 property_get("ro.crypto.state", encrypted_state, "");
1551 if (strcmp(encrypted_state, "encrypted") ) {
1552 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001553 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001554 }
1555
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001556 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001557 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001558 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001559 }
1560
Ken Sumrall160b4d62013-04-22 12:15:39 -07001561 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001562 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001563
Ken Sumralle1a45852011-12-14 21:24:27 -08001564 /*
1565 * Only report this error if key_loc is a file and it exists.
1566 * If the device was never encrypted, and /data is not mountable for
1567 * some reason, returning 1 should prevent the UI from presenting the
1568 * a "enter password" screen, or worse, a "press button to wipe the
1569 * device" screen.
1570 */
1571 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1572 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001573 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001574 } else {
1575 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001576 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001577 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001578 }
1579
Paul Lawrence74f29f12014-08-28 15:54:10 -07001580 // Test for possible error flags
1581 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1582 SLOGE("Encryption process is partway completed\n");
1583 return CRYPTO_COMPLETE_PARTIAL;
1584 }
1585
1586 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1587 SLOGE("Encryption process was interrupted but cannot continue\n");
1588 return CRYPTO_COMPLETE_INCONSISTENT;
1589 }
1590
1591 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1592 SLOGE("Encryption is successful but data is corrupt\n");
1593 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001594 }
1595
1596 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001597 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001598}
1599
Paul Lawrencef4faa572014-01-29 13:31:03 -08001600static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001601 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001602{
Greg Kaiser4a35ef02018-02-09 17:01:06 -08001603 unsigned char decrypted_master_key[DECRYPTED_MASTER_KEY_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001604 char crypto_blkdev[MAXPATHLEN];
1605 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001606 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001607 unsigned int orig_failed_decrypt_count;
1608 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001609 int use_keymaster = 0;
1610 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001611 unsigned char* intermediate_key = 0;
1612 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001613 int N = 1 << crypt_ftr->N_factor;
1614 int r = 1 << crypt_ftr->r_factor;
1615 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001616
Paul Lawrencef4faa572014-01-29 13:31:03 -08001617 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1618 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001619
Paul Lawrencef4faa572014-01-29 13:31:03 -08001620 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001621 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1622 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001623 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001624 rc = -1;
1625 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001626 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001627 }
1628
Paul Crowleye2ee1522017-09-26 14:05:26 -07001629 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001630
Paul Lawrence74f29f12014-08-28 15:54:10 -07001631 // Create crypto block device - all (non fatal) code paths
1632 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001633 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1634 SLOGE("Error creating decrypted block device\n");
1635 rc = -1;
1636 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001637 }
1638
Paul Lawrence74f29f12014-08-28 15:54:10 -07001639 /* Work out if the problem is the password or the data */
1640 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1641 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001642
Paul Lawrence74f29f12014-08-28 15:54:10 -07001643 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1644 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1645 N, r, p, scrypted_intermediate_key,
1646 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001647
Paul Lawrence74f29f12014-08-28 15:54:10 -07001648 // Does the key match the crypto footer?
1649 if (rc == 0 && memcmp(scrypted_intermediate_key,
1650 crypt_ftr->scrypted_intermediate_key,
1651 sizeof(scrypted_intermediate_key)) == 0) {
1652 SLOGI("Password matches");
1653 rc = 0;
1654 } else {
1655 /* Try mounting the file system anyway, just in case the problem's with
1656 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001657 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1658 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001659 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001660 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001661 SLOGE("Error temp mounting decrypted block device\n");
1662 delete_crypto_blk_dev(label);
1663
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001664 rc = ++crypt_ftr->failed_decrypt_count;
1665 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001666 } else {
1667 /* Success! */
1668 SLOGI("Password did not match but decrypted drive mounted - continue");
1669 umount(tmp_mount_point);
1670 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001671 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001672 }
1673
1674 if (rc == 0) {
1675 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001676 if (orig_failed_decrypt_count != 0) {
1677 put_crypt_ftr_and_key(crypt_ftr);
1678 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001679
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001680 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001681 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001682 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001683
1684 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001685 * the key when we want to change the password on it. */
Greg Kaiserfa099612018-02-14 11:26:00 -08001686 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001687 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001688 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001689 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001690 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001691
Paul Lawrence74f29f12014-08-28 15:54:10 -07001692 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001693 use_keymaster = keymaster_check_compatibility();
1694 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001695 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001696 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1697 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1698 upgrade = 1;
1699 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001700 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001701 upgrade = 1;
1702 }
1703
1704 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001705 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1706 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001707 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001708 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001709 }
1710 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001711
1712 // Do not fail even if upgrade failed - machine is bootable
1713 // Note that if this code is ever hit, there is a *serious* problem
1714 // since KDFs should never fail. You *must* fix the kdf before
1715 // proceeding!
1716 if (rc) {
1717 SLOGW("Upgrade failed with error %d,"
1718 " but continuing with previous state",
1719 rc);
1720 rc = 0;
1721 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001722 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001723 }
1724
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001725 errout:
1726 if (intermediate_key) {
1727 memset(intermediate_key, 0, intermediate_key_size);
1728 free(intermediate_key);
1729 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001730 return rc;
1731}
1732
Ken Sumrall29d8da82011-05-18 17:20:07 -07001733/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001734 * Called by vold when it's asked to mount an encrypted external
1735 * storage volume. The incoming partition has no crypto header/footer,
1736 * as any metadata is been stored in a separate, small partition.
1737 *
1738 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001739 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001740int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1741 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001742 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001743 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001744 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001745 return -1;
1746 }
1747
1748 unsigned long nr_sec = 0;
1749 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001750 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001751
Ken Sumrall29d8da82011-05-18 17:20:07 -07001752 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001753 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001754 return -1;
1755 }
1756
Jeff Sharkey9c484982015-03-31 10:35:33 -07001757 struct crypt_mnt_ftr ext_crypt_ftr;
1758 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1759 ext_crypt_ftr.fs_size = nr_sec;
1760 ext_crypt_ftr.keysize = keysize;
Greg Kaiserfa099612018-02-14 11:26:00 -08001761 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001762 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001763
Paul Crowley5afbc622017-11-27 09:42:17 -08001764 return create_crypto_blk_dev(
1765 &ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label,
1766 e4crypt_is_native() ? CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE : 0);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001767}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001768
Jeff Sharkey9c484982015-03-31 10:35:33 -07001769/*
1770 * Called by vold when it's asked to unmount an encrypted external
1771 * storage volume.
1772 */
1773int cryptfs_revert_ext_volume(const char* label) {
1774 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001775}
1776
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001777int cryptfs_crypto_complete(void)
1778{
1779 return do_crypto_complete("/data");
1780}
1781
Paul Lawrencef4faa572014-01-29 13:31:03 -08001782int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1783{
1784 char encrypted_state[PROPERTY_VALUE_MAX];
1785 property_get("ro.crypto.state", encrypted_state, "");
1786 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1787 SLOGE("encrypted fs already validated or not running with encryption,"
1788 " aborting");
1789 return -1;
1790 }
1791
1792 if (get_crypt_ftr_and_key(crypt_ftr)) {
1793 SLOGE("Error getting crypt footer and key");
1794 return -1;
1795 }
1796
1797 return 0;
1798}
1799
Wei Wang4375f1b2017-02-24 17:43:01 -08001800int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001801{
Paul Lawrence05335c32015-03-05 09:46:23 -08001802 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001803 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001804 SLOGE("cryptfs_check_passwd not valid for file encryption");
1805 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001806 }
1807
Paul Lawrencef4faa572014-01-29 13:31:03 -08001808 struct crypt_mnt_ftr crypt_ftr;
1809 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001810
Paul Lawrencef4faa572014-01-29 13:31:03 -08001811 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001812 if (rc) {
1813 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001814 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001815 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001816
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001817 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001818 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1819 if (rc) {
1820 SLOGE("Password did not match");
1821 return rc;
1822 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001823
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001824 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1825 // Here we have a default actual password but a real password
1826 // we must test against the scrypted value
1827 // First, we must delete the crypto block device that
1828 // test_mount_encrypted_fs leaves behind as a side effect
1829 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1830 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1831 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1832 if (rc) {
1833 SLOGE("Default password did not match on reboot encryption");
1834 return rc;
1835 }
1836
1837 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1838 put_crypt_ftr_and_key(&crypt_ftr);
1839 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1840 if (rc) {
1841 SLOGE("Could not change password on reboot encryption");
1842 return rc;
1843 }
1844 }
1845
1846 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001847 cryptfs_clear_password();
1848 password = strdup(passwd);
1849 struct timespec now;
1850 clock_gettime(CLOCK_BOOTTIME, &now);
1851 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001852 }
1853
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001854 return rc;
1855}
1856
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001857int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001858{
1859 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser4a35ef02018-02-09 17:01:06 -08001860 unsigned char decrypted_master_key[DECRYPTED_MASTER_KEY_BUF_SIZE];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001861 char encrypted_state[PROPERTY_VALUE_MAX];
1862 int rc;
1863
1864 property_get("ro.crypto.state", encrypted_state, "");
1865 if (strcmp(encrypted_state, "encrypted") ) {
1866 SLOGE("device not encrypted, aborting");
1867 return -2;
1868 }
1869
1870 if (!master_key_saved) {
1871 SLOGE("encrypted fs not yet mounted, aborting");
1872 return -1;
1873 }
1874
1875 if (!saved_mount_point) {
1876 SLOGE("encrypted fs failed to save mount point, aborting");
1877 return -1;
1878 }
1879
Ken Sumrall160b4d62013-04-22 12:15:39 -07001880 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001881 SLOGE("Error getting crypt footer and key\n");
1882 return -1;
1883 }
1884
1885 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1886 /* If the device has no password, then just say the password is valid */
1887 rc = 0;
1888 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001889 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001890 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1891 /* They match, the password is correct */
1892 rc = 0;
1893 } else {
1894 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1895 sleep(1);
1896 rc = 1;
1897 }
1898 }
1899
1900 return rc;
1901}
1902
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiserfa099612018-02-14 11:26:00 -08001904 * defaulted to 16 bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001905 * Presumably, at a minimum, the caller will update the
1906 * filesystem size and crypto_type_name after calling this function.
1907 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001908static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001909{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001910 off64_t off;
1911
1912 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001913 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001914 ftr->major_version = CURRENT_MAJOR_VERSION;
1915 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001916 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiserfa099612018-02-14 11:26:00 -08001917 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001918
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001919 switch (keymaster_check_compatibility()) {
1920 case 1:
1921 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1922 break;
1923
1924 case 0:
1925 ftr->kdf_type = KDF_SCRYPT;
1926 break;
1927
1928 default:
1929 SLOGE("keymaster_check_compatibility failed");
1930 return -1;
1931 }
1932
Kenny Rootc4c70f12013-06-14 12:11:38 -07001933 get_device_scrypt_params(ftr);
1934
Ken Sumrall160b4d62013-04-22 12:15:39 -07001935 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1936 if (get_crypt_ftr_info(NULL, &off) == 0) {
1937 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1938 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1939 ftr->persist_data_size;
1940 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001941
1942 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001943}
1944
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001945#define FRAMEWORK_BOOT_WAIT 60
1946
Paul Lawrence87999172014-02-20 12:21:31 -08001947static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1948{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001949 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001950 if (fd == -1) {
1951 SLOGE("Error opening file %s", filename);
1952 return -1;
1953 }
1954
1955 char block[CRYPT_INPLACE_BUFSIZE];
1956 memset(block, 0, sizeof(block));
1957 if (unix_read(fd, block, sizeof(block)) < 0) {
1958 SLOGE("Error reading file %s", filename);
1959 close(fd);
1960 return -1;
1961 }
1962
1963 close(fd);
1964
1965 SHA256_CTX c;
1966 SHA256_Init(&c);
1967 SHA256_Update(&c, block, sizeof(block));
1968 SHA256_Final(buf, &c);
1969
1970 return 0;
1971}
1972
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001973static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
1974 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08001975 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08001976 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001977
Paul Lawrence87999172014-02-20 12:21:31 -08001978 /* The size of the userdata partition, and add in the vold volumes below */
1979 tot_encryption_size = crypt_ftr->fs_size;
1980
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001981 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08001982 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08001983
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001984 if (rc == ENABLE_INPLACE_ERR_DEV) {
1985 /* Hack for b/17898962 */
1986 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
1987 cryptfs_reboot(RebootType::reboot);
1988 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07001989
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001990 if (!rc) {
1991 crypt_ftr->encrypted_upto = cur_encryption_done;
1992 }
Paul Lawrence87999172014-02-20 12:21:31 -08001993
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001994 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
1995 /* The inplace routine never actually sets the progress to 100% due
1996 * to the round down nature of integer division, so set it here */
1997 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08001998 }
1999
2000 return rc;
2001}
2002
Paul Crowleyb64933a2017-10-31 08:25:55 -07002003static int vold_unmountAll(void) {
2004 VolumeManager* vm = VolumeManager::Instance();
2005 return vm->unmountAll();
2006}
2007
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002008int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002009 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser4a35ef02018-02-09 17:01:06 -08002010 unsigned char decrypted_master_key[DECRYPTED_MASTER_KEY_BUF_SIZE];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002011 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002012 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002013 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002014 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002015 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002016 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002017 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002018 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002019 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002020 bool onlyCreateHeader = false;
2021 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002022
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002023 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002024 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2025 /* An encryption was underway and was interrupted */
2026 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2027 crypt_ftr.encrypted_upto = 0;
2028 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002029
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002030 /* At this point, we are in an inconsistent state. Until we successfully
2031 complete encryption, a reboot will leave us broken. So mark the
2032 encryption failed in case that happens.
2033 On successfully completing encryption, remove this flag */
2034 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002035
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002036 put_crypt_ftr_and_key(&crypt_ftr);
2037 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2038 if (!check_ftr_sha(&crypt_ftr)) {
2039 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2040 put_crypt_ftr_and_key(&crypt_ftr);
2041 goto error_unencrypted;
2042 }
2043
2044 /* Doing a reboot-encryption*/
2045 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2046 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2047 rebootEncryption = true;
2048 }
Paul Lawrence87999172014-02-20 12:21:31 -08002049 }
2050
2051 property_get("ro.crypto.state", encrypted_state, "");
2052 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2053 SLOGE("Device is already running encrypted, aborting");
2054 goto error_unencrypted;
2055 }
2056
2057 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002058 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2059 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002060
Ken Sumrall3ed82362011-01-28 23:31:16 -08002061 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002062 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002063 if (fd == -1) {
2064 SLOGE("Cannot open block device %s\n", real_blkdev);
2065 goto error_unencrypted;
2066 }
2067 unsigned long nr_sec;
2068 get_blkdev_size(fd, &nr_sec);
2069 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002070 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2071 goto error_unencrypted;
2072 }
2073 close(fd);
2074
2075 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002076 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002077 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002078 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002079 if (fs_size_sec == 0)
2080 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2081
Paul Lawrence87999172014-02-20 12:21:31 -08002082 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002083
2084 if (fs_size_sec > max_fs_size_sec) {
2085 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2086 goto error_unencrypted;
2087 }
2088 }
2089
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002090 /* Get a wakelock as this may take a while, and we don't want the
2091 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2092 * wants to keep the screen on, it can grab a full wakelock.
2093 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002094 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002095 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2096
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002097 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002098 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002099 */
2100 property_set("vold.decrypt", "trigger_shutdown_framework");
2101 SLOGD("Just asked init to shut down class main\n");
2102
Jeff Sharkey9c484982015-03-31 10:35:33 -07002103 /* Ask vold to unmount all devices that it manages */
2104 if (vold_unmountAll()) {
2105 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002106 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002107
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002108 /* no_ui means we are being called from init, not settings.
2109 Now we always reboot from settings, so !no_ui means reboot
2110 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002111 if (!no_ui) {
2112 /* Try fallback, which is to reboot and try there */
2113 onlyCreateHeader = true;
2114 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2115 if (breadcrumb == 0) {
2116 SLOGE("Failed to create breadcrumb file");
2117 goto error_shutting_down;
2118 }
2119 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002120 }
2121
2122 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002123 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002124 /* Now that /data is unmounted, we need to mount a tmpfs
2125 * /data, set a property saying we're doing inplace encryption,
2126 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002127 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002128 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002129 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002130 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002131 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002132 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002133
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002134 /* restart the framework. */
2135 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002136 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002137
Ken Sumrall92736ef2012-10-17 20:57:14 -07002138 /* Ugh, shutting down the framework is not synchronous, so until it
2139 * can be fixed, this horrible hack will wait a moment for it all to
2140 * shut down before proceeding. Without it, some devices cannot
2141 * restart the graphics services.
2142 */
2143 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002144 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002145
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002146 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002147 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002148 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002149 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2150 goto error_shutting_down;
2151 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002152
Paul Lawrence87999172014-02-20 12:21:31 -08002153 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2154 crypt_ftr.fs_size = nr_sec
2155 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2156 } else {
2157 crypt_ftr.fs_size = nr_sec;
2158 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002159 /* At this point, we are in an inconsistent state. Until we successfully
2160 complete encryption, a reboot will leave us broken. So mark the
2161 encryption failed in case that happens.
2162 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002163 if (onlyCreateHeader) {
2164 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2165 } else {
2166 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2167 }
Paul Lawrence87999172014-02-20 12:21:31 -08002168 crypt_ftr.crypt_type = crypt_type;
Greg Kaiserfa099612018-02-14 11:26:00 -08002169 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002170
Paul Lawrence87999172014-02-20 12:21:31 -08002171 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002172 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2173 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002174 SLOGE("Cannot create encrypted master key\n");
2175 goto error_shutting_down;
2176 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002177
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002178 /* Replace scrypted intermediate key if we are preparing for a reboot */
2179 if (onlyCreateHeader) {
Greg Kaiserfa099612018-02-14 11:26:00 -08002180 unsigned char fake_master_key[KEY_LEN_BYTES];
2181 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002182 memset(fake_master_key, 0, sizeof(fake_master_key));
2183 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2184 encrypted_fake_master_key, &crypt_ftr);
2185 }
2186
Paul Lawrence87999172014-02-20 12:21:31 -08002187 /* Write the key to the end of the partition */
2188 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002189
Paul Lawrence87999172014-02-20 12:21:31 -08002190 /* If any persistent data has been remembered, save it.
2191 * If none, create a valid empty table and save that.
2192 */
2193 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002194 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002195 if (pdata) {
2196 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2197 persist_data = pdata;
2198 }
2199 }
2200 if (persist_data) {
2201 save_persistent_data();
2202 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002203 }
2204
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002205 if (onlyCreateHeader) {
2206 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002207 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002208 }
2209
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002210 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002211 /* startup service classes main and late_start */
2212 property_set("vold.decrypt", "trigger_restart_min_framework");
2213 SLOGD("Just triggered restart_min_framework\n");
2214
2215 /* OK, the framework is restarted and will soon be showing a
2216 * progress bar. Time to setup an encrypted mapping, and
2217 * either write a new filesystem, or encrypt in place updating
2218 * the progress bar as we work.
2219 */
2220 }
2221
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002222 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002223 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002224 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002225
Paul Lawrence87999172014-02-20 12:21:31 -08002226 /* If we are continuing, check checksums match */
2227 rc = 0;
2228 if (previously_encrypted_upto) {
2229 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2230 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002231
Paul Lawrence87999172014-02-20 12:21:31 -08002232 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2233 sizeof(hash_first_block)) != 0) {
2234 SLOGE("Checksums do not match - trigger wipe");
2235 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002236 }
2237 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002238
Paul Lawrence87999172014-02-20 12:21:31 -08002239 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002240 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002241 previously_encrypted_upto);
2242 }
2243
2244 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002245 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002246 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2247 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002248 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002249 SLOGE("Error calculating checksum for continuing encryption");
2250 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002251 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002252 }
2253
2254 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002255 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002256
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002257 if (! rc) {
2258 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002259 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002260
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002261 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002262 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2263 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002264 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002265 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002266
Paul Lawrence6bfed202014-07-28 12:47:22 -07002267 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002268
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002269 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2270 char value[PROPERTY_VALUE_MAX];
2271 property_get("ro.crypto.state", value, "");
2272 if (!strcmp(value, "")) {
2273 /* default encryption - continue first boot sequence */
2274 property_set("ro.crypto.state", "encrypted");
2275 property_set("ro.crypto.type", "block");
2276 release_wake_lock(lockid);
2277 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2278 // Bring up cryptkeeper that will check the password and set it
2279 property_set("vold.decrypt", "trigger_shutdown_framework");
2280 sleep(2);
2281 property_set("vold.encrypt_progress", "");
2282 cryptfs_trigger_restart_min_framework();
2283 } else {
2284 cryptfs_check_passwd(DEFAULT_PASSWORD);
2285 cryptfs_restart_internal(1);
2286 }
2287 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002288 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002289 sleep(2); /* Give the UI a chance to show 100% progress */
2290 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002291 }
Paul Lawrence87999172014-02-20 12:21:31 -08002292 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002293 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002294 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002295 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002296 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002297 char value[PROPERTY_VALUE_MAX];
2298
Ken Sumrall319369a2012-06-27 16:30:18 -07002299 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002300 if (!strcmp(value, "1")) {
2301 /* wipe data if encryption failed */
2302 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002303 std::string err;
2304 const std::vector<std::string> options = {
2305 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2306 };
2307 if (!write_bootloader_message(options, &err)) {
2308 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002309 }
Josh Gaofec44372017-08-28 13:22:55 -07002310 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002311 } else {
2312 /* set property to trigger dialog */
2313 property_set("vold.encrypt_progress", "error_partially_encrypted");
2314 release_wake_lock(lockid);
2315 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002316 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002317 }
2318
Ken Sumrall3ed82362011-01-28 23:31:16 -08002319 /* hrm, the encrypt step claims success, but the reboot failed.
2320 * This should not happen.
2321 * Set the property and return. Hope the framework can deal with it.
2322 */
2323 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002324 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002325 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002326
2327error_unencrypted:
2328 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002329 if (lockid[0]) {
2330 release_wake_lock(lockid);
2331 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002332 return -1;
2333
2334error_shutting_down:
2335 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2336 * but the framework is stopped and not restarted to show the error, so it's up to
2337 * vold to restart the system.
2338 */
2339 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002340 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002341
2342 /* shouldn't get here */
2343 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002344 if (lockid[0]) {
2345 release_wake_lock(lockid);
2346 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002347 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002348}
2349
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002350int cryptfs_enable(int type, const char* passwd, int no_ui) {
2351 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002352}
2353
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002354int cryptfs_enable_default(int no_ui) {
2355 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002356}
2357
2358int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002359{
Paul Crowley38132a12016-02-09 09:50:32 +00002360 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002361 SLOGE("cryptfs_changepw not valid for file encryption");
2362 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002363 }
2364
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002365 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002366 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002367
2368 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002369 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002370 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002371 return -1;
2372 }
2373
Paul Lawrencef4faa572014-01-29 13:31:03 -08002374 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2375 SLOGE("Invalid crypt_type %d", crypt_type);
2376 return -1;
2377 }
2378
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002379 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002380 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002381 SLOGE("Error getting crypt footer and key");
2382 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002383 }
2384
Paul Lawrencef4faa572014-01-29 13:31:03 -08002385 crypt_ftr.crypt_type = crypt_type;
2386
JP Abgrall933216c2015-02-11 13:44:32 -08002387 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002388 : newpw,
2389 crypt_ftr.salt,
2390 saved_master_key,
2391 crypt_ftr.master_key,
2392 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002393 if (rc) {
2394 SLOGE("Encrypt master key failed: %d", rc);
2395 return -1;
2396 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002397 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002398 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002399
2400 return 0;
2401}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002402
Rubin Xu85c01f92014-10-13 12:49:54 +01002403static unsigned int persist_get_max_entries(int encrypted) {
2404 struct crypt_mnt_ftr crypt_ftr;
2405 unsigned int dsize;
2406 unsigned int max_persistent_entries;
2407
2408 /* If encrypted, use the values from the crypt_ftr, otherwise
2409 * use the values for the current spec.
2410 */
2411 if (encrypted) {
2412 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2413 return -1;
2414 }
2415 dsize = crypt_ftr.persist_data_size;
2416 } else {
2417 dsize = CRYPT_PERSIST_DATA_SIZE;
2418 }
2419
2420 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2421 sizeof(struct crypt_persist_entry);
2422
2423 return max_persistent_entries;
2424}
2425
2426static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002427{
2428 unsigned int i;
2429
2430 if (persist_data == NULL) {
2431 return -1;
2432 }
2433 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2434 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2435 /* We found it! */
2436 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2437 return 0;
2438 }
2439 }
2440
2441 return -1;
2442}
2443
Rubin Xu85c01f92014-10-13 12:49:54 +01002444static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002445{
2446 unsigned int i;
2447 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002448 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002449
2450 if (persist_data == NULL) {
2451 return -1;
2452 }
2453
Rubin Xu85c01f92014-10-13 12:49:54 +01002454 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002455
2456 num = persist_data->persist_valid_entries;
2457
2458 for (i = 0; i < num; i++) {
2459 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2460 /* We found an existing entry, update it! */
2461 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2462 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2463 return 0;
2464 }
2465 }
2466
2467 /* We didn't find it, add it to the end, if there is room */
2468 if (persist_data->persist_valid_entries < max_persistent_entries) {
2469 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2470 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2471 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2472 persist_data->persist_valid_entries++;
2473 return 0;
2474 }
2475
2476 return -1;
2477}
2478
Rubin Xu85c01f92014-10-13 12:49:54 +01002479/**
2480 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2481 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2482 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002483int match_multi_entry(const char *key, const char *field, unsigned index) {
2484 std::string key_ = key;
2485 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002486
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002487 std::string parsed_field;
2488 unsigned parsed_index;
2489
2490 std::string::size_type split = key_.find_last_of('_');
2491 if (split == std::string::npos) {
2492 parsed_field = key_;
2493 parsed_index = 0;
2494 } else {
2495 parsed_field = key_.substr(0, split);
2496 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002497 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002498
2499 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002500}
2501
2502/*
2503 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2504 * remaining entries starting from index will be deleted.
2505 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2506 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2507 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2508 *
2509 */
2510static int persist_del_keys(const char *fieldname, unsigned index)
2511{
2512 unsigned int i;
2513 unsigned int j;
2514 unsigned int num;
2515
2516 if (persist_data == NULL) {
2517 return PERSIST_DEL_KEY_ERROR_OTHER;
2518 }
2519
2520 num = persist_data->persist_valid_entries;
2521
2522 j = 0; // points to the end of non-deleted entries.
2523 // Filter out to-be-deleted entries in place.
2524 for (i = 0; i < num; i++) {
2525 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2526 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2527 j++;
2528 }
2529 }
2530
2531 if (j < num) {
2532 persist_data->persist_valid_entries = j;
2533 // Zeroise the remaining entries
2534 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2535 return PERSIST_DEL_KEY_OK;
2536 } else {
2537 // Did not find an entry matching the given fieldname
2538 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2539 }
2540}
2541
2542static int persist_count_keys(const char *fieldname)
2543{
2544 unsigned int i;
2545 unsigned int count;
2546
2547 if (persist_data == NULL) {
2548 return -1;
2549 }
2550
2551 count = 0;
2552 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2553 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2554 count++;
2555 }
2556 }
2557
2558 return count;
2559}
2560
Ken Sumrall160b4d62013-04-22 12:15:39 -07002561/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002562int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002563{
Paul Crowley38132a12016-02-09 09:50:32 +00002564 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002565 SLOGE("Cannot get field when file encrypted");
2566 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002567 }
2568
Ken Sumrall160b4d62013-04-22 12:15:39 -07002569 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002570 /* CRYPTO_GETFIELD_OK is success,
2571 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2572 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2573 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002574 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002575 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2576 int i;
2577 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002578
2579 if (persist_data == NULL) {
2580 load_persistent_data();
2581 if (persist_data == NULL) {
2582 SLOGE("Getfield error, cannot load persistent data");
2583 goto out;
2584 }
2585 }
2586
Rubin Xu85c01f92014-10-13 12:49:54 +01002587 // Read value from persistent entries. If the original value is split into multiple entries,
2588 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002589 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002590 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2591 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2592 // value too small
2593 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2594 goto out;
2595 }
2596 rc = CRYPTO_GETFIELD_OK;
2597
2598 for (i = 1; /* break explicitly */; i++) {
2599 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2600 (int) sizeof(temp_field)) {
2601 // If the fieldname is very long, we stop as soon as it begins to overflow the
2602 // maximum field length. At this point we have in fact fully read out the original
2603 // value because cryptfs_setfield would not allow fields with longer names to be
2604 // written in the first place.
2605 break;
2606 }
2607 if (!persist_get_key(temp_field, temp_value)) {
2608 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2609 // value too small.
2610 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2611 goto out;
2612 }
2613 } else {
2614 // Exhaust all entries.
2615 break;
2616 }
2617 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002618 } else {
2619 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002620 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002621 }
2622
2623out:
2624 return rc;
2625}
2626
2627/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002628int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002629{
Paul Crowley38132a12016-02-09 09:50:32 +00002630 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002631 SLOGE("Cannot set field when file encrypted");
2632 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002633 }
2634
Ken Sumrall160b4d62013-04-22 12:15:39 -07002635 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002636 /* 0 is success, negative values are error */
2637 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002638 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002639 unsigned int field_id;
2640 char temp_field[PROPERTY_KEY_MAX];
2641 unsigned int num_entries;
2642 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002643
2644 if (persist_data == NULL) {
2645 load_persistent_data();
2646 if (persist_data == NULL) {
2647 SLOGE("Setfield error, cannot load persistent data");
2648 goto out;
2649 }
2650 }
2651
2652 property_get("ro.crypto.state", encrypted_state, "");
2653 if (!strcmp(encrypted_state, "encrypted") ) {
2654 encrypted = 1;
2655 }
2656
Rubin Xu85c01f92014-10-13 12:49:54 +01002657 // Compute the number of entries required to store value, each entry can store up to
2658 // (PROPERTY_VALUE_MAX - 1) chars
2659 if (strlen(value) == 0) {
2660 // Empty value also needs one entry to store.
2661 num_entries = 1;
2662 } else {
2663 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2664 }
2665
2666 max_keylen = strlen(fieldname);
2667 if (num_entries > 1) {
2668 // Need an extra "_%d" suffix.
2669 max_keylen += 1 + log10(num_entries);
2670 }
2671 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2672 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002673 goto out;
2674 }
2675
Rubin Xu85c01f92014-10-13 12:49:54 +01002676 // Make sure we have enough space to write the new value
2677 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2678 persist_get_max_entries(encrypted)) {
2679 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2680 goto out;
2681 }
2682
2683 // Now that we know persist_data has enough space for value, let's delete the old field first
2684 // to make up space.
2685 persist_del_keys(fieldname, 0);
2686
2687 if (persist_set_key(fieldname, value, encrypted)) {
2688 // fail to set key, should not happen as we have already checked the available space
2689 SLOGE("persist_set_key() error during setfield()");
2690 goto out;
2691 }
2692
2693 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002694 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002695
2696 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2697 // fail to set key, should not happen as we have already checked the available space.
2698 SLOGE("persist_set_key() error during setfield()");
2699 goto out;
2700 }
2701 }
2702
Ken Sumrall160b4d62013-04-22 12:15:39 -07002703 /* If we are running encrypted, save the persistent data now */
2704 if (encrypted) {
2705 if (save_persistent_data()) {
2706 SLOGE("Setfield error, cannot save persistent data");
2707 goto out;
2708 }
2709 }
2710
Rubin Xu85c01f92014-10-13 12:49:54 +01002711 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002712
2713out:
2714 return rc;
2715}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002716
2717/* Checks userdata. Attempt to mount the volume if default-
2718 * encrypted.
2719 * On success trigger next init phase and return 0.
2720 * Currently do not handle failure - see TODO below.
2721 */
2722int cryptfs_mount_default_encrypted(void)
2723{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002724 int crypt_type = cryptfs_get_password_type();
2725 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2726 SLOGE("Bad crypt type - error");
2727 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2728 SLOGD("Password is not default - "
2729 "starting min framework to prompt");
2730 property_set("vold.decrypt", "trigger_restart_min_framework");
2731 return 0;
2732 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2733 SLOGD("Password is default - restarting filesystem");
2734 cryptfs_restart_internal(0);
2735 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002736 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002737 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002738 }
2739
Paul Lawrence6bfed202014-07-28 12:47:22 -07002740 /** Corrupt. Allow us to boot into framework, which will detect bad
2741 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002742 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002743 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002744 return 0;
2745}
2746
2747/* Returns type of the password, default, pattern, pin or password.
2748 */
2749int cryptfs_get_password_type(void)
2750{
Paul Crowley38132a12016-02-09 09:50:32 +00002751 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002752 SLOGE("cryptfs_get_password_type not valid for file encryption");
2753 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002754 }
2755
Paul Lawrencef4faa572014-01-29 13:31:03 -08002756 struct crypt_mnt_ftr crypt_ftr;
2757
2758 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2759 SLOGE("Error getting crypt footer and key\n");
2760 return -1;
2761 }
2762
Paul Lawrence6bfed202014-07-28 12:47:22 -07002763 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2764 return -1;
2765 }
2766
Paul Lawrencef4faa572014-01-29 13:31:03 -08002767 return crypt_ftr.crypt_type;
2768}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002769
Paul Lawrence05335c32015-03-05 09:46:23 -08002770const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002771{
Paul Crowley38132a12016-02-09 09:50:32 +00002772 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002773 SLOGE("cryptfs_get_password not valid for file encryption");
2774 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002775 }
2776
Paul Lawrence399317e2014-03-10 13:20:50 -07002777 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002778 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002779 if (now.tv_sec < password_expiry_time) {
2780 return password;
2781 } else {
2782 cryptfs_clear_password();
2783 return 0;
2784 }
2785}
2786
2787void cryptfs_clear_password()
2788{
2789 if (password) {
2790 size_t len = strlen(password);
2791 memset(password, 0, len);
2792 free(password);
2793 password = 0;
2794 password_expiry_time = 0;
2795 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002796}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002797
Paul Lawrence0c247462015-10-29 10:30:57 -07002798int cryptfs_isConvertibleToFBE()
2799{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002800 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002801 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2802}