blob: d42e00bf25100e9d04124875cef277df2f13684e [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 Crowleyf71ace32016-06-02 11:01:19 -070060#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080061#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000062#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080063#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070064#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080065extern "C" {
66#include <crypto_scrypt.h>
67}
Mark Salyzyn3e971272014-01-21 13:27:04 -080068
Mark Salyzyn5eecc442014-02-12 14:16:14 -080069#define UNUSED __attribute__((unused))
70
Ken Sumrall8f869aa2010-12-03 03:47:09 -080071#define DM_CRYPT_BUF_SIZE 4096
72
Jason parks70a4b3f2011-01-28 10:10:47 -060073#define HASH_COUNT 2000
74#define KEY_LEN_BYTES 16
75#define IV_LEN_BYTES 16
76
Ken Sumrall29d8da82011-05-18 17:20:07 -070077#define KEY_IN_FOOTER "footer"
78
Paul Lawrence3bd36d52015-06-09 13:37:44 -070079#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080080
Paul Lawrence3d99eba2015-11-20 07:07:19 -080081#define CRYPTO_BLOCK_DEVICE "userdata"
82
83#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
84
Ken Sumrall29d8da82011-05-18 17:20:07 -070085#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070086#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070087
Ken Sumralle919efe2012-09-29 17:07:41 -070088#define TABLE_LOAD_RETRIES 10
89
Shawn Willden47ba10d2014-09-03 17:07:06 -060090#define RSA_KEY_SIZE 2048
91#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
92#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060093#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070094
Paul Lawrence8e3f4512014-09-08 10:11:17 -070095#define RETRY_MOUNT_ATTEMPTS 10
96#define RETRY_MOUNT_DELAY_SECONDS 1
97
Jason parks70a4b3f2011-01-28 10:10:47 -060098static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070099static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600100static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700101static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800102
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700103/* Should we use keymaster? */
104static int keymaster_check_compatibility()
105{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000106 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700107}
108
109/* Create a new keymaster key and store it in this footer */
110static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
111{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800112 if (ftr->keymaster_blob_size) {
113 SLOGI("Already have key");
114 return 0;
115 }
116
Janis Danisevskis015ec302017-01-31 11:31:08 +0000117 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
118 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
119 &ftr->keymaster_blob_size);
120 if (rc) {
121 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
122 SLOGE("Keymaster key blob to large)");
123 ftr->keymaster_blob_size = 0;
124 }
125 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700126 return -1;
127 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000128 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700129}
130
Shawn Willdene17a9c42014-09-08 13:04:08 -0600131/* This signs the given object using the keymaster key. */
132static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600133 const unsigned char *object,
134 const size_t object_size,
135 unsigned char **signature,
136 size_t *signature_size)
137{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600138 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600139 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600140 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600141
Shawn Willdene17a9c42014-09-08 13:04:08 -0600142 // To sign a message with RSA, the message must satisfy two
143 // constraints:
144 //
145 // 1. The message, when interpreted as a big-endian numeric value, must
146 // be strictly less than the public modulus of the RSA key. Note
147 // that because the most significant bit of the public modulus is
148 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
149 // key), an n-bit message with most significant bit 0 always
150 // satisfies this requirement.
151 //
152 // 2. The message must have the same length in bits as the public
153 // modulus of the RSA key. This requirement isn't mathematically
154 // necessary, but is necessary to ensure consistency in
155 // implementations.
156 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600157 case KDF_SCRYPT_KEYMASTER:
158 // This ensures the most significant byte of the signed message
159 // is zero. We could have zero-padded to the left instead, but
160 // this approach is slightly more robust against changes in
161 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600162 // so) because we really should be using a proper deterministic
163 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800164 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600165 SLOGI("Signing safely-padded object");
166 break;
167 default:
168 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000169 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600170 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000171 return keymaster_sign_object_for_cryptfs_scrypt(ftr->keymaster_blob, ftr->keymaster_blob_size,
172 KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign, to_sign_size, signature, signature_size);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600173}
174
Paul Lawrence399317e2014-03-10 13:20:50 -0700175/* Store password when userdata is successfully decrypted and mounted.
176 * Cleared by cryptfs_clear_password
177 *
178 * To avoid a double prompt at boot, we need to store the CryptKeeper
179 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
180 * Since the entire framework is torn down and rebuilt after encryption,
181 * we have to use a daemon or similar to store the password. Since vold
182 * is secured against IPC except from system processes, it seems a reasonable
183 * place to store this.
184 *
185 * password should be cleared once it has been used.
186 *
187 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800188 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700189static char* password = 0;
190static int password_expiry_time = 0;
191static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800192
Josh Gaofec44372017-08-28 13:22:55 -0700193enum class RebootType {reboot, recovery, shutdown};
194static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700195{
Josh Gaofec44372017-08-28 13:22:55 -0700196 switch (rt) {
197 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800198 property_set(ANDROID_RB_PROPERTY, "reboot");
199 break;
200
Josh Gaofec44372017-08-28 13:22:55 -0700201 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800202 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
203 break;
204
Josh Gaofec44372017-08-28 13:22:55 -0700205 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800206 property_set(ANDROID_RB_PROPERTY, "shutdown");
207 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700208 }
Paul Lawrence87999172014-02-20 12:21:31 -0800209
Ken Sumralladfba362013-06-04 16:37:52 -0700210 sleep(20);
211
212 /* Shouldn't get here, reboot should happen before sleep times out */
213 return;
214}
215
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800216static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
217{
218 memset(io, 0, dataSize);
219 io->data_size = dataSize;
220 io->data_start = sizeof(struct dm_ioctl);
221 io->version[0] = 4;
222 io->version[1] = 0;
223 io->version[2] = 0;
224 io->flags = flags;
225 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100226 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800227 }
228}
229
Kenny Rootc4c70f12013-06-14 12:11:38 -0700230/**
231 * Gets the default device scrypt parameters for key derivation time tuning.
232 * The parameters should lead to about one second derivation time for the
233 * given device.
234 */
235static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700236 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000237 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700238
Paul Crowley63c18d32016-02-10 14:02:47 +0000239 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
240 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
241 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
242 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700243 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000244 ftr->N_factor = Nf;
245 ftr->r_factor = rf;
246 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700247}
248
Ken Sumrall3ed82362011-01-28 23:31:16 -0800249static unsigned int get_fs_size(char *dev)
250{
251 int fd, block_size;
252 struct ext4_super_block sb;
253 off64_t len;
254
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700255 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800256 SLOGE("Cannot open device to get filesystem size ");
257 return 0;
258 }
259
260 if (lseek64(fd, 1024, SEEK_SET) < 0) {
261 SLOGE("Cannot seek to superblock");
262 return 0;
263 }
264
265 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
266 SLOGE("Cannot read superblock");
267 return 0;
268 }
269
270 close(fd);
271
Daniel Rosenberge82df162014-08-15 22:19:23 +0000272 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
273 SLOGE("Not a valid ext4 superblock");
274 return 0;
275 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800276 block_size = 1024 << sb.s_log_block_size;
277 /* compute length in bytes */
278 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
279
280 /* return length in sectors */
281 return (unsigned int) (len / 512);
282}
283
Ken Sumrall160b4d62013-04-22 12:15:39 -0700284static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
285{
286 static int cached_data = 0;
287 static off64_t cached_off = 0;
288 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
289 int fd;
290 char key_loc[PROPERTY_VALUE_MAX];
291 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700292 int rc = -1;
293
294 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700295 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700296
297 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700298 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700299 SLOGE("Cannot open real block device %s\n", real_blkdev);
300 return -1;
301 }
302
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900303 unsigned long nr_sec = 0;
304 get_blkdev_size(fd, &nr_sec);
305 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700306 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
307 * encryption info footer and key, and plenty of bytes to spare for future
308 * growth.
309 */
310 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
311 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
312 cached_data = 1;
313 } else {
314 SLOGE("Cannot get size of block device %s\n", real_blkdev);
315 }
316 close(fd);
317 } else {
318 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
319 cached_off = 0;
320 cached_data = 1;
321 }
322 }
323
324 if (cached_data) {
325 if (metadata_fname) {
326 *metadata_fname = cached_metadata_fname;
327 }
328 if (off) {
329 *off = cached_off;
330 }
331 rc = 0;
332 }
333
334 return rc;
335}
336
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800337/* Set sha256 checksum in structure */
338static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
339{
340 SHA256_CTX c;
341 SHA256_Init(&c);
342 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
343 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
344 SHA256_Final(crypt_ftr->sha256, &c);
345}
346
Ken Sumralle8744072011-01-18 22:01:55 -0800347/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800348 * update the failed mount count but not change the key.
349 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700350static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800351{
352 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800353 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700354 /* starting_off is set to the SEEK_SET offset
355 * where the crypto structure starts
356 */
357 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800358 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700359 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700360 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800361
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800362 set_ftr_sha(crypt_ftr);
363
Ken Sumrall160b4d62013-04-22 12:15:39 -0700364 if (get_crypt_ftr_info(&fname, &starting_off)) {
365 SLOGE("Unable to get crypt_ftr_info\n");
366 return -1;
367 }
368 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700369 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700370 return -1;
371 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700372 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700373 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700374 return -1;
375 }
376
377 /* Seek to the start of the crypt footer */
378 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
379 SLOGE("Cannot seek to real block device footer\n");
380 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800381 }
382
383 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
384 SLOGE("Cannot write real block device footer\n");
385 goto errout;
386 }
387
Ken Sumrall3be890f2011-09-14 16:53:46 -0700388 fstat(fd, &statbuf);
389 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700390 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700391 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800392 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800393 goto errout;
394 }
395 }
396
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800397 /* Success! */
398 rc = 0;
399
400errout:
401 close(fd);
402 return rc;
403
404}
405
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800406static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
407{
408 struct crypt_mnt_ftr copy;
409 memcpy(&copy, crypt_ftr, sizeof(copy));
410 set_ftr_sha(&copy);
411 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
412}
413
Ken Sumrall160b4d62013-04-22 12:15:39 -0700414static inline int unix_read(int fd, void* buff, int len)
415{
416 return TEMP_FAILURE_RETRY(read(fd, buff, len));
417}
418
419static inline int unix_write(int fd, const void* buff, int len)
420{
421 return TEMP_FAILURE_RETRY(write(fd, buff, len));
422}
423
424static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
425{
426 memset(pdata, 0, len);
427 pdata->persist_magic = PERSIST_DATA_MAGIC;
428 pdata->persist_valid_entries = 0;
429}
430
431/* A routine to update the passed in crypt_ftr to the lastest version.
432 * fd is open read/write on the device that holds the crypto footer and persistent
433 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
434 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
435 */
436static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
437{
Kenny Root7434b312013-06-14 11:29:53 -0700438 int orig_major = crypt_ftr->major_version;
439 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700440
Kenny Root7434b312013-06-14 11:29:53 -0700441 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
442 struct crypt_persist_data *pdata;
443 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700444
Kenny Rootc4c70f12013-06-14 12:11:38 -0700445 SLOGW("upgrading crypto footer to 1.1");
446
Wei Wang4375f1b2017-02-24 17:43:01 -0800447 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700448 if (pdata == NULL) {
449 SLOGE("Cannot allocate persisent data\n");
450 return;
451 }
452 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
453
454 /* Need to initialize the persistent data area */
455 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
456 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100457 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700458 return;
459 }
460 /* Write all zeros to the first copy, making it invalid */
461 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
462
463 /* Write a valid but empty structure to the second copy */
464 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
465 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
466
467 /* Update the footer */
468 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
469 crypt_ftr->persist_data_offset[0] = pdata_offset;
470 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
471 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100472 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700473 }
474
Paul Lawrencef4faa572014-01-29 13:31:03 -0800475 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700476 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800477 /* But keep the old kdf_type.
478 * It will get updated later to KDF_SCRYPT after the password has been verified.
479 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700480 crypt_ftr->kdf_type = KDF_PBKDF2;
481 get_device_scrypt_params(crypt_ftr);
482 crypt_ftr->minor_version = 2;
483 }
484
Paul Lawrencef4faa572014-01-29 13:31:03 -0800485 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
486 SLOGW("upgrading crypto footer to 1.3");
487 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
488 crypt_ftr->minor_version = 3;
489 }
490
Kenny Root7434b312013-06-14 11:29:53 -0700491 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
492 if (lseek64(fd, offset, SEEK_SET) == -1) {
493 SLOGE("Cannot seek to crypt footer\n");
494 return;
495 }
496 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700497 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700498}
499
500
501static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800502{
503 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800504 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700505 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800506 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700507 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700508 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800509
Ken Sumrall160b4d62013-04-22 12:15:39 -0700510 if (get_crypt_ftr_info(&fname, &starting_off)) {
511 SLOGE("Unable to get crypt_ftr_info\n");
512 return -1;
513 }
514 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700515 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700516 return -1;
517 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700518 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700519 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700520 return -1;
521 }
522
523 /* Make sure it's 16 Kbytes in length */
524 fstat(fd, &statbuf);
525 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
526 SLOGE("footer file %s is not the expected size!\n", fname);
527 goto errout;
528 }
529
530 /* Seek to the start of the crypt footer */
531 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
532 SLOGE("Cannot seek to real block device footer\n");
533 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800534 }
535
536 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
537 SLOGE("Cannot read real block device footer\n");
538 goto errout;
539 }
540
541 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700542 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800543 goto errout;
544 }
545
Kenny Rootc96a5f82013-06-14 12:08:28 -0700546 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
547 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
548 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800549 goto errout;
550 }
551
Kenny Rootc96a5f82013-06-14 12:08:28 -0700552 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
553 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
554 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800555 }
556
Ken Sumrall160b4d62013-04-22 12:15:39 -0700557 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
558 * copy on disk before returning.
559 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700560 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700561 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800562 }
563
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800564 /* Success! */
565 rc = 0;
566
567errout:
568 close(fd);
569 return rc;
570}
571
Ken Sumrall160b4d62013-04-22 12:15:39 -0700572static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
573{
574 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
575 crypt_ftr->persist_data_offset[1]) {
576 SLOGE("Crypt_ftr persist data regions overlap");
577 return -1;
578 }
579
580 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
581 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
582 return -1;
583 }
584
585 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
586 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
587 CRYPT_FOOTER_OFFSET) {
588 SLOGE("Persistent data extends past crypto footer");
589 return -1;
590 }
591
592 return 0;
593}
594
595static int load_persistent_data(void)
596{
597 struct crypt_mnt_ftr crypt_ftr;
598 struct crypt_persist_data *pdata = NULL;
599 char encrypted_state[PROPERTY_VALUE_MAX];
600 char *fname;
601 int found = 0;
602 int fd;
603 int ret;
604 int i;
605
606 if (persist_data) {
607 /* Nothing to do, we've already loaded or initialized it */
608 return 0;
609 }
610
611
612 /* If not encrypted, just allocate an empty table and initialize it */
613 property_get("ro.crypto.state", encrypted_state, "");
614 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800615 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700616 if (pdata) {
617 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
618 persist_data = pdata;
619 return 0;
620 }
621 return -1;
622 }
623
624 if(get_crypt_ftr_and_key(&crypt_ftr)) {
625 return -1;
626 }
627
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700628 if ((crypt_ftr.major_version < 1)
629 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700630 SLOGE("Crypt_ftr version doesn't support persistent data");
631 return -1;
632 }
633
634 if (get_crypt_ftr_info(&fname, NULL)) {
635 return -1;
636 }
637
638 ret = validate_persistent_data_storage(&crypt_ftr);
639 if (ret) {
640 return -1;
641 }
642
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700643 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700644 if (fd < 0) {
645 SLOGE("Cannot open %s metadata file", fname);
646 return -1;
647 }
648
Wei Wang4375f1b2017-02-24 17:43:01 -0800649 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800650 if (pdata == NULL) {
651 SLOGE("Cannot allocate memory for persistent data");
652 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700653 }
654
655 for (i = 0; i < 2; i++) {
656 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
657 SLOGE("Cannot seek to read persistent data on %s", fname);
658 goto err2;
659 }
660 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
661 SLOGE("Error reading persistent data on iteration %d", i);
662 goto err2;
663 }
664 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
665 found = 1;
666 break;
667 }
668 }
669
670 if (!found) {
671 SLOGI("Could not find valid persistent data, creating");
672 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
673 }
674
675 /* Success */
676 persist_data = pdata;
677 close(fd);
678 return 0;
679
680err2:
681 free(pdata);
682
683err:
684 close(fd);
685 return -1;
686}
687
688static int save_persistent_data(void)
689{
690 struct crypt_mnt_ftr crypt_ftr;
691 struct crypt_persist_data *pdata;
692 char *fname;
693 off64_t write_offset;
694 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700695 int fd;
696 int ret;
697
698 if (persist_data == NULL) {
699 SLOGE("No persistent data to save");
700 return -1;
701 }
702
703 if(get_crypt_ftr_and_key(&crypt_ftr)) {
704 return -1;
705 }
706
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700707 if ((crypt_ftr.major_version < 1)
708 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700709 SLOGE("Crypt_ftr version doesn't support persistent data");
710 return -1;
711 }
712
713 ret = validate_persistent_data_storage(&crypt_ftr);
714 if (ret) {
715 return -1;
716 }
717
718 if (get_crypt_ftr_info(&fname, NULL)) {
719 return -1;
720 }
721
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700722 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700723 if (fd < 0) {
724 SLOGE("Cannot open %s metadata file", fname);
725 return -1;
726 }
727
Wei Wang4375f1b2017-02-24 17:43:01 -0800728 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700729 if (pdata == NULL) {
730 SLOGE("Cannot allocate persistant data");
731 goto err;
732 }
733
734 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
735 SLOGE("Cannot seek to read persistent data on %s", fname);
736 goto err2;
737 }
738
739 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
740 SLOGE("Error reading persistent data before save");
741 goto err2;
742 }
743
744 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
745 /* The first copy is the curent valid copy, so write to
746 * the second copy and erase this one */
747 write_offset = crypt_ftr.persist_data_offset[1];
748 erase_offset = crypt_ftr.persist_data_offset[0];
749 } else {
750 /* The second copy must be the valid copy, so write to
751 * the first copy, and erase the second */
752 write_offset = crypt_ftr.persist_data_offset[0];
753 erase_offset = crypt_ftr.persist_data_offset[1];
754 }
755
756 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100757 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700758 SLOGE("Cannot seek to write persistent data");
759 goto err2;
760 }
761 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
762 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100763 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700764 SLOGE("Cannot seek to erase previous persistent data");
765 goto err2;
766 }
767 fsync(fd);
768 memset(pdata, 0, crypt_ftr.persist_data_size);
769 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
770 (int) crypt_ftr.persist_data_size) {
771 SLOGE("Cannot write to erase previous persistent data");
772 goto err2;
773 }
774 fsync(fd);
775 } else {
776 SLOGE("Cannot write to save persistent data");
777 goto err2;
778 }
779
780 /* Success */
781 free(pdata);
782 close(fd);
783 return 0;
784
785err2:
786 free(pdata);
787err:
788 close(fd);
789 return -1;
790}
791
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800792/* Convert a binary key of specified length into an ascii hex string equivalent,
793 * without the leading 0x and with null termination
794 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700795static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700796 unsigned int keysize, char *master_key_ascii) {
797 unsigned int i, a;
798 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800799
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700800 for (i=0, a=0; i<keysize; i++, a+=2) {
801 /* For each byte, write out two ascii hex digits */
802 nibble = (master_key[i] >> 4) & 0xf;
803 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800804
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700805 nibble = master_key[i] & 0xf;
806 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
807 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800808
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700809 /* Add the null termination */
810 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800811
812}
813
Jeff Sharkey9c484982015-03-31 10:35:33 -0700814static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
815 const unsigned char *master_key, const char *real_blk_name,
816 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800817 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800818 struct dm_ioctl *io;
819 struct dm_target_spec *tgt;
820 char *crypt_params;
821 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800822 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800823 int i;
824
825 io = (struct dm_ioctl *) buffer;
826
827 /* Load the mapping table for this device */
828 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
829
830 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
831 io->target_count = 1;
832 tgt->status = 0;
833 tgt->sector_start = 0;
834 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700835 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800836
837 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
838 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800839
840 buff_offset = crypt_params - buffer;
841 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
842 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
843 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800844 crypt_params += strlen(crypt_params) + 1;
845 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
846 tgt->next = crypt_params - buffer;
847
848 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
849 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
850 break;
851 }
852 usleep(500000);
853 }
854
855 if (i == TABLE_LOAD_RETRIES) {
856 /* We failed to load the table, return an error */
857 return -1;
858 } else {
859 return i + 1;
860 }
861}
862
863
864static int get_dm_crypt_version(int fd, const char *name, int *version)
865{
866 char buffer[DM_CRYPT_BUF_SIZE];
867 struct dm_ioctl *io;
868 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800869
870 io = (struct dm_ioctl *) buffer;
871
872 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
873
874 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
875 return -1;
876 }
877
878 /* Iterate over the returned versions, looking for name of "crypt".
879 * When found, get and return the version.
880 */
881 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
882 while (v->next) {
883 if (! strcmp(v->name, "crypt")) {
884 /* We found the crypt driver, return the version, and get out */
885 version[0] = v->version[0];
886 version[1] = v->version[1];
887 version[2] = v->version[2];
888 return 0;
889 }
890 v = (struct dm_target_versions *)(((char *)v) + v->next);
891 }
892
893 return -1;
894}
895
Jeff Sharkey9c484982015-03-31 10:35:33 -0700896static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
897 const unsigned char *master_key, const char *real_blk_name,
898 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800899 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800900 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800901 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -0700902 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800903 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800904 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800905 int version[3];
Wei Wang4375f1b2017-02-24 17:43:01 -0800906 const char *extra_params;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800907 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800908
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700909 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800910 SLOGE("Cannot open device-mapper\n");
911 goto errout;
912 }
913
914 io = (struct dm_ioctl *) buffer;
915
916 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800917 err = ioctl(fd, DM_DEV_CREATE, io);
918 if (err) {
919 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800920 goto errout;
921 }
922
923 /* Get the device status, in particular, the name of it's device file */
924 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
925 if (ioctl(fd, DM_DEV_STATUS, io)) {
926 SLOGE("Cannot retrieve dm-crypt device status\n");
927 goto errout;
928 }
929 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
930 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
931
Ken Sumralldb5e0262013-02-05 17:39:48 -0800932 extra_params = "";
933 if (! get_dm_crypt_version(fd, name, version)) {
934 /* Support for allow_discards was added in version 1.11.0 */
935 if ((version[0] >= 2) ||
936 ((version[0] == 1) && (version[1] >= 11))) {
937 extra_params = "1 allow_discards";
938 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
939 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700940 }
941
Ken Sumralldb5e0262013-02-05 17:39:48 -0800942 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
943 fd, extra_params);
944 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800945 SLOGE("Cannot load dm-crypt mapping table.\n");
946 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800947 } else if (load_count > 1) {
948 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800949 }
950
951 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800952 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800953
954 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
955 SLOGE("Cannot resume the dm-crypt device\n");
956 goto errout;
957 }
958
959 /* We made it here with no errors. Woot! */
960 retval = 0;
961
962errout:
963 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
964
965 return retval;
966}
967
Wei Wang4375f1b2017-02-24 17:43:01 -0800968static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800969{
970 int fd;
971 char buffer[DM_CRYPT_BUF_SIZE];
972 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800973 int retval = -1;
974
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700975 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800976 SLOGE("Cannot open device-mapper\n");
977 goto errout;
978 }
979
980 io = (struct dm_ioctl *) buffer;
981
982 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
983 if (ioctl(fd, DM_DEV_REMOVE, io)) {
984 SLOGE("Cannot remove dm-crypt device\n");
985 goto errout;
986 }
987
988 /* We made it here with no errors. Woot! */
989 retval = 0;
990
991errout:
992 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
993
994 return retval;
995
996}
997
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700998static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -0800999 unsigned char *ikey, void *params UNUSED)
1000{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001001 SLOGI("Using pbkdf2 for cryptfs KDF");
1002
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001003 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001004 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1005 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1006 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001007}
1008
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001009static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001010 unsigned char *ikey, void *params)
1011{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001012 SLOGI("Using scrypt for cryptfs KDF");
1013
Kenny Rootc4c70f12013-06-14 12:11:38 -07001014 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1015
1016 int N = 1 << ftr->N_factor;
1017 int r = 1 << ftr->r_factor;
1018 int p = 1 << ftr->p_factor;
1019
1020 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001021 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001022 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1023 salt, SALT_LEN, N, r, p, ikey,
1024 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001025
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001026 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001027}
1028
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001029static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1030 unsigned char *ikey, void *params)
1031{
1032 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1033
1034 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001035 size_t signature_size;
1036 unsigned char* signature;
1037 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1038
1039 int N = 1 << ftr->N_factor;
1040 int r = 1 << ftr->r_factor;
1041 int p = 1 << ftr->p_factor;
1042
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001043 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1044 salt, SALT_LEN, N, r, p, ikey,
1045 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001046
1047 if (rc) {
1048 SLOGE("scrypt failed");
1049 return -1;
1050 }
1051
Shawn Willdene17a9c42014-09-08 13:04:08 -06001052 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1053 &signature, &signature_size)) {
1054 SLOGE("Signing failed");
1055 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001056 }
1057
1058 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1059 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1060 free(signature);
1061
1062 if (rc) {
1063 SLOGE("scrypt failed");
1064 return -1;
1065 }
1066
1067 return 0;
1068}
1069
1070static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1071 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001072 unsigned char *encrypted_master_key,
1073 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001074{
1075 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1076 EVP_CIPHER_CTX e_ctx;
1077 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001078 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001079
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001080 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001081 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001082
1083 switch (crypt_ftr->kdf_type) {
1084 case KDF_SCRYPT_KEYMASTER:
1085 if (keymaster_create_key(crypt_ftr)) {
1086 SLOGE("keymaster_create_key failed");
1087 return -1;
1088 }
1089
1090 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1091 SLOGE("scrypt failed");
1092 return -1;
1093 }
1094 break;
1095
1096 case KDF_SCRYPT:
1097 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1098 SLOGE("scrypt failed");
1099 return -1;
1100 }
1101 break;
1102
1103 default:
1104 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001105 return -1;
1106 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001107
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001108 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001109 EVP_CIPHER_CTX_init(&e_ctx);
1110 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001111 SLOGE("EVP_EncryptInit failed\n");
1112 return -1;
1113 }
1114 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001115
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001116 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001117 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001118 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001119 SLOGE("EVP_EncryptUpdate failed\n");
1120 return -1;
1121 }
Adam Langley889c4f12014-09-03 14:23:13 -07001122 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001123 SLOGE("EVP_EncryptFinal failed\n");
1124 return -1;
1125 }
1126
1127 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1128 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1129 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001130 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001131
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001132 /* Store the scrypt of the intermediate key, so we can validate if it's a
1133 password error or mount error when things go wrong.
1134 Note there's no need to check for errors, since if this is incorrect, we
1135 simply won't wipe userdata, which is the correct default behavior
1136 */
1137 int N = 1 << crypt_ftr->N_factor;
1138 int r = 1 << crypt_ftr->r_factor;
1139 int p = 1 << crypt_ftr->p_factor;
1140
1141 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1142 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1143 crypt_ftr->scrypted_intermediate_key,
1144 sizeof(crypt_ftr->scrypted_intermediate_key));
1145
1146 if (rc) {
1147 SLOGE("encrypt_master_key: crypto_scrypt failed");
1148 }
1149
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001150 EVP_CIPHER_CTX_cleanup(&e_ctx);
1151
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001152 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001153}
1154
Paul Lawrence731a7a22015-04-28 22:14:15 +00001155static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001156 unsigned char *encrypted_master_key,
1157 unsigned char *decrypted_master_key,
1158 kdf_func kdf, void *kdf_params,
1159 unsigned char** intermediate_key,
1160 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161{
1162 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 -08001163 EVP_CIPHER_CTX d_ctx;
1164 int decrypted_len, final_len;
1165
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001166 /* Turn the password into an intermediate key and IV that can decrypt the
1167 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001168 if (kdf(passwd, salt, ikey, kdf_params)) {
1169 SLOGE("kdf failed");
1170 return -1;
1171 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001172
1173 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001174 EVP_CIPHER_CTX_init(&d_ctx);
1175 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001176 return -1;
1177 }
1178 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1179 /* Decrypt the master key */
1180 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1181 encrypted_master_key, KEY_LEN_BYTES)) {
1182 return -1;
1183 }
Adam Langley889c4f12014-09-03 14:23:13 -07001184 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001185 return -1;
1186 }
1187
1188 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1189 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001190 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001191
1192 /* Copy intermediate key if needed by params */
1193 if (intermediate_key && intermediate_key_size) {
1194 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001195 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001196 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1197 *intermediate_key_size = KEY_LEN_BYTES;
1198 }
1199 }
1200
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001201 EVP_CIPHER_CTX_cleanup(&d_ctx);
1202
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001203 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001204}
1205
Kenny Rootc4c70f12013-06-14 12:11:38 -07001206static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001207{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001208 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001209 *kdf = scrypt_keymaster;
1210 *kdf_params = ftr;
1211 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001212 *kdf = scrypt;
1213 *kdf_params = ftr;
1214 } else {
1215 *kdf = pbkdf2;
1216 *kdf_params = NULL;
1217 }
1218}
1219
Paul Lawrence731a7a22015-04-28 22:14:15 +00001220static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001221 struct crypt_mnt_ftr *crypt_ftr,
1222 unsigned char** intermediate_key,
1223 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001224{
1225 kdf_func kdf;
1226 void *kdf_params;
1227 int ret;
1228
1229 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001230 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1231 decrypted_master_key, kdf, kdf_params,
1232 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001233 if (ret != 0) {
1234 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001235 }
1236
1237 return ret;
1238}
1239
Wei Wang4375f1b2017-02-24 17:43:01 -08001240static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001241 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001242 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001243 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001244
1245 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001246 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001247 read(fd, key_buf, sizeof(key_buf));
1248 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001249 close(fd);
1250
1251 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001252 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001253}
1254
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001255int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001256{
Greg Hackmann955653e2014-09-24 14:55:20 -07001257 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001258#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259
1260 /* Now umount the tmpfs filesystem */
1261 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001262 if (umount(mountpoint) == 0) {
1263 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001264 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001265
1266 if (errno == EINVAL) {
1267 /* EINVAL is returned if the directory is not a mountpoint,
1268 * i.e. there is no filesystem mounted there. So just get out.
1269 */
1270 break;
1271 }
1272
1273 err = errno;
1274
1275 /* If allowed, be increasingly aggressive before the last two retries */
1276 if (kill) {
1277 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1278 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001279 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001280 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1281 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001282 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001283 }
1284 }
1285
1286 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001287 }
1288
1289 if (i < WAIT_UNMOUNT_COUNT) {
1290 SLOGD("unmounting %s succeeded\n", mountpoint);
1291 rc = 0;
1292 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001293 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001294 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001295 rc = -1;
1296 }
1297
1298 return rc;
1299}
1300
Wei Wang42e38102017-06-07 10:46:12 -07001301static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001302{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001303 // NOTE: post_fs_data results in init calling back around to vold, so all
1304 // callers to this method must be async
1305
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001306 /* Do the prep of the /data filesystem */
1307 property_set("vold.post_fs_data_done", "0");
1308 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001309 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001310
Ken Sumrallc5872692013-05-14 15:26:31 -07001311 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001312 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001313 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001314 std::chrono::seconds(15))) {
1315 /* We timed out to prep /data in time. Continue wait. */
1316 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001317 }
Wei Wang42e38102017-06-07 10:46:12 -07001318 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001319}
1320
Paul Lawrence74f29f12014-08-28 15:54:10 -07001321static void cryptfs_set_corrupt()
1322{
1323 // Mark the footer as bad
1324 struct crypt_mnt_ftr crypt_ftr;
1325 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1326 SLOGE("Failed to get crypto footer - panic");
1327 return;
1328 }
1329
1330 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1331 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1332 SLOGE("Failed to set crypto footer - panic");
1333 return;
1334 }
1335}
1336
1337static void cryptfs_trigger_restart_min_framework()
1338{
1339 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1340 SLOGE("Failed to mount tmpfs on data - panic");
1341 return;
1342 }
1343
1344 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1345 SLOGE("Failed to trigger post fs data - panic");
1346 return;
1347 }
1348
1349 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1350 SLOGE("Failed to trigger restart min framework - panic");
1351 return;
1352 }
1353}
1354
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001355/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001356static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001357{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001358 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001359 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001360 static int restart_successful = 0;
1361
1362 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001363 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001364 SLOGE("Encrypted filesystem not validated, aborting");
1365 return -1;
1366 }
1367
1368 if (restart_successful) {
1369 SLOGE("System already restarted with encrypted disk, aborting");
1370 return -1;
1371 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001372
Paul Lawrencef4faa572014-01-29 13:31:03 -08001373 if (restart_main) {
1374 /* Here is where we shut down the framework. The init scripts
1375 * start all services in one of three classes: core, main or late_start.
1376 * On boot, we start core and main. Now, we stop main, but not core,
1377 * as core includes vold and a few other really important things that
1378 * we need to keep running. Once main has stopped, we should be able
1379 * to umount the tmpfs /data, then mount the encrypted /data.
1380 * We then restart the class main, and also the class late_start.
1381 * At the moment, I've only put a few things in late_start that I know
1382 * are not needed to bring up the framework, and that also cause problems
1383 * with unmounting the tmpfs /data, but I hope to add add more services
1384 * to the late_start class as we optimize this to decrease the delay
1385 * till the user is asked for the password to the filesystem.
1386 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001387
Paul Lawrencef4faa572014-01-29 13:31:03 -08001388 /* The init files are setup to stop the class main when vold.decrypt is
1389 * set to trigger_reset_main.
1390 */
1391 property_set("vold.decrypt", "trigger_reset_main");
1392 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001393
Paul Lawrencef4faa572014-01-29 13:31:03 -08001394 /* Ugh, shutting down the framework is not synchronous, so until it
1395 * can be fixed, this horrible hack will wait a moment for it all to
1396 * shut down before proceeding. Without it, some devices cannot
1397 * restart the graphics services.
1398 */
1399 sleep(2);
1400 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001401
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001402 /* Now that the framework is shutdown, we should be able to umount()
1403 * the tmpfs filesystem, and mount the real one.
1404 */
1405
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001406 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1407 if (strlen(crypto_blkdev) == 0) {
1408 SLOGE("fs_crypto_blkdev not set\n");
1409 return -1;
1410 }
1411
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001412 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001413 /* If ro.crypto.readonly is set to 1, mount the decrypted
1414 * filesystem readonly. This is used when /data is mounted by
1415 * recovery mode.
1416 */
1417 char ro_prop[PROPERTY_VALUE_MAX];
1418 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001419 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001420 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001421 rec->flags |= MS_RDONLY;
1422 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001423
Ken Sumralle5032c42012-04-01 23:58:44 -07001424 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001425 int retries = RETRY_MOUNT_ATTEMPTS;
1426 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001427
1428 /*
1429 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1430 * partitions in the fsck domain.
1431 */
1432 if (setexeccon(secontextFsck())){
1433 SLOGE("Failed to setexeccon");
1434 return -1;
1435 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001436 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001437 crypto_blkdev, 0))
1438 != 0) {
1439 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1440 /* TODO: invoke something similar to
1441 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1442 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1443 SLOGI("Failed to mount %s because it is busy - waiting",
1444 crypto_blkdev);
1445 if (--retries) {
1446 sleep(RETRY_MOUNT_DELAY_SECONDS);
1447 } else {
1448 /* Let's hope that a reboot clears away whatever is keeping
1449 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001450 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001451 }
1452 } else {
1453 SLOGE("Failed to mount decrypted data");
1454 cryptfs_set_corrupt();
1455 cryptfs_trigger_restart_min_framework();
1456 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001457 if (setexeccon(NULL)) {
1458 SLOGE("Failed to setexeccon");
1459 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001460 return -1;
1461 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001462 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001463 if (setexeccon(NULL)) {
1464 SLOGE("Failed to setexeccon");
1465 return -1;
1466 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001467
Ken Sumralle5032c42012-04-01 23:58:44 -07001468 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001469 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001470 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001471
1472 /* startup service classes main and late_start */
1473 property_set("vold.decrypt", "trigger_restart_framework");
1474 SLOGD("Just triggered restart_framework\n");
1475
1476 /* Give it a few moments to get started */
1477 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001478 }
1479
Ken Sumrall0cc16632011-01-18 20:32:26 -08001480 if (rc == 0) {
1481 restart_successful = 1;
1482 }
1483
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001484 return rc;
1485}
1486
Paul Lawrencef4faa572014-01-29 13:31:03 -08001487int cryptfs_restart(void)
1488{
Paul Lawrence05335c32015-03-05 09:46:23 -08001489 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001490 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001491 SLOGE("cryptfs_restart not valid for file encryption:");
1492 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001493 }
1494
Paul Lawrencef4faa572014-01-29 13:31:03 -08001495 /* Call internal implementation forcing a restart of main service group */
1496 return cryptfs_restart_internal(1);
1497}
1498
Wei Wang4375f1b2017-02-24 17:43:01 -08001499static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001500{
1501 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001502 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001503 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001504
1505 property_get("ro.crypto.state", encrypted_state, "");
1506 if (strcmp(encrypted_state, "encrypted") ) {
1507 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001508 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001509 }
1510
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001511 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001512 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001513 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001514 }
1515
Ken Sumrall160b4d62013-04-22 12:15:39 -07001516 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001517 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001518
Ken Sumralle1a45852011-12-14 21:24:27 -08001519 /*
1520 * Only report this error if key_loc is a file and it exists.
1521 * If the device was never encrypted, and /data is not mountable for
1522 * some reason, returning 1 should prevent the UI from presenting the
1523 * a "enter password" screen, or worse, a "press button to wipe the
1524 * device" screen.
1525 */
1526 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1527 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001528 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001529 } else {
1530 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001531 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001532 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001533 }
1534
Paul Lawrence74f29f12014-08-28 15:54:10 -07001535 // Test for possible error flags
1536 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1537 SLOGE("Encryption process is partway completed\n");
1538 return CRYPTO_COMPLETE_PARTIAL;
1539 }
1540
1541 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1542 SLOGE("Encryption process was interrupted but cannot continue\n");
1543 return CRYPTO_COMPLETE_INCONSISTENT;
1544 }
1545
1546 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1547 SLOGE("Encryption is successful but data is corrupt\n");
1548 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001549 }
1550
1551 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001552 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001553}
1554
Paul Lawrencef4faa572014-01-29 13:31:03 -08001555static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001556 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001557{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001558 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001559 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001560 char crypto_blkdev[MAXPATHLEN];
1561 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001562 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001563 unsigned int orig_failed_decrypt_count;
1564 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001565 int use_keymaster = 0;
1566 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001567 unsigned char* intermediate_key = 0;
1568 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001569 int N = 1 << crypt_ftr->N_factor;
1570 int r = 1 << crypt_ftr->r_factor;
1571 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001572
Paul Lawrencef4faa572014-01-29 13:31:03 -08001573 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1574 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001575
Paul Lawrencef4faa572014-01-29 13:31:03 -08001576 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001577 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1578 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001579 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001580 rc = -1;
1581 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001582 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001583 }
1584
Paul Crowleye2ee1522017-09-26 14:05:26 -07001585 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001586
Paul Lawrence74f29f12014-08-28 15:54:10 -07001587 // Create crypto block device - all (non fatal) code paths
1588 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001589 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1590 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001591 SLOGE("Error creating decrypted block device\n");
1592 rc = -1;
1593 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001594 }
1595
Paul Lawrence74f29f12014-08-28 15:54:10 -07001596 /* Work out if the problem is the password or the data */
1597 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1598 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001599
Paul Lawrence74f29f12014-08-28 15:54:10 -07001600 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1601 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1602 N, r, p, scrypted_intermediate_key,
1603 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001604
Paul Lawrence74f29f12014-08-28 15:54:10 -07001605 // Does the key match the crypto footer?
1606 if (rc == 0 && memcmp(scrypted_intermediate_key,
1607 crypt_ftr->scrypted_intermediate_key,
1608 sizeof(scrypted_intermediate_key)) == 0) {
1609 SLOGI("Password matches");
1610 rc = 0;
1611 } else {
1612 /* Try mounting the file system anyway, just in case the problem's with
1613 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001614 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1615 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001616 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001617 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001618 SLOGE("Error temp mounting decrypted block device\n");
1619 delete_crypto_blk_dev(label);
1620
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001621 rc = ++crypt_ftr->failed_decrypt_count;
1622 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001623 } else {
1624 /* Success! */
1625 SLOGI("Password did not match but decrypted drive mounted - continue");
1626 umount(tmp_mount_point);
1627 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001628 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001629 }
1630
1631 if (rc == 0) {
1632 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001633 if (orig_failed_decrypt_count != 0) {
1634 put_crypt_ftr_and_key(crypt_ftr);
1635 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001636
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001637 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001638 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001639 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001640
1641 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001642 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001643 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001644 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001645 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001646 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001647 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001648
Paul Lawrence74f29f12014-08-28 15:54:10 -07001649 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001650 use_keymaster = keymaster_check_compatibility();
1651 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001652 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001653 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1654 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1655 upgrade = 1;
1656 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001657 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001658 upgrade = 1;
1659 }
1660
1661 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001662 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1663 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001664 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001665 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001666 }
1667 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001668
1669 // Do not fail even if upgrade failed - machine is bootable
1670 // Note that if this code is ever hit, there is a *serious* problem
1671 // since KDFs should never fail. You *must* fix the kdf before
1672 // proceeding!
1673 if (rc) {
1674 SLOGW("Upgrade failed with error %d,"
1675 " but continuing with previous state",
1676 rc);
1677 rc = 0;
1678 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001679 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001680 }
1681
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001682 errout:
1683 if (intermediate_key) {
1684 memset(intermediate_key, 0, intermediate_key_size);
1685 free(intermediate_key);
1686 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001687 return rc;
1688}
1689
Ken Sumrall29d8da82011-05-18 17:20:07 -07001690/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001691 * Called by vold when it's asked to mount an encrypted external
1692 * storage volume. The incoming partition has no crypto header/footer,
1693 * as any metadata is been stored in a separate, small partition.
1694 *
1695 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001696 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001697int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1698 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001699 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001700 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001701 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001702 return -1;
1703 }
1704
1705 unsigned long nr_sec = 0;
1706 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001707 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001708
Ken Sumrall29d8da82011-05-18 17:20:07 -07001709 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001710 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001711 return -1;
1712 }
1713
Jeff Sharkey9c484982015-03-31 10:35:33 -07001714 struct crypt_mnt_ftr ext_crypt_ftr;
1715 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1716 ext_crypt_ftr.fs_size = nr_sec;
1717 ext_crypt_ftr.keysize = keysize;
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001718 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
1719 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001720
Jeff Sharkey9c484982015-03-31 10:35:33 -07001721 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1722 out_crypto_blkdev, label);
1723}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001724
Jeff Sharkey9c484982015-03-31 10:35:33 -07001725/*
1726 * Called by vold when it's asked to unmount an encrypted external
1727 * storage volume.
1728 */
1729int cryptfs_revert_ext_volume(const char* label) {
1730 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001731}
1732
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001733int cryptfs_crypto_complete(void)
1734{
1735 return do_crypto_complete("/data");
1736}
1737
Paul Lawrencef4faa572014-01-29 13:31:03 -08001738int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1739{
1740 char encrypted_state[PROPERTY_VALUE_MAX];
1741 property_get("ro.crypto.state", encrypted_state, "");
1742 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1743 SLOGE("encrypted fs already validated or not running with encryption,"
1744 " aborting");
1745 return -1;
1746 }
1747
1748 if (get_crypt_ftr_and_key(crypt_ftr)) {
1749 SLOGE("Error getting crypt footer and key");
1750 return -1;
1751 }
1752
1753 return 0;
1754}
1755
Wei Wang4375f1b2017-02-24 17:43:01 -08001756int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001757{
Paul Lawrence05335c32015-03-05 09:46:23 -08001758 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001759 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001760 SLOGE("cryptfs_check_passwd not valid for file encryption");
1761 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001762 }
1763
Paul Lawrencef4faa572014-01-29 13:31:03 -08001764 struct crypt_mnt_ftr crypt_ftr;
1765 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001766
Paul Lawrencef4faa572014-01-29 13:31:03 -08001767 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001768 if (rc) {
1769 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001770 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001771 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001772
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001773 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001774 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1775 if (rc) {
1776 SLOGE("Password did not match");
1777 return rc;
1778 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001779
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001780 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1781 // Here we have a default actual password but a real password
1782 // we must test against the scrypted value
1783 // First, we must delete the crypto block device that
1784 // test_mount_encrypted_fs leaves behind as a side effect
1785 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1786 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1787 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1788 if (rc) {
1789 SLOGE("Default password did not match on reboot encryption");
1790 return rc;
1791 }
1792
1793 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1794 put_crypt_ftr_and_key(&crypt_ftr);
1795 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1796 if (rc) {
1797 SLOGE("Could not change password on reboot encryption");
1798 return rc;
1799 }
1800 }
1801
1802 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001803 cryptfs_clear_password();
1804 password = strdup(passwd);
1805 struct timespec now;
1806 clock_gettime(CLOCK_BOOTTIME, &now);
1807 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001808 }
1809
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001810 return rc;
1811}
1812
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001813int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001814{
1815 struct crypt_mnt_ftr crypt_ftr;
1816 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001817 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001818 char encrypted_state[PROPERTY_VALUE_MAX];
1819 int rc;
1820
1821 property_get("ro.crypto.state", encrypted_state, "");
1822 if (strcmp(encrypted_state, "encrypted") ) {
1823 SLOGE("device not encrypted, aborting");
1824 return -2;
1825 }
1826
1827 if (!master_key_saved) {
1828 SLOGE("encrypted fs not yet mounted, aborting");
1829 return -1;
1830 }
1831
1832 if (!saved_mount_point) {
1833 SLOGE("encrypted fs failed to save mount point, aborting");
1834 return -1;
1835 }
1836
Ken Sumrall160b4d62013-04-22 12:15:39 -07001837 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001838 SLOGE("Error getting crypt footer and key\n");
1839 return -1;
1840 }
1841
1842 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1843 /* If the device has no password, then just say the password is valid */
1844 rc = 0;
1845 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001846 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001847 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1848 /* They match, the password is correct */
1849 rc = 0;
1850 } else {
1851 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1852 sleep(1);
1853 rc = 1;
1854 }
1855 }
1856
1857 return rc;
1858}
1859
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001860/* Initialize a crypt_mnt_ftr structure. The keysize is
1861 * defaulted to 16 bytes, and the filesystem size to 0.
1862 * Presumably, at a minimum, the caller will update the
1863 * filesystem size and crypto_type_name after calling this function.
1864 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001865static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001866{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001867 off64_t off;
1868
1869 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001870 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001871 ftr->major_version = CURRENT_MAJOR_VERSION;
1872 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001873 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001874 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001875
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001876 switch (keymaster_check_compatibility()) {
1877 case 1:
1878 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1879 break;
1880
1881 case 0:
1882 ftr->kdf_type = KDF_SCRYPT;
1883 break;
1884
1885 default:
1886 SLOGE("keymaster_check_compatibility failed");
1887 return -1;
1888 }
1889
Kenny Rootc4c70f12013-06-14 12:11:38 -07001890 get_device_scrypt_params(ftr);
1891
Ken Sumrall160b4d62013-04-22 12:15:39 -07001892 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1893 if (get_crypt_ftr_info(NULL, &off) == 0) {
1894 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1895 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1896 ftr->persist_data_size;
1897 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001898
1899 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001900}
1901
Ken Sumrall29d8da82011-05-18 17:20:07 -07001902static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903{
Ken Sumralle550f782013-08-20 13:48:23 -07001904 const char *args[10];
1905 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1906 int num_args;
1907 int status;
1908 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001909 int rc = -1;
1910
Ken Sumrall29d8da82011-05-18 17:20:07 -07001911 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001912 args[0] = "/system/bin/mke2fs";
1913 args[1] = "-M";
1914 args[2] = "/data";
1915 args[3] = "-b";
1916 args[4] = "4096";
1917 args[5] = "-t";
1918 args[6] = "ext4";
1919 args[7] = crypto_blkdev;
1920 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1921 args[8] = size_str;
1922 num_args = 9;
Ken Sumralle550f782013-08-20 13:48:23 -07001923 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1924 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001925 } else if (type == F2FS_FS) {
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001926 args[0] = "/system/bin/make_f2fs";
JP Abgrall62c7af32014-06-16 13:01:23 -07001927 args[1] = "-t";
1928 args[2] = "-d1";
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001929 args[3] = "-f";
1930 args[4] = "-O encrypt";
1931 args[5] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001932 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001933 args[6] = size_str;
1934 num_args = 7;
1935 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s\n",
1936 args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001937 } else {
1938 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1939 return -1;
1940 }
1941
Ken Sumralle550f782013-08-20 13:48:23 -07001942 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1943
1944 if (tmp != 0) {
1945 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001946 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001947 if (WIFEXITED(status)) {
1948 if (WEXITSTATUS(status)) {
1949 SLOGE("Error creating filesystem on %s, exit status %d ",
1950 crypto_blkdev, WEXITSTATUS(status));
1951 } else {
1952 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1953 rc = 0;
1954 }
1955 } else {
1956 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1957 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001958 }
1959
1960 return rc;
1961}
1962
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001963#define CRYPTO_ENABLE_WIPE 1
1964#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001965
1966#define FRAMEWORK_BOOT_WAIT 60
1967
Paul Lawrence87999172014-02-20 12:21:31 -08001968static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1969{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001970 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001971 if (fd == -1) {
1972 SLOGE("Error opening file %s", filename);
1973 return -1;
1974 }
1975
1976 char block[CRYPT_INPLACE_BUFSIZE];
1977 memset(block, 0, sizeof(block));
1978 if (unix_read(fd, block, sizeof(block)) < 0) {
1979 SLOGE("Error reading file %s", filename);
1980 close(fd);
1981 return -1;
1982 }
1983
1984 close(fd);
1985
1986 SHA256_CTX c;
1987 SHA256_Init(&c);
1988 SHA256_Update(&c, block, sizeof(block));
1989 SHA256_Final(buf, &c);
1990
1991 return 0;
1992}
1993
JP Abgrall62c7af32014-06-16 13:01:23 -07001994static int get_fs_type(struct fstab_rec *rec)
1995{
1996 if (!strcmp(rec->fs_type, "ext4")) {
1997 return EXT4_FS;
1998 } else if (!strcmp(rec->fs_type, "f2fs")) {
1999 return F2FS_FS;
2000 } else {
2001 return -1;
2002 }
2003}
2004
Paul Lawrence87999172014-02-20 12:21:31 -08002005static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2006 char *crypto_blkdev, char *real_blkdev,
2007 int previously_encrypted_upto)
2008{
2009 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002010 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002011
Paul Lawrence87999172014-02-20 12:21:31 -08002012 /* The size of the userdata partition, and add in the vold volumes below */
2013 tot_encryption_size = crypt_ftr->fs_size;
2014
2015 if (how == CRYPTO_ENABLE_WIPE) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002016 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
JP Abgrall62c7af32014-06-16 13:01:23 -07002017 int fs_type = get_fs_type(rec);
2018 if (fs_type < 0) {
2019 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2020 return -1;
2021 }
2022 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002023 } else if (how == CRYPTO_ENABLE_INPLACE) {
2024 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2025 crypt_ftr->fs_size, &cur_encryption_done,
2026 tot_encryption_size,
2027 previously_encrypted_upto);
2028
JP Abgrall7fc1de82014-10-10 18:43:41 -07002029 if (rc == ENABLE_INPLACE_ERR_DEV) {
2030 /* Hack for b/17898962 */
2031 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
Josh Gaofec44372017-08-28 13:22:55 -07002032 cryptfs_reboot(RebootType::reboot);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002033 }
2034
Paul Lawrence73d7a022014-06-09 14:10:09 -07002035 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002036 crypt_ftr->encrypted_upto = cur_encryption_done;
2037 }
2038
Paul Lawrence73d7a022014-06-09 14:10:09 -07002039 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002040 /* The inplace routine never actually sets the progress to 100% due
2041 * to the round down nature of integer division, so set it here */
2042 property_set("vold.encrypt_progress", "100");
2043 }
2044 } else {
2045 /* Shouldn't happen */
2046 SLOGE("cryptfs_enable: internal error, unknown option\n");
2047 rc = -1;
2048 }
2049
2050 return rc;
2051}
2052
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002053int cryptfs_enable_internal(const char *howarg, int crypt_type, const char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002054 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002055{
2056 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002057 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002058 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002059 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002060 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002061 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002062 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002063 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002064 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002065 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002066 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002067 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002068 bool onlyCreateHeader = false;
2069 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002070
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002071 if (!strcmp(howarg, "wipe")) {
2072 how = CRYPTO_ENABLE_WIPE;
2073 } else if (! strcmp(howarg, "inplace")) {
2074 how = CRYPTO_ENABLE_INPLACE;
2075 } else {
2076 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002077 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002078 }
2079
Paul Lawrence87999172014-02-20 12:21:31 -08002080 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002081 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2082 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2083 /* An encryption was underway and was interrupted */
2084 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2085 crypt_ftr.encrypted_upto = 0;
2086 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002087
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002088 /* At this point, we are in an inconsistent state. Until we successfully
2089 complete encryption, a reboot will leave us broken. So mark the
2090 encryption failed in case that happens.
2091 On successfully completing encryption, remove this flag */
2092 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002093
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002094 put_crypt_ftr_and_key(&crypt_ftr);
2095 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2096 if (!check_ftr_sha(&crypt_ftr)) {
2097 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2098 put_crypt_ftr_and_key(&crypt_ftr);
2099 goto error_unencrypted;
2100 }
2101
2102 /* Doing a reboot-encryption*/
2103 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2104 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2105 rebootEncryption = true;
2106 }
Paul Lawrence87999172014-02-20 12:21:31 -08002107 }
2108
2109 property_get("ro.crypto.state", encrypted_state, "");
2110 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2111 SLOGE("Device is already running encrypted, aborting");
2112 goto error_unencrypted;
2113 }
2114
2115 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002116 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2117 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002118
Ken Sumrall3ed82362011-01-28 23:31:16 -08002119 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002120 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002121 if (fd == -1) {
2122 SLOGE("Cannot open block device %s\n", real_blkdev);
2123 goto error_unencrypted;
2124 }
2125 unsigned long nr_sec;
2126 get_blkdev_size(fd, &nr_sec);
2127 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002128 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2129 goto error_unencrypted;
2130 }
2131 close(fd);
2132
2133 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002134 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002135 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002136 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002137 if (fs_size_sec == 0)
2138 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2139
Paul Lawrence87999172014-02-20 12:21:31 -08002140 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002141
2142 if (fs_size_sec > max_fs_size_sec) {
2143 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2144 goto error_unencrypted;
2145 }
2146 }
2147
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002148 /* Get a wakelock as this may take a while, and we don't want the
2149 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2150 * wants to keep the screen on, it can grab a full wakelock.
2151 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002152 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002153 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2154
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002155 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002156 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002157 */
2158 property_set("vold.decrypt", "trigger_shutdown_framework");
2159 SLOGD("Just asked init to shut down class main\n");
2160
Jeff Sharkey9c484982015-03-31 10:35:33 -07002161 /* Ask vold to unmount all devices that it manages */
2162 if (vold_unmountAll()) {
2163 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002164 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002165
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002166 /* no_ui means we are being called from init, not settings.
2167 Now we always reboot from settings, so !no_ui means reboot
2168 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002169 if (!no_ui) {
2170 /* Try fallback, which is to reboot and try there */
2171 onlyCreateHeader = true;
2172 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2173 if (breadcrumb == 0) {
2174 SLOGE("Failed to create breadcrumb file");
2175 goto error_shutting_down;
2176 }
2177 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002178 }
2179
2180 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002181 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002182 /* Now that /data is unmounted, we need to mount a tmpfs
2183 * /data, set a property saying we're doing inplace encryption,
2184 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002185 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002186 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002187 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002188 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002189 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002190 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002191
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002192 /* restart the framework. */
2193 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002194 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002195
Ken Sumrall92736ef2012-10-17 20:57:14 -07002196 /* Ugh, shutting down the framework is not synchronous, so until it
2197 * can be fixed, this horrible hack will wait a moment for it all to
2198 * shut down before proceeding. Without it, some devices cannot
2199 * restart the graphics services.
2200 */
2201 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002202 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002203
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002204 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002205 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002206 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002207 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2208 goto error_shutting_down;
2209 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002210
Paul Lawrence87999172014-02-20 12:21:31 -08002211 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2212 crypt_ftr.fs_size = nr_sec
2213 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2214 } else {
2215 crypt_ftr.fs_size = nr_sec;
2216 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002217 /* At this point, we are in an inconsistent state. Until we successfully
2218 complete encryption, a reboot will leave us broken. So mark the
2219 encryption failed in case that happens.
2220 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002221 if (onlyCreateHeader) {
2222 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2223 } else {
2224 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2225 }
Paul Lawrence87999172014-02-20 12:21:31 -08002226 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002227 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002228
Paul Lawrence87999172014-02-20 12:21:31 -08002229 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002230 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2231 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002232 SLOGE("Cannot create encrypted master key\n");
2233 goto error_shutting_down;
2234 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002235
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002236 /* Replace scrypted intermediate key if we are preparing for a reboot */
2237 if (onlyCreateHeader) {
2238 unsigned char fake_master_key[KEY_LEN_BYTES];
2239 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2240 memset(fake_master_key, 0, sizeof(fake_master_key));
2241 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2242 encrypted_fake_master_key, &crypt_ftr);
2243 }
2244
Paul Lawrence87999172014-02-20 12:21:31 -08002245 /* Write the key to the end of the partition */
2246 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002247
Paul Lawrence87999172014-02-20 12:21:31 -08002248 /* If any persistent data has been remembered, save it.
2249 * If none, create a valid empty table and save that.
2250 */
2251 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002252 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002253 if (pdata) {
2254 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2255 persist_data = pdata;
2256 }
2257 }
2258 if (persist_data) {
2259 save_persistent_data();
2260 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002261 }
2262
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002263 if (onlyCreateHeader) {
2264 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002265 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002266 }
2267
2268 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002269 /* startup service classes main and late_start */
2270 property_set("vold.decrypt", "trigger_restart_min_framework");
2271 SLOGD("Just triggered restart_min_framework\n");
2272
2273 /* OK, the framework is restarted and will soon be showing a
2274 * progress bar. Time to setup an encrypted mapping, and
2275 * either write a new filesystem, or encrypt in place updating
2276 * the progress bar as we work.
2277 */
2278 }
2279
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002280 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002281 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002282 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002283
Paul Lawrence87999172014-02-20 12:21:31 -08002284 /* If we are continuing, check checksums match */
2285 rc = 0;
2286 if (previously_encrypted_upto) {
2287 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2288 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002289
Paul Lawrence87999172014-02-20 12:21:31 -08002290 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2291 sizeof(hash_first_block)) != 0) {
2292 SLOGE("Checksums do not match - trigger wipe");
2293 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002294 }
2295 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002296
Paul Lawrence87999172014-02-20 12:21:31 -08002297 if (!rc) {
2298 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2299 crypto_blkdev, real_blkdev,
2300 previously_encrypted_upto);
2301 }
2302
2303 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002304 if (!rc && how == CRYPTO_ENABLE_INPLACE
2305 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002306 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2307 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002308 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002309 SLOGE("Error calculating checksum for continuing encryption");
2310 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002311 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002312 }
2313
2314 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002315 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002316
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002317 if (! rc) {
2318 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002319 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002320
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002321 if (how == CRYPTO_ENABLE_INPLACE
2322 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002323 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2324 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002325 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002326 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002327
Paul Lawrence6bfed202014-07-28 12:47:22 -07002328 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002329
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002330 if (how == CRYPTO_ENABLE_WIPE
2331 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002332 char value[PROPERTY_VALUE_MAX];
2333 property_get("ro.crypto.state", value, "");
2334 if (!strcmp(value, "")) {
2335 /* default encryption - continue first boot sequence */
2336 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08002337 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002338 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002339 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2340 // Bring up cryptkeeper that will check the password and set it
2341 property_set("vold.decrypt", "trigger_shutdown_framework");
2342 sleep(2);
2343 property_set("vold.encrypt_progress", "");
2344 cryptfs_trigger_restart_min_framework();
2345 } else {
2346 cryptfs_check_passwd(DEFAULT_PASSWORD);
2347 cryptfs_restart_internal(1);
2348 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002349 return 0;
2350 } else {
2351 sleep(2); /* Give the UI a chance to show 100% progress */
Josh Gaofec44372017-08-28 13:22:55 -07002352 cryptfs_reboot(RebootType::reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002353 }
Paul Lawrence87999172014-02-20 12:21:31 -08002354 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002355 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002356 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002357 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002358 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002359 char value[PROPERTY_VALUE_MAX];
2360
Ken Sumrall319369a2012-06-27 16:30:18 -07002361 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002362 if (!strcmp(value, "1")) {
2363 /* wipe data if encryption failed */
2364 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002365 std::string err;
2366 const std::vector<std::string> options = {
2367 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2368 };
2369 if (!write_bootloader_message(options, &err)) {
2370 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002371 }
Josh Gaofec44372017-08-28 13:22:55 -07002372 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002373 } else {
2374 /* set property to trigger dialog */
2375 property_set("vold.encrypt_progress", "error_partially_encrypted");
2376 release_wake_lock(lockid);
2377 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002378 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002379 }
2380
Ken Sumrall3ed82362011-01-28 23:31:16 -08002381 /* hrm, the encrypt step claims success, but the reboot failed.
2382 * This should not happen.
2383 * Set the property and return. Hope the framework can deal with it.
2384 */
2385 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002386 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002387 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002388
2389error_unencrypted:
2390 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002391 if (lockid[0]) {
2392 release_wake_lock(lockid);
2393 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002394 return -1;
2395
2396error_shutting_down:
2397 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2398 * but the framework is stopped and not restarted to show the error, so it's up to
2399 * vold to restart the system.
2400 */
2401 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002402 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002403
2404 /* shouldn't get here */
2405 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002406 if (lockid[0]) {
2407 release_wake_lock(lockid);
2408 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002409 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002410}
2411
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002412int cryptfs_enable(const char *howarg, int type, const char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002413{
Paul Lawrence569649f2015-09-09 12:13:00 -07002414 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002415}
2416
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002417int cryptfs_enable_default(const char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002418{
2419 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07002420 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002421}
2422
2423int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002424{
Paul Crowley38132a12016-02-09 09:50:32 +00002425 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002426 SLOGE("cryptfs_changepw not valid for file encryption");
2427 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002428 }
2429
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002430 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002431 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002432
2433 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002434 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002435 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002436 return -1;
2437 }
2438
Paul Lawrencef4faa572014-01-29 13:31:03 -08002439 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2440 SLOGE("Invalid crypt_type %d", crypt_type);
2441 return -1;
2442 }
2443
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002444 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002445 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002446 SLOGE("Error getting crypt footer and key");
2447 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002448 }
2449
Paul Lawrencef4faa572014-01-29 13:31:03 -08002450 crypt_ftr.crypt_type = crypt_type;
2451
JP Abgrall933216c2015-02-11 13:44:32 -08002452 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002453 : newpw,
2454 crypt_ftr.salt,
2455 saved_master_key,
2456 crypt_ftr.master_key,
2457 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002458 if (rc) {
2459 SLOGE("Encrypt master key failed: %d", rc);
2460 return -1;
2461 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002462 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002463 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002464
2465 return 0;
2466}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002467
Rubin Xu85c01f92014-10-13 12:49:54 +01002468static unsigned int persist_get_max_entries(int encrypted) {
2469 struct crypt_mnt_ftr crypt_ftr;
2470 unsigned int dsize;
2471 unsigned int max_persistent_entries;
2472
2473 /* If encrypted, use the values from the crypt_ftr, otherwise
2474 * use the values for the current spec.
2475 */
2476 if (encrypted) {
2477 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2478 return -1;
2479 }
2480 dsize = crypt_ftr.persist_data_size;
2481 } else {
2482 dsize = CRYPT_PERSIST_DATA_SIZE;
2483 }
2484
2485 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2486 sizeof(struct crypt_persist_entry);
2487
2488 return max_persistent_entries;
2489}
2490
2491static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002492{
2493 unsigned int i;
2494
2495 if (persist_data == NULL) {
2496 return -1;
2497 }
2498 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2499 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2500 /* We found it! */
2501 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2502 return 0;
2503 }
2504 }
2505
2506 return -1;
2507}
2508
Rubin Xu85c01f92014-10-13 12:49:54 +01002509static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002510{
2511 unsigned int i;
2512 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002513 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002514
2515 if (persist_data == NULL) {
2516 return -1;
2517 }
2518
Rubin Xu85c01f92014-10-13 12:49:54 +01002519 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002520
2521 num = persist_data->persist_valid_entries;
2522
2523 for (i = 0; i < num; i++) {
2524 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2525 /* We found an existing entry, update it! */
2526 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2527 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2528 return 0;
2529 }
2530 }
2531
2532 /* We didn't find it, add it to the end, if there is room */
2533 if (persist_data->persist_valid_entries < max_persistent_entries) {
2534 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2535 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2536 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2537 persist_data->persist_valid_entries++;
2538 return 0;
2539 }
2540
2541 return -1;
2542}
2543
Rubin Xu85c01f92014-10-13 12:49:54 +01002544/**
2545 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2546 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2547 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002548int match_multi_entry(const char *key, const char *field, unsigned index) {
2549 std::string key_ = key;
2550 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002551
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002552 std::string parsed_field;
2553 unsigned parsed_index;
2554
2555 std::string::size_type split = key_.find_last_of('_');
2556 if (split == std::string::npos) {
2557 parsed_field = key_;
2558 parsed_index = 0;
2559 } else {
2560 parsed_field = key_.substr(0, split);
2561 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002562 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002563
2564 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002565}
2566
2567/*
2568 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2569 * remaining entries starting from index will be deleted.
2570 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2571 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2572 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2573 *
2574 */
2575static int persist_del_keys(const char *fieldname, unsigned index)
2576{
2577 unsigned int i;
2578 unsigned int j;
2579 unsigned int num;
2580
2581 if (persist_data == NULL) {
2582 return PERSIST_DEL_KEY_ERROR_OTHER;
2583 }
2584
2585 num = persist_data->persist_valid_entries;
2586
2587 j = 0; // points to the end of non-deleted entries.
2588 // Filter out to-be-deleted entries in place.
2589 for (i = 0; i < num; i++) {
2590 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2591 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2592 j++;
2593 }
2594 }
2595
2596 if (j < num) {
2597 persist_data->persist_valid_entries = j;
2598 // Zeroise the remaining entries
2599 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2600 return PERSIST_DEL_KEY_OK;
2601 } else {
2602 // Did not find an entry matching the given fieldname
2603 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2604 }
2605}
2606
2607static int persist_count_keys(const char *fieldname)
2608{
2609 unsigned int i;
2610 unsigned int count;
2611
2612 if (persist_data == NULL) {
2613 return -1;
2614 }
2615
2616 count = 0;
2617 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2618 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2619 count++;
2620 }
2621 }
2622
2623 return count;
2624}
2625
Ken Sumrall160b4d62013-04-22 12:15:39 -07002626/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002627int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002628{
Paul Crowley38132a12016-02-09 09:50:32 +00002629 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002630 SLOGE("Cannot get field when file encrypted");
2631 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002632 }
2633
Ken Sumrall160b4d62013-04-22 12:15:39 -07002634 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002635 /* CRYPTO_GETFIELD_OK is success,
2636 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2637 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2638 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002639 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002640 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2641 int i;
2642 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002643
2644 if (persist_data == NULL) {
2645 load_persistent_data();
2646 if (persist_data == NULL) {
2647 SLOGE("Getfield error, cannot load persistent data");
2648 goto out;
2649 }
2650 }
2651
Rubin Xu85c01f92014-10-13 12:49:54 +01002652 // Read value from persistent entries. If the original value is split into multiple entries,
2653 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002654 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002655 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2656 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2657 // value too small
2658 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2659 goto out;
2660 }
2661 rc = CRYPTO_GETFIELD_OK;
2662
2663 for (i = 1; /* break explicitly */; i++) {
2664 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2665 (int) sizeof(temp_field)) {
2666 // If the fieldname is very long, we stop as soon as it begins to overflow the
2667 // maximum field length. At this point we have in fact fully read out the original
2668 // value because cryptfs_setfield would not allow fields with longer names to be
2669 // written in the first place.
2670 break;
2671 }
2672 if (!persist_get_key(temp_field, temp_value)) {
2673 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2674 // value too small.
2675 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2676 goto out;
2677 }
2678 } else {
2679 // Exhaust all entries.
2680 break;
2681 }
2682 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002683 } else {
2684 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002685 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002686 }
2687
2688out:
2689 return rc;
2690}
2691
2692/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002693int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002694{
Paul Crowley38132a12016-02-09 09:50:32 +00002695 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002696 SLOGE("Cannot set field when file encrypted");
2697 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002698 }
2699
Ken Sumrall160b4d62013-04-22 12:15:39 -07002700 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002701 /* 0 is success, negative values are error */
2702 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002703 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002704 unsigned int field_id;
2705 char temp_field[PROPERTY_KEY_MAX];
2706 unsigned int num_entries;
2707 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002708
2709 if (persist_data == NULL) {
2710 load_persistent_data();
2711 if (persist_data == NULL) {
2712 SLOGE("Setfield error, cannot load persistent data");
2713 goto out;
2714 }
2715 }
2716
2717 property_get("ro.crypto.state", encrypted_state, "");
2718 if (!strcmp(encrypted_state, "encrypted") ) {
2719 encrypted = 1;
2720 }
2721
Rubin Xu85c01f92014-10-13 12:49:54 +01002722 // Compute the number of entries required to store value, each entry can store up to
2723 // (PROPERTY_VALUE_MAX - 1) chars
2724 if (strlen(value) == 0) {
2725 // Empty value also needs one entry to store.
2726 num_entries = 1;
2727 } else {
2728 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2729 }
2730
2731 max_keylen = strlen(fieldname);
2732 if (num_entries > 1) {
2733 // Need an extra "_%d" suffix.
2734 max_keylen += 1 + log10(num_entries);
2735 }
2736 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2737 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002738 goto out;
2739 }
2740
Rubin Xu85c01f92014-10-13 12:49:54 +01002741 // Make sure we have enough space to write the new value
2742 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2743 persist_get_max_entries(encrypted)) {
2744 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2745 goto out;
2746 }
2747
2748 // Now that we know persist_data has enough space for value, let's delete the old field first
2749 // to make up space.
2750 persist_del_keys(fieldname, 0);
2751
2752 if (persist_set_key(fieldname, value, encrypted)) {
2753 // fail to set key, should not happen as we have already checked the available space
2754 SLOGE("persist_set_key() error during setfield()");
2755 goto out;
2756 }
2757
2758 for (field_id = 1; field_id < num_entries; field_id++) {
2759 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
2760
2761 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2762 // fail to set key, should not happen as we have already checked the available space.
2763 SLOGE("persist_set_key() error during setfield()");
2764 goto out;
2765 }
2766 }
2767
Ken Sumrall160b4d62013-04-22 12:15:39 -07002768 /* If we are running encrypted, save the persistent data now */
2769 if (encrypted) {
2770 if (save_persistent_data()) {
2771 SLOGE("Setfield error, cannot save persistent data");
2772 goto out;
2773 }
2774 }
2775
Rubin Xu85c01f92014-10-13 12:49:54 +01002776 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002777
2778out:
2779 return rc;
2780}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002781
2782/* Checks userdata. Attempt to mount the volume if default-
2783 * encrypted.
2784 * On success trigger next init phase and return 0.
2785 * Currently do not handle failure - see TODO below.
2786 */
2787int cryptfs_mount_default_encrypted(void)
2788{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002789 int crypt_type = cryptfs_get_password_type();
2790 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2791 SLOGE("Bad crypt type - error");
2792 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2793 SLOGD("Password is not default - "
2794 "starting min framework to prompt");
2795 property_set("vold.decrypt", "trigger_restart_min_framework");
2796 return 0;
2797 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2798 SLOGD("Password is default - restarting filesystem");
2799 cryptfs_restart_internal(0);
2800 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002801 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002802 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002803 }
2804
Paul Lawrence6bfed202014-07-28 12:47:22 -07002805 /** Corrupt. Allow us to boot into framework, which will detect bad
2806 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002807 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002808 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002809 return 0;
2810}
2811
2812/* Returns type of the password, default, pattern, pin or password.
2813 */
2814int cryptfs_get_password_type(void)
2815{
Paul Crowley38132a12016-02-09 09:50:32 +00002816 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002817 SLOGE("cryptfs_get_password_type not valid for file encryption");
2818 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002819 }
2820
Paul Lawrencef4faa572014-01-29 13:31:03 -08002821 struct crypt_mnt_ftr crypt_ftr;
2822
2823 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2824 SLOGE("Error getting crypt footer and key\n");
2825 return -1;
2826 }
2827
Paul Lawrence6bfed202014-07-28 12:47:22 -07002828 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2829 return -1;
2830 }
2831
Paul Lawrencef4faa572014-01-29 13:31:03 -08002832 return crypt_ftr.crypt_type;
2833}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002834
Paul Lawrence05335c32015-03-05 09:46:23 -08002835const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002836{
Paul Crowley38132a12016-02-09 09:50:32 +00002837 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002838 SLOGE("cryptfs_get_password not valid for file encryption");
2839 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002840 }
2841
Paul Lawrence399317e2014-03-10 13:20:50 -07002842 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002843 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002844 if (now.tv_sec < password_expiry_time) {
2845 return password;
2846 } else {
2847 cryptfs_clear_password();
2848 return 0;
2849 }
2850}
2851
2852void cryptfs_clear_password()
2853{
2854 if (password) {
2855 size_t len = strlen(password);
2856 memset(password, 0, len);
2857 free(password);
2858 password = 0;
2859 password_expiry_time = 0;
2860 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002861}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002862
Paul Lawrence0c247462015-10-29 10:30:57 -07002863int cryptfs_isConvertibleToFBE()
2864{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002865 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002866 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2867}
2868
Paul Lawrence731a7a22015-04-28 22:14:15 +00002869int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
2870{
2871 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
2872 SLOGE("Failed to initialize crypt_ftr");
2873 return -1;
2874 }
2875
2876 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
2877 crypt_ftr->salt, crypt_ftr)) {
2878 SLOGE("Cannot create encrypted master key\n");
2879 return -1;
2880 }
2881
2882 //crypt_ftr->keysize = key_length / 8;
2883 return 0;
2884}
2885
2886int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
2887 unsigned char* master_key)
2888{
2889 int rc;
2890
Paul Lawrence731a7a22015-04-28 22:14:15 +00002891 unsigned char* intermediate_key = 0;
2892 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002893
2894 if (password == 0 || *password == 0) {
2895 password = DEFAULT_PASSWORD;
2896 }
2897
Paul Lawrence731a7a22015-04-28 22:14:15 +00002898 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
2899 &intermediate_key_size);
2900
Paul Lawrence300dae72016-03-11 11:02:52 -08002901 if (rc) {
2902 SLOGE("Can't calculate intermediate key");
2903 return rc;
2904 }
2905
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002906 int N = 1 << ftr->N_factor;
2907 int r = 1 << ftr->r_factor;
2908 int p = 1 << ftr->p_factor;
2909
2910 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
2911
2912 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
2913 ftr->salt, sizeof(ftr->salt), N, r, p,
2914 scrypted_intermediate_key,
2915 sizeof(scrypted_intermediate_key));
2916
2917 free(intermediate_key);
2918
2919 if (rc) {
Paul Lawrence300dae72016-03-11 11:02:52 -08002920 SLOGE("Can't scrypt intermediate key");
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002921 return rc;
2922 }
2923
2924 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
2925 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00002926}
2927
2928int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
2929 const unsigned char* master_key)
2930{
2931 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
2932 ftr);
2933}
Paul Lawrence6e410592016-05-24 14:20:38 -07002934
Eric Biggersb45caaf2017-02-02 14:52:12 -08002935void cryptfs_get_file_encryption_modes(const char **contents_mode_ret,
2936 const char **filenames_mode_ret)
Paul Lawrence6e410592016-05-24 14:20:38 -07002937{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002938 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Eric Biggersb45caaf2017-02-02 14:52:12 -08002939 fs_mgr_get_file_encryption_modes(rec, contents_mode_ret, filenames_mode_ret);
Paul Lawrence6e410592016-05-24 14:20:38 -07002940}