blob: 132b31f5cb619c9751dc2e5bb6a1f6b0d5df1352 [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>
Tao Bao5a95ddb2016-10-05 18:01:19 -070041#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080046#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080047#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080048#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080049#define LOG_TAG "Cryptfs"
50#include "cutils/log.h"
51#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070052#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080053#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070054#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000055#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070056#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070057#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000058#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000059#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080060#include "CheckBattery.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070061#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080062#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000063#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080064#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070065#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080066extern "C" {
67#include <crypto_scrypt.h>
68}
Mark Salyzyn3e971272014-01-21 13:27:04 -080069
Mark Salyzyn5eecc442014-02-12 14:16:14 -080070#define UNUSED __attribute__((unused))
71
Ken Sumrall8f869aa2010-12-03 03:47:09 -080072#define DM_CRYPT_BUF_SIZE 4096
73
Jason parks70a4b3f2011-01-28 10:10:47 -060074#define HASH_COUNT 2000
75#define KEY_LEN_BYTES 16
76#define IV_LEN_BYTES 16
77
Ken Sumrall29d8da82011-05-18 17:20:07 -070078#define KEY_IN_FOOTER "footer"
79
Paul Lawrence3bd36d52015-06-09 13:37:44 -070080#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080081
Paul Lawrence3d99eba2015-11-20 07:07:19 -080082#define CRYPTO_BLOCK_DEVICE "userdata"
83
84#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
85
Ken Sumrall29d8da82011-05-18 17:20:07 -070086#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070087#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070088
Ken Sumralle919efe2012-09-29 17:07:41 -070089#define TABLE_LOAD_RETRIES 10
90
Shawn Willden47ba10d2014-09-03 17:07:06 -060091#define RSA_KEY_SIZE 2048
92#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
93#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060094#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070095
Paul Lawrence8e3f4512014-09-08 10:11:17 -070096#define RETRY_MOUNT_ATTEMPTS 10
97#define RETRY_MOUNT_DELAY_SECONDS 1
98
Jason parks70a4b3f2011-01-28 10:10:47 -060099static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700100static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600101static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700102static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800103
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700104/* Should we use keymaster? */
105static int keymaster_check_compatibility()
106{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000107 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700108}
109
110/* Create a new keymaster key and store it in this footer */
111static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
112{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800113 if (ftr->keymaster_blob_size) {
114 SLOGI("Already have key");
115 return 0;
116 }
117
Janis Danisevskis015ec302017-01-31 11:31:08 +0000118 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
119 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
120 &ftr->keymaster_blob_size);
121 if (rc) {
122 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
123 SLOGE("Keymaster key blob to large)");
124 ftr->keymaster_blob_size = 0;
125 }
126 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700127 return -1;
128 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000129 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700130}
131
Shawn Willdene17a9c42014-09-08 13:04:08 -0600132/* This signs the given object using the keymaster key. */
133static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600134 const unsigned char *object,
135 const size_t object_size,
136 unsigned char **signature,
137 size_t *signature_size)
138{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600139 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600140 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600141 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600142
Shawn Willdene17a9c42014-09-08 13:04:08 -0600143 // To sign a message with RSA, the message must satisfy two
144 // constraints:
145 //
146 // 1. The message, when interpreted as a big-endian numeric value, must
147 // be strictly less than the public modulus of the RSA key. Note
148 // that because the most significant bit of the public modulus is
149 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
150 // key), an n-bit message with most significant bit 0 always
151 // satisfies this requirement.
152 //
153 // 2. The message must have the same length in bits as the public
154 // modulus of the RSA key. This requirement isn't mathematically
155 // necessary, but is necessary to ensure consistency in
156 // implementations.
157 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600158 case KDF_SCRYPT_KEYMASTER:
159 // This ensures the most significant byte of the signed message
160 // is zero. We could have zero-padded to the left instead, but
161 // this approach is slightly more robust against changes in
162 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600163 // so) because we really should be using a proper deterministic
164 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800165 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600166 SLOGI("Signing safely-padded object");
167 break;
168 default:
169 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000170 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600171 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000172 return keymaster_sign_object_for_cryptfs_scrypt(ftr->keymaster_blob, ftr->keymaster_blob_size,
173 KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign, to_sign_size, signature, signature_size);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600174}
175
Paul Lawrence399317e2014-03-10 13:20:50 -0700176/* Store password when userdata is successfully decrypted and mounted.
177 * Cleared by cryptfs_clear_password
178 *
179 * To avoid a double prompt at boot, we need to store the CryptKeeper
180 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
181 * Since the entire framework is torn down and rebuilt after encryption,
182 * we have to use a daemon or similar to store the password. Since vold
183 * is secured against IPC except from system processes, it seems a reasonable
184 * place to store this.
185 *
186 * password should be cleared once it has been used.
187 *
188 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800189 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700190static char* password = 0;
191static int password_expiry_time = 0;
192static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800193
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800194extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800195
Josh Gaofec44372017-08-28 13:22:55 -0700196enum class RebootType {reboot, recovery, shutdown};
197static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700198{
Josh Gaofec44372017-08-28 13:22:55 -0700199 switch (rt) {
200 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800201 property_set(ANDROID_RB_PROPERTY, "reboot");
202 break;
203
Josh Gaofec44372017-08-28 13:22:55 -0700204 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800205 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
206 break;
207
Josh Gaofec44372017-08-28 13:22:55 -0700208 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800209 property_set(ANDROID_RB_PROPERTY, "shutdown");
210 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700211 }
Paul Lawrence87999172014-02-20 12:21:31 -0800212
Ken Sumralladfba362013-06-04 16:37:52 -0700213 sleep(20);
214
215 /* Shouldn't get here, reboot should happen before sleep times out */
216 return;
217}
218
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800219static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
220{
221 memset(io, 0, dataSize);
222 io->data_size = dataSize;
223 io->data_start = sizeof(struct dm_ioctl);
224 io->version[0] = 4;
225 io->version[1] = 0;
226 io->version[2] = 0;
227 io->flags = flags;
228 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100229 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800230 }
231}
232
Kenny Rootc4c70f12013-06-14 12:11:38 -0700233/**
234 * Gets the default device scrypt parameters for key derivation time tuning.
235 * The parameters should lead to about one second derivation time for the
236 * given device.
237 */
238static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700239 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000240 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700241
Paul Crowley63c18d32016-02-10 14:02:47 +0000242 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
243 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
244 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
245 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700246 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000247 ftr->N_factor = Nf;
248 ftr->r_factor = rf;
249 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700250}
251
Ken Sumrall3ed82362011-01-28 23:31:16 -0800252static unsigned int get_fs_size(char *dev)
253{
254 int fd, block_size;
255 struct ext4_super_block sb;
256 off64_t len;
257
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700258 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800259 SLOGE("Cannot open device to get filesystem size ");
260 return 0;
261 }
262
263 if (lseek64(fd, 1024, SEEK_SET) < 0) {
264 SLOGE("Cannot seek to superblock");
265 return 0;
266 }
267
268 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
269 SLOGE("Cannot read superblock");
270 return 0;
271 }
272
273 close(fd);
274
Daniel Rosenberge82df162014-08-15 22:19:23 +0000275 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
276 SLOGE("Not a valid ext4 superblock");
277 return 0;
278 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800279 block_size = 1024 << sb.s_log_block_size;
280 /* compute length in bytes */
281 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
282
283 /* return length in sectors */
284 return (unsigned int) (len / 512);
285}
286
Ken Sumrall160b4d62013-04-22 12:15:39 -0700287static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
288{
289 static int cached_data = 0;
290 static off64_t cached_off = 0;
291 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
292 int fd;
293 char key_loc[PROPERTY_VALUE_MAX];
294 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700295 int rc = -1;
296
297 if (!cached_data) {
298 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
299
300 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700301 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700302 SLOGE("Cannot open real block device %s\n", real_blkdev);
303 return -1;
304 }
305
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900306 unsigned long nr_sec = 0;
307 get_blkdev_size(fd, &nr_sec);
308 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700309 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
310 * encryption info footer and key, and plenty of bytes to spare for future
311 * growth.
312 */
313 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
314 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
315 cached_data = 1;
316 } else {
317 SLOGE("Cannot get size of block device %s\n", real_blkdev);
318 }
319 close(fd);
320 } else {
321 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
322 cached_off = 0;
323 cached_data = 1;
324 }
325 }
326
327 if (cached_data) {
328 if (metadata_fname) {
329 *metadata_fname = cached_metadata_fname;
330 }
331 if (off) {
332 *off = cached_off;
333 }
334 rc = 0;
335 }
336
337 return rc;
338}
339
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800340/* Set sha256 checksum in structure */
341static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
342{
343 SHA256_CTX c;
344 SHA256_Init(&c);
345 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
346 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
347 SHA256_Final(crypt_ftr->sha256, &c);
348}
349
Ken Sumralle8744072011-01-18 22:01:55 -0800350/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800351 * update the failed mount count but not change the key.
352 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700353static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800354{
355 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800356 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700357 /* starting_off is set to the SEEK_SET offset
358 * where the crypto structure starts
359 */
360 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800361 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700362 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700363 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800364
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800365 set_ftr_sha(crypt_ftr);
366
Ken Sumrall160b4d62013-04-22 12:15:39 -0700367 if (get_crypt_ftr_info(&fname, &starting_off)) {
368 SLOGE("Unable to get crypt_ftr_info\n");
369 return -1;
370 }
371 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700372 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700373 return -1;
374 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700375 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700376 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700377 return -1;
378 }
379
380 /* Seek to the start of the crypt footer */
381 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
382 SLOGE("Cannot seek to real block device footer\n");
383 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800384 }
385
386 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
387 SLOGE("Cannot write real block device footer\n");
388 goto errout;
389 }
390
Ken Sumrall3be890f2011-09-14 16:53:46 -0700391 fstat(fd, &statbuf);
392 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700393 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700394 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800395 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800396 goto errout;
397 }
398 }
399
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800400 /* Success! */
401 rc = 0;
402
403errout:
404 close(fd);
405 return rc;
406
407}
408
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800409static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
410{
411 struct crypt_mnt_ftr copy;
412 memcpy(&copy, crypt_ftr, sizeof(copy));
413 set_ftr_sha(&copy);
414 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
415}
416
Ken Sumrall160b4d62013-04-22 12:15:39 -0700417static inline int unix_read(int fd, void* buff, int len)
418{
419 return TEMP_FAILURE_RETRY(read(fd, buff, len));
420}
421
422static inline int unix_write(int fd, const void* buff, int len)
423{
424 return TEMP_FAILURE_RETRY(write(fd, buff, len));
425}
426
427static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
428{
429 memset(pdata, 0, len);
430 pdata->persist_magic = PERSIST_DATA_MAGIC;
431 pdata->persist_valid_entries = 0;
432}
433
434/* A routine to update the passed in crypt_ftr to the lastest version.
435 * fd is open read/write on the device that holds the crypto footer and persistent
436 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
437 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
438 */
439static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
440{
Kenny Root7434b312013-06-14 11:29:53 -0700441 int orig_major = crypt_ftr->major_version;
442 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700443
Kenny Root7434b312013-06-14 11:29:53 -0700444 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
445 struct crypt_persist_data *pdata;
446 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700447
Kenny Rootc4c70f12013-06-14 12:11:38 -0700448 SLOGW("upgrading crypto footer to 1.1");
449
Wei Wang4375f1b2017-02-24 17:43:01 -0800450 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700451 if (pdata == NULL) {
452 SLOGE("Cannot allocate persisent data\n");
453 return;
454 }
455 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
456
457 /* Need to initialize the persistent data area */
458 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
459 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100460 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700461 return;
462 }
463 /* Write all zeros to the first copy, making it invalid */
464 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
465
466 /* Write a valid but empty structure to the second copy */
467 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
468 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
469
470 /* Update the footer */
471 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
472 crypt_ftr->persist_data_offset[0] = pdata_offset;
473 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
474 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100475 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700476 }
477
Paul Lawrencef4faa572014-01-29 13:31:03 -0800478 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700479 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800480 /* But keep the old kdf_type.
481 * It will get updated later to KDF_SCRYPT after the password has been verified.
482 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700483 crypt_ftr->kdf_type = KDF_PBKDF2;
484 get_device_scrypt_params(crypt_ftr);
485 crypt_ftr->minor_version = 2;
486 }
487
Paul Lawrencef4faa572014-01-29 13:31:03 -0800488 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
489 SLOGW("upgrading crypto footer to 1.3");
490 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
491 crypt_ftr->minor_version = 3;
492 }
493
Kenny Root7434b312013-06-14 11:29:53 -0700494 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
495 if (lseek64(fd, offset, SEEK_SET) == -1) {
496 SLOGE("Cannot seek to crypt footer\n");
497 return;
498 }
499 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700500 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700501}
502
503
504static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800505{
506 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800507 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700508 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800509 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700510 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700511 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800512
Ken Sumrall160b4d62013-04-22 12:15:39 -0700513 if (get_crypt_ftr_info(&fname, &starting_off)) {
514 SLOGE("Unable to get crypt_ftr_info\n");
515 return -1;
516 }
517 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700518 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700519 return -1;
520 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700521 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700522 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700523 return -1;
524 }
525
526 /* Make sure it's 16 Kbytes in length */
527 fstat(fd, &statbuf);
528 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
529 SLOGE("footer file %s is not the expected size!\n", fname);
530 goto errout;
531 }
532
533 /* Seek to the start of the crypt footer */
534 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
535 SLOGE("Cannot seek to real block device footer\n");
536 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800537 }
538
539 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
540 SLOGE("Cannot read real block device footer\n");
541 goto errout;
542 }
543
544 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700545 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800546 goto errout;
547 }
548
Kenny Rootc96a5f82013-06-14 12:08:28 -0700549 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
550 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
551 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800552 goto errout;
553 }
554
Kenny Rootc96a5f82013-06-14 12:08:28 -0700555 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
556 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
557 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800558 }
559
Ken Sumrall160b4d62013-04-22 12:15:39 -0700560 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
561 * copy on disk before returning.
562 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700563 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700564 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800565 }
566
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800567 /* Success! */
568 rc = 0;
569
570errout:
571 close(fd);
572 return rc;
573}
574
Ken Sumrall160b4d62013-04-22 12:15:39 -0700575static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
576{
577 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
578 crypt_ftr->persist_data_offset[1]) {
579 SLOGE("Crypt_ftr persist data regions overlap");
580 return -1;
581 }
582
583 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
584 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
585 return -1;
586 }
587
588 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
589 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
590 CRYPT_FOOTER_OFFSET) {
591 SLOGE("Persistent data extends past crypto footer");
592 return -1;
593 }
594
595 return 0;
596}
597
598static int load_persistent_data(void)
599{
600 struct crypt_mnt_ftr crypt_ftr;
601 struct crypt_persist_data *pdata = NULL;
602 char encrypted_state[PROPERTY_VALUE_MAX];
603 char *fname;
604 int found = 0;
605 int fd;
606 int ret;
607 int i;
608
609 if (persist_data) {
610 /* Nothing to do, we've already loaded or initialized it */
611 return 0;
612 }
613
614
615 /* If not encrypted, just allocate an empty table and initialize it */
616 property_get("ro.crypto.state", encrypted_state, "");
617 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800618 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619 if (pdata) {
620 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
621 persist_data = pdata;
622 return 0;
623 }
624 return -1;
625 }
626
627 if(get_crypt_ftr_and_key(&crypt_ftr)) {
628 return -1;
629 }
630
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700631 if ((crypt_ftr.major_version < 1)
632 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700633 SLOGE("Crypt_ftr version doesn't support persistent data");
634 return -1;
635 }
636
637 if (get_crypt_ftr_info(&fname, NULL)) {
638 return -1;
639 }
640
641 ret = validate_persistent_data_storage(&crypt_ftr);
642 if (ret) {
643 return -1;
644 }
645
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700646 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700647 if (fd < 0) {
648 SLOGE("Cannot open %s metadata file", fname);
649 return -1;
650 }
651
Wei Wang4375f1b2017-02-24 17:43:01 -0800652 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800653 if (pdata == NULL) {
654 SLOGE("Cannot allocate memory for persistent data");
655 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700656 }
657
658 for (i = 0; i < 2; i++) {
659 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
660 SLOGE("Cannot seek to read persistent data on %s", fname);
661 goto err2;
662 }
663 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
664 SLOGE("Error reading persistent data on iteration %d", i);
665 goto err2;
666 }
667 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
668 found = 1;
669 break;
670 }
671 }
672
673 if (!found) {
674 SLOGI("Could not find valid persistent data, creating");
675 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
676 }
677
678 /* Success */
679 persist_data = pdata;
680 close(fd);
681 return 0;
682
683err2:
684 free(pdata);
685
686err:
687 close(fd);
688 return -1;
689}
690
691static int save_persistent_data(void)
692{
693 struct crypt_mnt_ftr crypt_ftr;
694 struct crypt_persist_data *pdata;
695 char *fname;
696 off64_t write_offset;
697 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700698 int fd;
699 int ret;
700
701 if (persist_data == NULL) {
702 SLOGE("No persistent data to save");
703 return -1;
704 }
705
706 if(get_crypt_ftr_and_key(&crypt_ftr)) {
707 return -1;
708 }
709
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700710 if ((crypt_ftr.major_version < 1)
711 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700712 SLOGE("Crypt_ftr version doesn't support persistent data");
713 return -1;
714 }
715
716 ret = validate_persistent_data_storage(&crypt_ftr);
717 if (ret) {
718 return -1;
719 }
720
721 if (get_crypt_ftr_info(&fname, NULL)) {
722 return -1;
723 }
724
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700725 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700726 if (fd < 0) {
727 SLOGE("Cannot open %s metadata file", fname);
728 return -1;
729 }
730
Wei Wang4375f1b2017-02-24 17:43:01 -0800731 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700732 if (pdata == NULL) {
733 SLOGE("Cannot allocate persistant data");
734 goto err;
735 }
736
737 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
738 SLOGE("Cannot seek to read persistent data on %s", fname);
739 goto err2;
740 }
741
742 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
743 SLOGE("Error reading persistent data before save");
744 goto err2;
745 }
746
747 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
748 /* The first copy is the curent valid copy, so write to
749 * the second copy and erase this one */
750 write_offset = crypt_ftr.persist_data_offset[1];
751 erase_offset = crypt_ftr.persist_data_offset[0];
752 } else {
753 /* The second copy must be the valid copy, so write to
754 * the first copy, and erase the second */
755 write_offset = crypt_ftr.persist_data_offset[0];
756 erase_offset = crypt_ftr.persist_data_offset[1];
757 }
758
759 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100760 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700761 SLOGE("Cannot seek to write persistent data");
762 goto err2;
763 }
764 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
765 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100766 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700767 SLOGE("Cannot seek to erase previous persistent data");
768 goto err2;
769 }
770 fsync(fd);
771 memset(pdata, 0, crypt_ftr.persist_data_size);
772 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
773 (int) crypt_ftr.persist_data_size) {
774 SLOGE("Cannot write to erase previous persistent data");
775 goto err2;
776 }
777 fsync(fd);
778 } else {
779 SLOGE("Cannot write to save persistent data");
780 goto err2;
781 }
782
783 /* Success */
784 free(pdata);
785 close(fd);
786 return 0;
787
788err2:
789 free(pdata);
790err:
791 close(fd);
792 return -1;
793}
794
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800795/* Convert a binary key of specified length into an ascii hex string equivalent,
796 * without the leading 0x and with null termination
797 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700798static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700799 unsigned int keysize, char *master_key_ascii) {
800 unsigned int i, a;
801 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800802
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700803 for (i=0, a=0; i<keysize; i++, a+=2) {
804 /* For each byte, write out two ascii hex digits */
805 nibble = (master_key[i] >> 4) & 0xf;
806 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800807
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700808 nibble = master_key[i] & 0xf;
809 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
810 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800811
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700812 /* Add the null termination */
813 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800814
815}
816
Jeff Sharkey9c484982015-03-31 10:35:33 -0700817static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
818 const unsigned char *master_key, const char *real_blk_name,
819 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800820 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800821 struct dm_ioctl *io;
822 struct dm_target_spec *tgt;
823 char *crypt_params;
824 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800825 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800826 int i;
827
828 io = (struct dm_ioctl *) buffer;
829
830 /* Load the mapping table for this device */
831 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
832
833 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
834 io->target_count = 1;
835 tgt->status = 0;
836 tgt->sector_start = 0;
837 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700838 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800839
840 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
841 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800842
843 buff_offset = crypt_params - buffer;
844 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
845 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
846 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800847 crypt_params += strlen(crypt_params) + 1;
848 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
849 tgt->next = crypt_params - buffer;
850
851 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
852 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
853 break;
854 }
855 usleep(500000);
856 }
857
858 if (i == TABLE_LOAD_RETRIES) {
859 /* We failed to load the table, return an error */
860 return -1;
861 } else {
862 return i + 1;
863 }
864}
865
866
867static int get_dm_crypt_version(int fd, const char *name, int *version)
868{
869 char buffer[DM_CRYPT_BUF_SIZE];
870 struct dm_ioctl *io;
871 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800872
873 io = (struct dm_ioctl *) buffer;
874
875 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
876
877 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
878 return -1;
879 }
880
881 /* Iterate over the returned versions, looking for name of "crypt".
882 * When found, get and return the version.
883 */
884 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
885 while (v->next) {
886 if (! strcmp(v->name, "crypt")) {
887 /* We found the crypt driver, return the version, and get out */
888 version[0] = v->version[0];
889 version[1] = v->version[1];
890 version[2] = v->version[2];
891 return 0;
892 }
893 v = (struct dm_target_versions *)(((char *)v) + v->next);
894 }
895
896 return -1;
897}
898
Jeff Sharkey9c484982015-03-31 10:35:33 -0700899static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
900 const unsigned char *master_key, const char *real_blk_name,
901 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800902 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800903 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800904 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -0700905 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800906 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800907 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800908 int version[3];
Wei Wang4375f1b2017-02-24 17:43:01 -0800909 const char *extra_params;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800910 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800911
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700912 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800913 SLOGE("Cannot open device-mapper\n");
914 goto errout;
915 }
916
917 io = (struct dm_ioctl *) buffer;
918
919 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800920 err = ioctl(fd, DM_DEV_CREATE, io);
921 if (err) {
922 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800923 goto errout;
924 }
925
926 /* Get the device status, in particular, the name of it's device file */
927 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
928 if (ioctl(fd, DM_DEV_STATUS, io)) {
929 SLOGE("Cannot retrieve dm-crypt device status\n");
930 goto errout;
931 }
932 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
933 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
934
Ken Sumralldb5e0262013-02-05 17:39:48 -0800935 extra_params = "";
936 if (! get_dm_crypt_version(fd, name, version)) {
937 /* Support for allow_discards was added in version 1.11.0 */
938 if ((version[0] >= 2) ||
939 ((version[0] == 1) && (version[1] >= 11))) {
940 extra_params = "1 allow_discards";
941 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
942 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700943 }
944
Ken Sumralldb5e0262013-02-05 17:39:48 -0800945 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
946 fd, extra_params);
947 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800948 SLOGE("Cannot load dm-crypt mapping table.\n");
949 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800950 } else if (load_count > 1) {
951 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800952 }
953
954 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800955 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800956
957 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
958 SLOGE("Cannot resume the dm-crypt device\n");
959 goto errout;
960 }
961
962 /* We made it here with no errors. Woot! */
963 retval = 0;
964
965errout:
966 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
967
968 return retval;
969}
970
Wei Wang4375f1b2017-02-24 17:43:01 -0800971static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800972{
973 int fd;
974 char buffer[DM_CRYPT_BUF_SIZE];
975 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800976 int retval = -1;
977
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700978 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800979 SLOGE("Cannot open device-mapper\n");
980 goto errout;
981 }
982
983 io = (struct dm_ioctl *) buffer;
984
985 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
986 if (ioctl(fd, DM_DEV_REMOVE, io)) {
987 SLOGE("Cannot remove dm-crypt device\n");
988 goto errout;
989 }
990
991 /* We made it here with no errors. Woot! */
992 retval = 0;
993
994errout:
995 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
996
997 return retval;
998
999}
1000
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001001static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001002 unsigned char *ikey, void *params UNUSED)
1003{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001004 SLOGI("Using pbkdf2 for cryptfs KDF");
1005
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001006 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001007 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1008 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1009 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001010}
1011
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001012static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001013 unsigned char *ikey, void *params)
1014{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001015 SLOGI("Using scrypt for cryptfs KDF");
1016
Kenny Rootc4c70f12013-06-14 12:11:38 -07001017 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1018
1019 int N = 1 << ftr->N_factor;
1020 int r = 1 << ftr->r_factor;
1021 int p = 1 << ftr->p_factor;
1022
1023 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001024 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001025 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1026 salt, SALT_LEN, N, r, p, ikey,
1027 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001028
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001029 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001030}
1031
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001032static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1033 unsigned char *ikey, void *params)
1034{
1035 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1036
1037 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001038 size_t signature_size;
1039 unsigned char* signature;
1040 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1041
1042 int N = 1 << ftr->N_factor;
1043 int r = 1 << ftr->r_factor;
1044 int p = 1 << ftr->p_factor;
1045
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001046 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1047 salt, SALT_LEN, N, r, p, ikey,
1048 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001049
1050 if (rc) {
1051 SLOGE("scrypt failed");
1052 return -1;
1053 }
1054
Shawn Willdene17a9c42014-09-08 13:04:08 -06001055 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1056 &signature, &signature_size)) {
1057 SLOGE("Signing failed");
1058 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001059 }
1060
1061 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1062 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1063 free(signature);
1064
1065 if (rc) {
1066 SLOGE("scrypt failed");
1067 return -1;
1068 }
1069
1070 return 0;
1071}
1072
1073static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1074 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001075 unsigned char *encrypted_master_key,
1076 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001077{
1078 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1079 EVP_CIPHER_CTX e_ctx;
1080 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001081 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001082
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001083 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001084 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001085
1086 switch (crypt_ftr->kdf_type) {
1087 case KDF_SCRYPT_KEYMASTER:
1088 if (keymaster_create_key(crypt_ftr)) {
1089 SLOGE("keymaster_create_key failed");
1090 return -1;
1091 }
1092
1093 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1094 SLOGE("scrypt failed");
1095 return -1;
1096 }
1097 break;
1098
1099 case KDF_SCRYPT:
1100 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1101 SLOGE("scrypt failed");
1102 return -1;
1103 }
1104 break;
1105
1106 default:
1107 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001108 return -1;
1109 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001110
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001111 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001112 EVP_CIPHER_CTX_init(&e_ctx);
1113 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001114 SLOGE("EVP_EncryptInit failed\n");
1115 return -1;
1116 }
1117 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001118
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001119 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001120 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001121 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001122 SLOGE("EVP_EncryptUpdate failed\n");
1123 return -1;
1124 }
Adam Langley889c4f12014-09-03 14:23:13 -07001125 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126 SLOGE("EVP_EncryptFinal failed\n");
1127 return -1;
1128 }
1129
1130 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1131 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1132 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001133 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001134
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001135 /* Store the scrypt of the intermediate key, so we can validate if it's a
1136 password error or mount error when things go wrong.
1137 Note there's no need to check for errors, since if this is incorrect, we
1138 simply won't wipe userdata, which is the correct default behavior
1139 */
1140 int N = 1 << crypt_ftr->N_factor;
1141 int r = 1 << crypt_ftr->r_factor;
1142 int p = 1 << crypt_ftr->p_factor;
1143
1144 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1145 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1146 crypt_ftr->scrypted_intermediate_key,
1147 sizeof(crypt_ftr->scrypted_intermediate_key));
1148
1149 if (rc) {
1150 SLOGE("encrypt_master_key: crypto_scrypt failed");
1151 }
1152
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001153 EVP_CIPHER_CTX_cleanup(&e_ctx);
1154
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001155 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156}
1157
Paul Lawrence731a7a22015-04-28 22:14:15 +00001158static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001159 unsigned char *encrypted_master_key,
1160 unsigned char *decrypted_master_key,
1161 kdf_func kdf, void *kdf_params,
1162 unsigned char** intermediate_key,
1163 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001164{
1165 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001166 EVP_CIPHER_CTX d_ctx;
1167 int decrypted_len, final_len;
1168
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001169 /* Turn the password into an intermediate key and IV that can decrypt the
1170 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001171 if (kdf(passwd, salt, ikey, kdf_params)) {
1172 SLOGE("kdf failed");
1173 return -1;
1174 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001175
1176 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001177 EVP_CIPHER_CTX_init(&d_ctx);
1178 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001179 return -1;
1180 }
1181 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1182 /* Decrypt the master key */
1183 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1184 encrypted_master_key, KEY_LEN_BYTES)) {
1185 return -1;
1186 }
Adam Langley889c4f12014-09-03 14:23:13 -07001187 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001188 return -1;
1189 }
1190
1191 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1192 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001193 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001194
1195 /* Copy intermediate key if needed by params */
1196 if (intermediate_key && intermediate_key_size) {
1197 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001198 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001199 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1200 *intermediate_key_size = KEY_LEN_BYTES;
1201 }
1202 }
1203
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001204 EVP_CIPHER_CTX_cleanup(&d_ctx);
1205
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001206 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207}
1208
Kenny Rootc4c70f12013-06-14 12:11:38 -07001209static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001210{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001211 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001212 *kdf = scrypt_keymaster;
1213 *kdf_params = ftr;
1214 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001215 *kdf = scrypt;
1216 *kdf_params = ftr;
1217 } else {
1218 *kdf = pbkdf2;
1219 *kdf_params = NULL;
1220 }
1221}
1222
Paul Lawrence731a7a22015-04-28 22:14:15 +00001223static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001224 struct crypt_mnt_ftr *crypt_ftr,
1225 unsigned char** intermediate_key,
1226 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001227{
1228 kdf_func kdf;
1229 void *kdf_params;
1230 int ret;
1231
1232 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001233 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1234 decrypted_master_key, kdf, kdf_params,
1235 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001236 if (ret != 0) {
1237 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001238 }
1239
1240 return ret;
1241}
1242
Wei Wang4375f1b2017-02-24 17:43:01 -08001243static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001244 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001245 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001246 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001247
1248 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001249 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001250 read(fd, key_buf, sizeof(key_buf));
1251 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001252 close(fd);
1253
1254 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001255 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001256}
1257
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001258int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259{
Greg Hackmann955653e2014-09-24 14:55:20 -07001260 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001261#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001262
1263 /* Now umount the tmpfs filesystem */
1264 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001265 if (umount(mountpoint) == 0) {
1266 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001267 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001268
1269 if (errno == EINVAL) {
1270 /* EINVAL is returned if the directory is not a mountpoint,
1271 * i.e. there is no filesystem mounted there. So just get out.
1272 */
1273 break;
1274 }
1275
1276 err = errno;
1277
1278 /* If allowed, be increasingly aggressive before the last two retries */
1279 if (kill) {
1280 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1281 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001282 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001283 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1284 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001285 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001286 }
1287 }
1288
1289 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001290 }
1291
1292 if (i < WAIT_UNMOUNT_COUNT) {
1293 SLOGD("unmounting %s succeeded\n", mountpoint);
1294 rc = 0;
1295 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001296 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001297 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001298 rc = -1;
1299 }
1300
1301 return rc;
1302}
1303
Wei Wang42e38102017-06-07 10:46:12 -07001304static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001305{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001306 // NOTE: post_fs_data results in init calling back around to vold, so all
1307 // callers to this method must be async
1308
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001309 /* Do the prep of the /data filesystem */
1310 property_set("vold.post_fs_data_done", "0");
1311 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001312 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001313
Ken Sumrallc5872692013-05-14 15:26:31 -07001314 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001315 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001316 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001317 std::chrono::seconds(15))) {
1318 /* We timed out to prep /data in time. Continue wait. */
1319 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001320 }
Wei Wang42e38102017-06-07 10:46:12 -07001321 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001322}
1323
Paul Lawrence74f29f12014-08-28 15:54:10 -07001324static void cryptfs_set_corrupt()
1325{
1326 // Mark the footer as bad
1327 struct crypt_mnt_ftr crypt_ftr;
1328 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1329 SLOGE("Failed to get crypto footer - panic");
1330 return;
1331 }
1332
1333 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1334 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1335 SLOGE("Failed to set crypto footer - panic");
1336 return;
1337 }
1338}
1339
1340static void cryptfs_trigger_restart_min_framework()
1341{
1342 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1343 SLOGE("Failed to mount tmpfs on data - panic");
1344 return;
1345 }
1346
1347 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1348 SLOGE("Failed to trigger post fs data - panic");
1349 return;
1350 }
1351
1352 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1353 SLOGE("Failed to trigger restart min framework - panic");
1354 return;
1355 }
1356}
1357
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001358/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001359static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001360{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001361 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001362 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001363 static int restart_successful = 0;
1364
1365 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001366 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001367 SLOGE("Encrypted filesystem not validated, aborting");
1368 return -1;
1369 }
1370
1371 if (restart_successful) {
1372 SLOGE("System already restarted with encrypted disk, aborting");
1373 return -1;
1374 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001375
Paul Lawrencef4faa572014-01-29 13:31:03 -08001376 if (restart_main) {
1377 /* Here is where we shut down the framework. The init scripts
1378 * start all services in one of three classes: core, main or late_start.
1379 * On boot, we start core and main. Now, we stop main, but not core,
1380 * as core includes vold and a few other really important things that
1381 * we need to keep running. Once main has stopped, we should be able
1382 * to umount the tmpfs /data, then mount the encrypted /data.
1383 * We then restart the class main, and also the class late_start.
1384 * At the moment, I've only put a few things in late_start that I know
1385 * are not needed to bring up the framework, and that also cause problems
1386 * with unmounting the tmpfs /data, but I hope to add add more services
1387 * to the late_start class as we optimize this to decrease the delay
1388 * till the user is asked for the password to the filesystem.
1389 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001390
Paul Lawrencef4faa572014-01-29 13:31:03 -08001391 /* The init files are setup to stop the class main when vold.decrypt is
1392 * set to trigger_reset_main.
1393 */
1394 property_set("vold.decrypt", "trigger_reset_main");
1395 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001396
Paul Lawrencef4faa572014-01-29 13:31:03 -08001397 /* Ugh, shutting down the framework is not synchronous, so until it
1398 * can be fixed, this horrible hack will wait a moment for it all to
1399 * shut down before proceeding. Without it, some devices cannot
1400 * restart the graphics services.
1401 */
1402 sleep(2);
1403 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001404
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001405 /* Now that the framework is shutdown, we should be able to umount()
1406 * the tmpfs filesystem, and mount the real one.
1407 */
1408
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001409 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1410 if (strlen(crypto_blkdev) == 0) {
1411 SLOGE("fs_crypto_blkdev not set\n");
1412 return -1;
1413 }
1414
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001415 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001416 /* If ro.crypto.readonly is set to 1, mount the decrypted
1417 * filesystem readonly. This is used when /data is mounted by
1418 * recovery mode.
1419 */
1420 char ro_prop[PROPERTY_VALUE_MAX];
1421 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001422 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001423 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1424 rec->flags |= MS_RDONLY;
1425 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001426
Ken Sumralle5032c42012-04-01 23:58:44 -07001427 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001428 int retries = RETRY_MOUNT_ATTEMPTS;
1429 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001430
1431 /*
1432 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1433 * partitions in the fsck domain.
1434 */
1435 if (setexeccon(secontextFsck())){
1436 SLOGE("Failed to setexeccon");
1437 return -1;
1438 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001439 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1440 crypto_blkdev, 0))
1441 != 0) {
1442 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1443 /* TODO: invoke something similar to
1444 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1445 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1446 SLOGI("Failed to mount %s because it is busy - waiting",
1447 crypto_blkdev);
1448 if (--retries) {
1449 sleep(RETRY_MOUNT_DELAY_SECONDS);
1450 } else {
1451 /* Let's hope that a reboot clears away whatever is keeping
1452 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001453 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001454 }
1455 } else {
1456 SLOGE("Failed to mount decrypted data");
1457 cryptfs_set_corrupt();
1458 cryptfs_trigger_restart_min_framework();
1459 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001460 if (setexeccon(NULL)) {
1461 SLOGE("Failed to setexeccon");
1462 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001463 return -1;
1464 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001465 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001466 if (setexeccon(NULL)) {
1467 SLOGE("Failed to setexeccon");
1468 return -1;
1469 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001470
Ken Sumralle5032c42012-04-01 23:58:44 -07001471 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001472 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001473 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001474
1475 /* startup service classes main and late_start */
1476 property_set("vold.decrypt", "trigger_restart_framework");
1477 SLOGD("Just triggered restart_framework\n");
1478
1479 /* Give it a few moments to get started */
1480 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001481 }
1482
Ken Sumrall0cc16632011-01-18 20:32:26 -08001483 if (rc == 0) {
1484 restart_successful = 1;
1485 }
1486
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001487 return rc;
1488}
1489
Paul Lawrencef4faa572014-01-29 13:31:03 -08001490int cryptfs_restart(void)
1491{
Paul Lawrence05335c32015-03-05 09:46:23 -08001492 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001493 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001494 SLOGE("cryptfs_restart not valid for file encryption:");
1495 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001496 }
1497
Paul Lawrencef4faa572014-01-29 13:31:03 -08001498 /* Call internal implementation forcing a restart of main service group */
1499 return cryptfs_restart_internal(1);
1500}
1501
Wei Wang4375f1b2017-02-24 17:43:01 -08001502static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001503{
1504 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001505 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001506 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001507
1508 property_get("ro.crypto.state", encrypted_state, "");
1509 if (strcmp(encrypted_state, "encrypted") ) {
1510 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001511 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001512 }
1513
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001514 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001515 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001516 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001517 }
1518
Ken Sumrall160b4d62013-04-22 12:15:39 -07001519 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001520 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001521
Ken Sumralle1a45852011-12-14 21:24:27 -08001522 /*
1523 * Only report this error if key_loc is a file and it exists.
1524 * If the device was never encrypted, and /data is not mountable for
1525 * some reason, returning 1 should prevent the UI from presenting the
1526 * a "enter password" screen, or worse, a "press button to wipe the
1527 * device" screen.
1528 */
1529 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1530 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001531 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001532 } else {
1533 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001534 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001535 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001536 }
1537
Paul Lawrence74f29f12014-08-28 15:54:10 -07001538 // Test for possible error flags
1539 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1540 SLOGE("Encryption process is partway completed\n");
1541 return CRYPTO_COMPLETE_PARTIAL;
1542 }
1543
1544 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1545 SLOGE("Encryption process was interrupted but cannot continue\n");
1546 return CRYPTO_COMPLETE_INCONSISTENT;
1547 }
1548
1549 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1550 SLOGE("Encryption is successful but data is corrupt\n");
1551 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001552 }
1553
1554 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001555 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001556}
1557
Paul Lawrencef4faa572014-01-29 13:31:03 -08001558static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001559 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001560{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001561 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001562 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001563 char crypto_blkdev[MAXPATHLEN];
1564 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001565 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001566 unsigned int orig_failed_decrypt_count;
1567 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001568 int use_keymaster = 0;
1569 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001570 unsigned char* intermediate_key = 0;
1571 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001572 int N = 1 << crypt_ftr->N_factor;
1573 int r = 1 << crypt_ftr->r_factor;
1574 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001575
Paul Lawrencef4faa572014-01-29 13:31:03 -08001576 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1577 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001578
Paul Lawrencef4faa572014-01-29 13:31:03 -08001579 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001580 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1581 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001582 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001583 rc = -1;
1584 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001585 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001586 }
1587
Paul Lawrencef4faa572014-01-29 13:31:03 -08001588 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1589
Paul Lawrence74f29f12014-08-28 15:54:10 -07001590 // Create crypto block device - all (non fatal) code paths
1591 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001592 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1593 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001594 SLOGE("Error creating decrypted block device\n");
1595 rc = -1;
1596 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001597 }
1598
Paul Lawrence74f29f12014-08-28 15:54:10 -07001599 /* Work out if the problem is the password or the data */
1600 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1601 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001602
Paul Lawrence74f29f12014-08-28 15:54:10 -07001603 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1604 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1605 N, r, p, scrypted_intermediate_key,
1606 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001607
Paul Lawrence74f29f12014-08-28 15:54:10 -07001608 // Does the key match the crypto footer?
1609 if (rc == 0 && memcmp(scrypted_intermediate_key,
1610 crypt_ftr->scrypted_intermediate_key,
1611 sizeof(scrypted_intermediate_key)) == 0) {
1612 SLOGI("Password matches");
1613 rc = 0;
1614 } else {
1615 /* Try mounting the file system anyway, just in case the problem's with
1616 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001617 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1618 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001619 mkdir(tmp_mount_point, 0755);
1620 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1621 SLOGE("Error temp mounting decrypted block device\n");
1622 delete_crypto_blk_dev(label);
1623
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001624 rc = ++crypt_ftr->failed_decrypt_count;
1625 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001626 } else {
1627 /* Success! */
1628 SLOGI("Password did not match but decrypted drive mounted - continue");
1629 umount(tmp_mount_point);
1630 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001631 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001632 }
1633
1634 if (rc == 0) {
1635 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001636 if (orig_failed_decrypt_count != 0) {
1637 put_crypt_ftr_and_key(crypt_ftr);
1638 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001639
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001640 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001641 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001642 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001643
1644 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001645 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001646 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001647 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001648 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001649 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001650 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001651
Paul Lawrence74f29f12014-08-28 15:54:10 -07001652 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001653 use_keymaster = keymaster_check_compatibility();
1654 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001655 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001656 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1657 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1658 upgrade = 1;
1659 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001660 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001661 upgrade = 1;
1662 }
1663
1664 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001665 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1666 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001667 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001668 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001669 }
1670 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001671
1672 // Do not fail even if upgrade failed - machine is bootable
1673 // Note that if this code is ever hit, there is a *serious* problem
1674 // since KDFs should never fail. You *must* fix the kdf before
1675 // proceeding!
1676 if (rc) {
1677 SLOGW("Upgrade failed with error %d,"
1678 " but continuing with previous state",
1679 rc);
1680 rc = 0;
1681 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001682 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001683 }
1684
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001685 errout:
1686 if (intermediate_key) {
1687 memset(intermediate_key, 0, intermediate_key_size);
1688 free(intermediate_key);
1689 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001690 return rc;
1691}
1692
Ken Sumrall29d8da82011-05-18 17:20:07 -07001693/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001694 * Called by vold when it's asked to mount an encrypted external
1695 * storage volume. The incoming partition has no crypto header/footer,
1696 * as any metadata is been stored in a separate, small partition.
1697 *
1698 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001699 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001700int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1701 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001702 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001703 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001704 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001705 return -1;
1706 }
1707
1708 unsigned long nr_sec = 0;
1709 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001710 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001711
Ken Sumrall29d8da82011-05-18 17:20:07 -07001712 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001713 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001714 return -1;
1715 }
1716
Jeff Sharkey9c484982015-03-31 10:35:33 -07001717 struct crypt_mnt_ftr ext_crypt_ftr;
1718 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1719 ext_crypt_ftr.fs_size = nr_sec;
1720 ext_crypt_ftr.keysize = keysize;
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001721 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
1722 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001723
Jeff Sharkey9c484982015-03-31 10:35:33 -07001724 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1725 out_crypto_blkdev, label);
1726}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001727
Jeff Sharkey9c484982015-03-31 10:35:33 -07001728/*
1729 * Called by vold when it's asked to unmount an encrypted external
1730 * storage volume.
1731 */
1732int cryptfs_revert_ext_volume(const char* label) {
1733 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001734}
1735
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001736int cryptfs_crypto_complete(void)
1737{
1738 return do_crypto_complete("/data");
1739}
1740
Paul Lawrencef4faa572014-01-29 13:31:03 -08001741int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1742{
1743 char encrypted_state[PROPERTY_VALUE_MAX];
1744 property_get("ro.crypto.state", encrypted_state, "");
1745 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1746 SLOGE("encrypted fs already validated or not running with encryption,"
1747 " aborting");
1748 return -1;
1749 }
1750
1751 if (get_crypt_ftr_and_key(crypt_ftr)) {
1752 SLOGE("Error getting crypt footer and key");
1753 return -1;
1754 }
1755
1756 return 0;
1757}
1758
Wei Wang4375f1b2017-02-24 17:43:01 -08001759int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001760{
Paul Lawrence05335c32015-03-05 09:46:23 -08001761 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001762 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001763 SLOGE("cryptfs_check_passwd not valid for file encryption");
1764 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001765 }
1766
Paul Lawrencef4faa572014-01-29 13:31:03 -08001767 struct crypt_mnt_ftr crypt_ftr;
1768 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001769
Paul Lawrencef4faa572014-01-29 13:31:03 -08001770 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001771 if (rc) {
1772 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001773 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001774 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001775
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001776 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001777 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1778 if (rc) {
1779 SLOGE("Password did not match");
1780 return rc;
1781 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001782
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001783 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1784 // Here we have a default actual password but a real password
1785 // we must test against the scrypted value
1786 // First, we must delete the crypto block device that
1787 // test_mount_encrypted_fs leaves behind as a side effect
1788 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1789 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1790 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1791 if (rc) {
1792 SLOGE("Default password did not match on reboot encryption");
1793 return rc;
1794 }
1795
1796 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1797 put_crypt_ftr_and_key(&crypt_ftr);
1798 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1799 if (rc) {
1800 SLOGE("Could not change password on reboot encryption");
1801 return rc;
1802 }
1803 }
1804
1805 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001806 cryptfs_clear_password();
1807 password = strdup(passwd);
1808 struct timespec now;
1809 clock_gettime(CLOCK_BOOTTIME, &now);
1810 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001811 }
1812
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001813 return rc;
1814}
1815
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001816int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001817{
1818 struct crypt_mnt_ftr crypt_ftr;
1819 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001820 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001821 char encrypted_state[PROPERTY_VALUE_MAX];
1822 int rc;
1823
1824 property_get("ro.crypto.state", encrypted_state, "");
1825 if (strcmp(encrypted_state, "encrypted") ) {
1826 SLOGE("device not encrypted, aborting");
1827 return -2;
1828 }
1829
1830 if (!master_key_saved) {
1831 SLOGE("encrypted fs not yet mounted, aborting");
1832 return -1;
1833 }
1834
1835 if (!saved_mount_point) {
1836 SLOGE("encrypted fs failed to save mount point, aborting");
1837 return -1;
1838 }
1839
Ken Sumrall160b4d62013-04-22 12:15:39 -07001840 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001841 SLOGE("Error getting crypt footer and key\n");
1842 return -1;
1843 }
1844
1845 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1846 /* If the device has no password, then just say the password is valid */
1847 rc = 0;
1848 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001849 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001850 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1851 /* They match, the password is correct */
1852 rc = 0;
1853 } else {
1854 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1855 sleep(1);
1856 rc = 1;
1857 }
1858 }
1859
1860 return rc;
1861}
1862
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001863/* Initialize a crypt_mnt_ftr structure. The keysize is
1864 * defaulted to 16 bytes, and the filesystem size to 0.
1865 * Presumably, at a minimum, the caller will update the
1866 * filesystem size and crypto_type_name after calling this function.
1867 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001868static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001869{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001870 off64_t off;
1871
1872 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001873 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001874 ftr->major_version = CURRENT_MAJOR_VERSION;
1875 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001876 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001877 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001878
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001879 switch (keymaster_check_compatibility()) {
1880 case 1:
1881 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1882 break;
1883
1884 case 0:
1885 ftr->kdf_type = KDF_SCRYPT;
1886 break;
1887
1888 default:
1889 SLOGE("keymaster_check_compatibility failed");
1890 return -1;
1891 }
1892
Kenny Rootc4c70f12013-06-14 12:11:38 -07001893 get_device_scrypt_params(ftr);
1894
Ken Sumrall160b4d62013-04-22 12:15:39 -07001895 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1896 if (get_crypt_ftr_info(NULL, &off) == 0) {
1897 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1898 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1899 ftr->persist_data_size;
1900 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001901
1902 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903}
1904
Ken Sumrall29d8da82011-05-18 17:20:07 -07001905static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001906{
Ken Sumralle550f782013-08-20 13:48:23 -07001907 const char *args[10];
1908 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1909 int num_args;
1910 int status;
1911 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001912 int rc = -1;
1913
Ken Sumrall29d8da82011-05-18 17:20:07 -07001914 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001915 args[0] = "/system/bin/mke2fs";
1916 args[1] = "-M";
1917 args[2] = "/data";
1918 args[3] = "-b";
1919 args[4] = "4096";
1920 args[5] = "-t";
1921 args[6] = "ext4";
1922 args[7] = crypto_blkdev;
1923 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1924 args[8] = size_str;
1925 num_args = 9;
Ken Sumralle550f782013-08-20 13:48:23 -07001926 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1927 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001928 } else if (type == F2FS_FS) {
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001929 args[0] = "/system/bin/make_f2fs";
JP Abgrall62c7af32014-06-16 13:01:23 -07001930 args[1] = "-t";
1931 args[2] = "-d1";
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001932 args[3] = "-f";
1933 args[4] = "-O encrypt";
1934 args[5] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001935 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001936 args[6] = size_str;
1937 num_args = 7;
1938 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s\n",
1939 args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001940 } else {
1941 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1942 return -1;
1943 }
1944
Ken Sumralle550f782013-08-20 13:48:23 -07001945 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1946
1947 if (tmp != 0) {
1948 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001949 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001950 if (WIFEXITED(status)) {
1951 if (WEXITSTATUS(status)) {
1952 SLOGE("Error creating filesystem on %s, exit status %d ",
1953 crypto_blkdev, WEXITSTATUS(status));
1954 } else {
1955 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1956 rc = 0;
1957 }
1958 } else {
1959 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1960 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001961 }
1962
1963 return rc;
1964}
1965
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001966#define CRYPTO_ENABLE_WIPE 1
1967#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001968
1969#define FRAMEWORK_BOOT_WAIT 60
1970
Paul Lawrence87999172014-02-20 12:21:31 -08001971static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1972{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001973 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001974 if (fd == -1) {
1975 SLOGE("Error opening file %s", filename);
1976 return -1;
1977 }
1978
1979 char block[CRYPT_INPLACE_BUFSIZE];
1980 memset(block, 0, sizeof(block));
1981 if (unix_read(fd, block, sizeof(block)) < 0) {
1982 SLOGE("Error reading file %s", filename);
1983 close(fd);
1984 return -1;
1985 }
1986
1987 close(fd);
1988
1989 SHA256_CTX c;
1990 SHA256_Init(&c);
1991 SHA256_Update(&c, block, sizeof(block));
1992 SHA256_Final(buf, &c);
1993
1994 return 0;
1995}
1996
JP Abgrall62c7af32014-06-16 13:01:23 -07001997static int get_fs_type(struct fstab_rec *rec)
1998{
1999 if (!strcmp(rec->fs_type, "ext4")) {
2000 return EXT4_FS;
2001 } else if (!strcmp(rec->fs_type, "f2fs")) {
2002 return F2FS_FS;
2003 } else {
2004 return -1;
2005 }
2006}
2007
Paul Lawrence87999172014-02-20 12:21:31 -08002008static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2009 char *crypto_blkdev, char *real_blkdev,
2010 int previously_encrypted_upto)
2011{
2012 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002013 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002014
Paul Lawrence73d7a022014-06-09 14:10:09 -07002015 if (!is_battery_ok_to_start()) {
2016 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002017 return 0;
2018 }
2019
2020 /* The size of the userdata partition, and add in the vold volumes below */
2021 tot_encryption_size = crypt_ftr->fs_size;
2022
2023 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002024 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2025 int fs_type = get_fs_type(rec);
2026 if (fs_type < 0) {
2027 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2028 return -1;
2029 }
2030 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002031 } else if (how == CRYPTO_ENABLE_INPLACE) {
2032 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2033 crypt_ftr->fs_size, &cur_encryption_done,
2034 tot_encryption_size,
2035 previously_encrypted_upto);
2036
JP Abgrall7fc1de82014-10-10 18:43:41 -07002037 if (rc == ENABLE_INPLACE_ERR_DEV) {
2038 /* Hack for b/17898962 */
2039 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
Josh Gaofec44372017-08-28 13:22:55 -07002040 cryptfs_reboot(RebootType::reboot);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002041 }
2042
Paul Lawrence73d7a022014-06-09 14:10:09 -07002043 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002044 crypt_ftr->encrypted_upto = cur_encryption_done;
2045 }
2046
Paul Lawrence73d7a022014-06-09 14:10:09 -07002047 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002048 /* The inplace routine never actually sets the progress to 100% due
2049 * to the round down nature of integer division, so set it here */
2050 property_set("vold.encrypt_progress", "100");
2051 }
2052 } else {
2053 /* Shouldn't happen */
2054 SLOGE("cryptfs_enable: internal error, unknown option\n");
2055 rc = -1;
2056 }
2057
2058 return rc;
2059}
2060
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002061int cryptfs_enable_internal(const char *howarg, int crypt_type, const char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002062 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002063{
2064 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002065 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002066 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002067 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002068 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002069 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002070 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002071 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002072 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002073 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002074 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002075 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002076 bool onlyCreateHeader = false;
2077 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002078
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002079 if (!strcmp(howarg, "wipe")) {
2080 how = CRYPTO_ENABLE_WIPE;
2081 } else if (! strcmp(howarg, "inplace")) {
2082 how = CRYPTO_ENABLE_INPLACE;
2083 } else {
2084 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002085 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002086 }
2087
Paul Lawrence87999172014-02-20 12:21:31 -08002088 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002089 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2090 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2091 /* An encryption was underway and was interrupted */
2092 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2093 crypt_ftr.encrypted_upto = 0;
2094 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002095
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002096 /* At this point, we are in an inconsistent state. Until we successfully
2097 complete encryption, a reboot will leave us broken. So mark the
2098 encryption failed in case that happens.
2099 On successfully completing encryption, remove this flag */
2100 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002101
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002102 put_crypt_ftr_and_key(&crypt_ftr);
2103 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2104 if (!check_ftr_sha(&crypt_ftr)) {
2105 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2106 put_crypt_ftr_and_key(&crypt_ftr);
2107 goto error_unencrypted;
2108 }
2109
2110 /* Doing a reboot-encryption*/
2111 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2112 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2113 rebootEncryption = true;
2114 }
Paul Lawrence87999172014-02-20 12:21:31 -08002115 }
2116
2117 property_get("ro.crypto.state", encrypted_state, "");
2118 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2119 SLOGE("Device is already running encrypted, aborting");
2120 goto error_unencrypted;
2121 }
2122
2123 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2124 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002125 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002126
Ken Sumrall3ed82362011-01-28 23:31:16 -08002127 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002128 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002129 if (fd == -1) {
2130 SLOGE("Cannot open block device %s\n", real_blkdev);
2131 goto error_unencrypted;
2132 }
2133 unsigned long nr_sec;
2134 get_blkdev_size(fd, &nr_sec);
2135 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002136 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2137 goto error_unencrypted;
2138 }
2139 close(fd);
2140
2141 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002142 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002143 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002144 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002145 if (fs_size_sec == 0)
2146 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2147
Paul Lawrence87999172014-02-20 12:21:31 -08002148 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002149
2150 if (fs_size_sec > max_fs_size_sec) {
2151 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2152 goto error_unencrypted;
2153 }
2154 }
2155
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002156 /* Get a wakelock as this may take a while, and we don't want the
2157 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2158 * wants to keep the screen on, it can grab a full wakelock.
2159 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002160 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002161 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2162
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002163 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002164 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002165 */
2166 property_set("vold.decrypt", "trigger_shutdown_framework");
2167 SLOGD("Just asked init to shut down class main\n");
2168
Jeff Sharkey9c484982015-03-31 10:35:33 -07002169 /* Ask vold to unmount all devices that it manages */
2170 if (vold_unmountAll()) {
2171 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002172 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002173
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002174 /* no_ui means we are being called from init, not settings.
2175 Now we always reboot from settings, so !no_ui means reboot
2176 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002177 if (!no_ui) {
2178 /* Try fallback, which is to reboot and try there */
2179 onlyCreateHeader = true;
2180 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2181 if (breadcrumb == 0) {
2182 SLOGE("Failed to create breadcrumb file");
2183 goto error_shutting_down;
2184 }
2185 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002186 }
2187
2188 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002189 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002190 /* Now that /data is unmounted, we need to mount a tmpfs
2191 * /data, set a property saying we're doing inplace encryption,
2192 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002193 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002194 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002195 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002196 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002197 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002198 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002199
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002200 /* restart the framework. */
2201 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002202 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002203
Ken Sumrall92736ef2012-10-17 20:57:14 -07002204 /* Ugh, shutting down the framework is not synchronous, so until it
2205 * can be fixed, this horrible hack will wait a moment for it all to
2206 * shut down before proceeding. Without it, some devices cannot
2207 * restart the graphics services.
2208 */
2209 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002210 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002211
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002212 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002213 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002214 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002215 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2216 goto error_shutting_down;
2217 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002218
Paul Lawrence87999172014-02-20 12:21:31 -08002219 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2220 crypt_ftr.fs_size = nr_sec
2221 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2222 } else {
2223 crypt_ftr.fs_size = nr_sec;
2224 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002225 /* At this point, we are in an inconsistent state. Until we successfully
2226 complete encryption, a reboot will leave us broken. So mark the
2227 encryption failed in case that happens.
2228 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002229 if (onlyCreateHeader) {
2230 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2231 } else {
2232 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2233 }
Paul Lawrence87999172014-02-20 12:21:31 -08002234 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002235 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002236
Paul Lawrence87999172014-02-20 12:21:31 -08002237 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002238 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2239 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002240 SLOGE("Cannot create encrypted master key\n");
2241 goto error_shutting_down;
2242 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002243
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002244 /* Replace scrypted intermediate key if we are preparing for a reboot */
2245 if (onlyCreateHeader) {
2246 unsigned char fake_master_key[KEY_LEN_BYTES];
2247 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2248 memset(fake_master_key, 0, sizeof(fake_master_key));
2249 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2250 encrypted_fake_master_key, &crypt_ftr);
2251 }
2252
Paul Lawrence87999172014-02-20 12:21:31 -08002253 /* Write the key to the end of the partition */
2254 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002255
Paul Lawrence87999172014-02-20 12:21:31 -08002256 /* If any persistent data has been remembered, save it.
2257 * If none, create a valid empty table and save that.
2258 */
2259 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002260 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002261 if (pdata) {
2262 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2263 persist_data = pdata;
2264 }
2265 }
2266 if (persist_data) {
2267 save_persistent_data();
2268 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002269 }
2270
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002271 if (onlyCreateHeader) {
2272 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002273 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002274 }
2275
2276 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002277 /* startup service classes main and late_start */
2278 property_set("vold.decrypt", "trigger_restart_min_framework");
2279 SLOGD("Just triggered restart_min_framework\n");
2280
2281 /* OK, the framework is restarted and will soon be showing a
2282 * progress bar. Time to setup an encrypted mapping, and
2283 * either write a new filesystem, or encrypt in place updating
2284 * the progress bar as we work.
2285 */
2286 }
2287
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002288 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002289 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002290 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002291
Paul Lawrence87999172014-02-20 12:21:31 -08002292 /* If we are continuing, check checksums match */
2293 rc = 0;
2294 if (previously_encrypted_upto) {
2295 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2296 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002297
Paul Lawrence87999172014-02-20 12:21:31 -08002298 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2299 sizeof(hash_first_block)) != 0) {
2300 SLOGE("Checksums do not match - trigger wipe");
2301 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002302 }
2303 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002304
Paul Lawrence87999172014-02-20 12:21:31 -08002305 if (!rc) {
2306 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2307 crypto_blkdev, real_blkdev,
2308 previously_encrypted_upto);
2309 }
2310
2311 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002312 if (!rc && how == CRYPTO_ENABLE_INPLACE
2313 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002314 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2315 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002316 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002317 SLOGE("Error calculating checksum for continuing encryption");
2318 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002319 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002320 }
2321
2322 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002323 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002324
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002325 if (! rc) {
2326 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002327 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002328
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002329 if (how == CRYPTO_ENABLE_INPLACE
2330 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002331 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2332 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002333 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002334 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002335
Paul Lawrence6bfed202014-07-28 12:47:22 -07002336 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002337
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002338 if (how == CRYPTO_ENABLE_WIPE
2339 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002340 char value[PROPERTY_VALUE_MAX];
2341 property_get("ro.crypto.state", value, "");
2342 if (!strcmp(value, "")) {
2343 /* default encryption - continue first boot sequence */
2344 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08002345 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002346 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002347 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2348 // Bring up cryptkeeper that will check the password and set it
2349 property_set("vold.decrypt", "trigger_shutdown_framework");
2350 sleep(2);
2351 property_set("vold.encrypt_progress", "");
2352 cryptfs_trigger_restart_min_framework();
2353 } else {
2354 cryptfs_check_passwd(DEFAULT_PASSWORD);
2355 cryptfs_restart_internal(1);
2356 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002357 return 0;
2358 } else {
2359 sleep(2); /* Give the UI a chance to show 100% progress */
Josh Gaofec44372017-08-28 13:22:55 -07002360 cryptfs_reboot(RebootType::reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002361 }
Paul Lawrence87999172014-02-20 12:21:31 -08002362 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002363 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002364 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002365 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002366 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002367 char value[PROPERTY_VALUE_MAX];
2368
Ken Sumrall319369a2012-06-27 16:30:18 -07002369 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002370 if (!strcmp(value, "1")) {
2371 /* wipe data if encryption failed */
2372 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002373 std::string err;
2374 const std::vector<std::string> options = {
2375 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2376 };
2377 if (!write_bootloader_message(options, &err)) {
2378 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002379 }
Josh Gaofec44372017-08-28 13:22:55 -07002380 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002381 } else {
2382 /* set property to trigger dialog */
2383 property_set("vold.encrypt_progress", "error_partially_encrypted");
2384 release_wake_lock(lockid);
2385 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002386 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002387 }
2388
Ken Sumrall3ed82362011-01-28 23:31:16 -08002389 /* hrm, the encrypt step claims success, but the reboot failed.
2390 * This should not happen.
2391 * Set the property and return. Hope the framework can deal with it.
2392 */
2393 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002394 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002395 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002396
2397error_unencrypted:
2398 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002399 if (lockid[0]) {
2400 release_wake_lock(lockid);
2401 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002402 return -1;
2403
2404error_shutting_down:
2405 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2406 * but the framework is stopped and not restarted to show the error, so it's up to
2407 * vold to restart the system.
2408 */
2409 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002410 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002411
2412 /* shouldn't get here */
2413 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002414 if (lockid[0]) {
2415 release_wake_lock(lockid);
2416 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002417 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002418}
2419
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002420int cryptfs_enable(const char *howarg, int type, const char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002421{
Paul Lawrence569649f2015-09-09 12:13:00 -07002422 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002423}
2424
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002425int cryptfs_enable_default(const char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002426{
2427 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07002428 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002429}
2430
2431int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002432{
Paul Crowley38132a12016-02-09 09:50:32 +00002433 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002434 SLOGE("cryptfs_changepw not valid for file encryption");
2435 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002436 }
2437
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002438 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002439 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002440
2441 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002442 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002443 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002444 return -1;
2445 }
2446
Paul Lawrencef4faa572014-01-29 13:31:03 -08002447 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2448 SLOGE("Invalid crypt_type %d", crypt_type);
2449 return -1;
2450 }
2451
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002452 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002453 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002454 SLOGE("Error getting crypt footer and key");
2455 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002456 }
2457
Paul Lawrencef4faa572014-01-29 13:31:03 -08002458 crypt_ftr.crypt_type = crypt_type;
2459
JP Abgrall933216c2015-02-11 13:44:32 -08002460 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002461 : newpw,
2462 crypt_ftr.salt,
2463 saved_master_key,
2464 crypt_ftr.master_key,
2465 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002466 if (rc) {
2467 SLOGE("Encrypt master key failed: %d", rc);
2468 return -1;
2469 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002470 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002471 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002472
2473 return 0;
2474}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002475
Rubin Xu85c01f92014-10-13 12:49:54 +01002476static unsigned int persist_get_max_entries(int encrypted) {
2477 struct crypt_mnt_ftr crypt_ftr;
2478 unsigned int dsize;
2479 unsigned int max_persistent_entries;
2480
2481 /* If encrypted, use the values from the crypt_ftr, otherwise
2482 * use the values for the current spec.
2483 */
2484 if (encrypted) {
2485 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2486 return -1;
2487 }
2488 dsize = crypt_ftr.persist_data_size;
2489 } else {
2490 dsize = CRYPT_PERSIST_DATA_SIZE;
2491 }
2492
2493 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2494 sizeof(struct crypt_persist_entry);
2495
2496 return max_persistent_entries;
2497}
2498
2499static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002500{
2501 unsigned int i;
2502
2503 if (persist_data == NULL) {
2504 return -1;
2505 }
2506 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2507 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2508 /* We found it! */
2509 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2510 return 0;
2511 }
2512 }
2513
2514 return -1;
2515}
2516
Rubin Xu85c01f92014-10-13 12:49:54 +01002517static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002518{
2519 unsigned int i;
2520 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002521 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002522
2523 if (persist_data == NULL) {
2524 return -1;
2525 }
2526
Rubin Xu85c01f92014-10-13 12:49:54 +01002527 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002528
2529 num = persist_data->persist_valid_entries;
2530
2531 for (i = 0; i < num; i++) {
2532 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2533 /* We found an existing entry, update it! */
2534 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2535 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2536 return 0;
2537 }
2538 }
2539
2540 /* We didn't find it, add it to the end, if there is room */
2541 if (persist_data->persist_valid_entries < max_persistent_entries) {
2542 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2543 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2544 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2545 persist_data->persist_valid_entries++;
2546 return 0;
2547 }
2548
2549 return -1;
2550}
2551
Rubin Xu85c01f92014-10-13 12:49:54 +01002552/**
2553 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2554 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2555 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002556int match_multi_entry(const char *key, const char *field, unsigned index) {
2557 std::string key_ = key;
2558 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002559
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002560 std::string parsed_field;
2561 unsigned parsed_index;
2562
2563 std::string::size_type split = key_.find_last_of('_');
2564 if (split == std::string::npos) {
2565 parsed_field = key_;
2566 parsed_index = 0;
2567 } else {
2568 parsed_field = key_.substr(0, split);
2569 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002570 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002571
2572 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002573}
2574
2575/*
2576 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2577 * remaining entries starting from index will be deleted.
2578 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2579 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2580 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2581 *
2582 */
2583static int persist_del_keys(const char *fieldname, unsigned index)
2584{
2585 unsigned int i;
2586 unsigned int j;
2587 unsigned int num;
2588
2589 if (persist_data == NULL) {
2590 return PERSIST_DEL_KEY_ERROR_OTHER;
2591 }
2592
2593 num = persist_data->persist_valid_entries;
2594
2595 j = 0; // points to the end of non-deleted entries.
2596 // Filter out to-be-deleted entries in place.
2597 for (i = 0; i < num; i++) {
2598 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2599 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2600 j++;
2601 }
2602 }
2603
2604 if (j < num) {
2605 persist_data->persist_valid_entries = j;
2606 // Zeroise the remaining entries
2607 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2608 return PERSIST_DEL_KEY_OK;
2609 } else {
2610 // Did not find an entry matching the given fieldname
2611 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2612 }
2613}
2614
2615static int persist_count_keys(const char *fieldname)
2616{
2617 unsigned int i;
2618 unsigned int count;
2619
2620 if (persist_data == NULL) {
2621 return -1;
2622 }
2623
2624 count = 0;
2625 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2626 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2627 count++;
2628 }
2629 }
2630
2631 return count;
2632}
2633
Ken Sumrall160b4d62013-04-22 12:15:39 -07002634/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002635int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002636{
Paul Crowley38132a12016-02-09 09:50:32 +00002637 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002638 SLOGE("Cannot get field when file encrypted");
2639 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002640 }
2641
Ken Sumrall160b4d62013-04-22 12:15:39 -07002642 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002643 /* CRYPTO_GETFIELD_OK is success,
2644 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2645 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2646 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002647 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002648 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2649 int i;
2650 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002651
2652 if (persist_data == NULL) {
2653 load_persistent_data();
2654 if (persist_data == NULL) {
2655 SLOGE("Getfield error, cannot load persistent data");
2656 goto out;
2657 }
2658 }
2659
Rubin Xu85c01f92014-10-13 12:49:54 +01002660 // Read value from persistent entries. If the original value is split into multiple entries,
2661 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002662 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002663 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2664 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2665 // value too small
2666 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2667 goto out;
2668 }
2669 rc = CRYPTO_GETFIELD_OK;
2670
2671 for (i = 1; /* break explicitly */; i++) {
2672 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2673 (int) sizeof(temp_field)) {
2674 // If the fieldname is very long, we stop as soon as it begins to overflow the
2675 // maximum field length. At this point we have in fact fully read out the original
2676 // value because cryptfs_setfield would not allow fields with longer names to be
2677 // written in the first place.
2678 break;
2679 }
2680 if (!persist_get_key(temp_field, temp_value)) {
2681 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2682 // value too small.
2683 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2684 goto out;
2685 }
2686 } else {
2687 // Exhaust all entries.
2688 break;
2689 }
2690 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002691 } else {
2692 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002693 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002694 }
2695
2696out:
2697 return rc;
2698}
2699
2700/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002701int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002702{
Paul Crowley38132a12016-02-09 09:50:32 +00002703 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002704 SLOGE("Cannot set field when file encrypted");
2705 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002706 }
2707
Ken Sumrall160b4d62013-04-22 12:15:39 -07002708 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002709 /* 0 is success, negative values are error */
2710 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002711 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002712 unsigned int field_id;
2713 char temp_field[PROPERTY_KEY_MAX];
2714 unsigned int num_entries;
2715 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002716
2717 if (persist_data == NULL) {
2718 load_persistent_data();
2719 if (persist_data == NULL) {
2720 SLOGE("Setfield error, cannot load persistent data");
2721 goto out;
2722 }
2723 }
2724
2725 property_get("ro.crypto.state", encrypted_state, "");
2726 if (!strcmp(encrypted_state, "encrypted") ) {
2727 encrypted = 1;
2728 }
2729
Rubin Xu85c01f92014-10-13 12:49:54 +01002730 // Compute the number of entries required to store value, each entry can store up to
2731 // (PROPERTY_VALUE_MAX - 1) chars
2732 if (strlen(value) == 0) {
2733 // Empty value also needs one entry to store.
2734 num_entries = 1;
2735 } else {
2736 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2737 }
2738
2739 max_keylen = strlen(fieldname);
2740 if (num_entries > 1) {
2741 // Need an extra "_%d" suffix.
2742 max_keylen += 1 + log10(num_entries);
2743 }
2744 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2745 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002746 goto out;
2747 }
2748
Rubin Xu85c01f92014-10-13 12:49:54 +01002749 // Make sure we have enough space to write the new value
2750 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2751 persist_get_max_entries(encrypted)) {
2752 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2753 goto out;
2754 }
2755
2756 // Now that we know persist_data has enough space for value, let's delete the old field first
2757 // to make up space.
2758 persist_del_keys(fieldname, 0);
2759
2760 if (persist_set_key(fieldname, value, encrypted)) {
2761 // fail to set key, should not happen as we have already checked the available space
2762 SLOGE("persist_set_key() error during setfield()");
2763 goto out;
2764 }
2765
2766 for (field_id = 1; field_id < num_entries; field_id++) {
2767 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
2768
2769 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2770 // fail to set key, should not happen as we have already checked the available space.
2771 SLOGE("persist_set_key() error during setfield()");
2772 goto out;
2773 }
2774 }
2775
Ken Sumrall160b4d62013-04-22 12:15:39 -07002776 /* If we are running encrypted, save the persistent data now */
2777 if (encrypted) {
2778 if (save_persistent_data()) {
2779 SLOGE("Setfield error, cannot save persistent data");
2780 goto out;
2781 }
2782 }
2783
Rubin Xu85c01f92014-10-13 12:49:54 +01002784 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002785
2786out:
2787 return rc;
2788}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002789
2790/* Checks userdata. Attempt to mount the volume if default-
2791 * encrypted.
2792 * On success trigger next init phase and return 0.
2793 * Currently do not handle failure - see TODO below.
2794 */
2795int cryptfs_mount_default_encrypted(void)
2796{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002797 int crypt_type = cryptfs_get_password_type();
2798 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2799 SLOGE("Bad crypt type - error");
2800 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2801 SLOGD("Password is not default - "
2802 "starting min framework to prompt");
2803 property_set("vold.decrypt", "trigger_restart_min_framework");
2804 return 0;
2805 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2806 SLOGD("Password is default - restarting filesystem");
2807 cryptfs_restart_internal(0);
2808 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002809 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002810 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002811 }
2812
Paul Lawrence6bfed202014-07-28 12:47:22 -07002813 /** Corrupt. Allow us to boot into framework, which will detect bad
2814 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002815 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002816 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002817 return 0;
2818}
2819
2820/* Returns type of the password, default, pattern, pin or password.
2821 */
2822int cryptfs_get_password_type(void)
2823{
Paul Crowley38132a12016-02-09 09:50:32 +00002824 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002825 SLOGE("cryptfs_get_password_type not valid for file encryption");
2826 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002827 }
2828
Paul Lawrencef4faa572014-01-29 13:31:03 -08002829 struct crypt_mnt_ftr crypt_ftr;
2830
2831 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2832 SLOGE("Error getting crypt footer and key\n");
2833 return -1;
2834 }
2835
Paul Lawrence6bfed202014-07-28 12:47:22 -07002836 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2837 return -1;
2838 }
2839
Paul Lawrencef4faa572014-01-29 13:31:03 -08002840 return crypt_ftr.crypt_type;
2841}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002842
Paul Lawrence05335c32015-03-05 09:46:23 -08002843const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002844{
Paul Crowley38132a12016-02-09 09:50:32 +00002845 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002846 SLOGE("cryptfs_get_password not valid for file encryption");
2847 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002848 }
2849
Paul Lawrence399317e2014-03-10 13:20:50 -07002850 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002851 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002852 if (now.tv_sec < password_expiry_time) {
2853 return password;
2854 } else {
2855 cryptfs_clear_password();
2856 return 0;
2857 }
2858}
2859
2860void cryptfs_clear_password()
2861{
2862 if (password) {
2863 size_t len = strlen(password);
2864 memset(password, 0, len);
2865 free(password);
2866 password = 0;
2867 password_expiry_time = 0;
2868 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002869}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002870
Paul Lawrence0c247462015-10-29 10:30:57 -07002871int cryptfs_isConvertibleToFBE()
2872{
2873 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2874 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2875}
2876
Paul Lawrence731a7a22015-04-28 22:14:15 +00002877int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
2878{
2879 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
2880 SLOGE("Failed to initialize crypt_ftr");
2881 return -1;
2882 }
2883
2884 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
2885 crypt_ftr->salt, crypt_ftr)) {
2886 SLOGE("Cannot create encrypted master key\n");
2887 return -1;
2888 }
2889
2890 //crypt_ftr->keysize = key_length / 8;
2891 return 0;
2892}
2893
2894int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
2895 unsigned char* master_key)
2896{
2897 int rc;
2898
Paul Lawrence731a7a22015-04-28 22:14:15 +00002899 unsigned char* intermediate_key = 0;
2900 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002901
2902 if (password == 0 || *password == 0) {
2903 password = DEFAULT_PASSWORD;
2904 }
2905
Paul Lawrence731a7a22015-04-28 22:14:15 +00002906 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
2907 &intermediate_key_size);
2908
Paul Lawrence300dae72016-03-11 11:02:52 -08002909 if (rc) {
2910 SLOGE("Can't calculate intermediate key");
2911 return rc;
2912 }
2913
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002914 int N = 1 << ftr->N_factor;
2915 int r = 1 << ftr->r_factor;
2916 int p = 1 << ftr->p_factor;
2917
2918 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
2919
2920 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
2921 ftr->salt, sizeof(ftr->salt), N, r, p,
2922 scrypted_intermediate_key,
2923 sizeof(scrypted_intermediate_key));
2924
2925 free(intermediate_key);
2926
2927 if (rc) {
Paul Lawrence300dae72016-03-11 11:02:52 -08002928 SLOGE("Can't scrypt intermediate key");
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002929 return rc;
2930 }
2931
2932 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
2933 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00002934}
2935
2936int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
2937 const unsigned char* master_key)
2938{
2939 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
2940 ftr);
2941}
Paul Lawrence6e410592016-05-24 14:20:38 -07002942
Eric Biggersb45caaf2017-02-02 14:52:12 -08002943void cryptfs_get_file_encryption_modes(const char **contents_mode_ret,
2944 const char **filenames_mode_ret)
Paul Lawrence6e410592016-05-24 14:20:38 -07002945{
2946 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
Eric Biggersb45caaf2017-02-02 14:52:12 -08002947 fs_mgr_get_file_encryption_modes(rec, contents_mode_ret, filenames_mode_ret);
Paul Lawrence6e410592016-05-24 14:20:38 -07002948}