blob: 40b1e0742b8bd1335309842648aa3e3455b3a04e [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070041#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080046#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080047#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080048#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080049#define LOG_TAG "Cryptfs"
50#include "cutils/log.h"
51#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070052#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080053#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070054#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000055#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070056#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070057#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000058#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000059#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080060#include "CheckBattery.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070061#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080062#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000063#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080064#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070065#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080066extern "C" {
67#include <crypto_scrypt.h>
68}
Mark Salyzyn3e971272014-01-21 13:27:04 -080069
Mark Salyzyn5eecc442014-02-12 14:16:14 -080070#define UNUSED __attribute__((unused))
71
Ken Sumrall8f869aa2010-12-03 03:47:09 -080072#define DM_CRYPT_BUF_SIZE 4096
73
Jason parks70a4b3f2011-01-28 10:10:47 -060074#define HASH_COUNT 2000
75#define KEY_LEN_BYTES 16
76#define IV_LEN_BYTES 16
77
Ken Sumrall29d8da82011-05-18 17:20:07 -070078#define KEY_IN_FOOTER "footer"
79
Paul Lawrence3bd36d52015-06-09 13:37:44 -070080#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080081
Paul Lawrence3d99eba2015-11-20 07:07:19 -080082#define CRYPTO_BLOCK_DEVICE "userdata"
83
84#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
85
Ken Sumrall29d8da82011-05-18 17:20:07 -070086#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070087#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070088
Ken Sumralle919efe2012-09-29 17:07:41 -070089#define TABLE_LOAD_RETRIES 10
90
Shawn Willden47ba10d2014-09-03 17:07:06 -060091#define RSA_KEY_SIZE 2048
92#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
93#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060094#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070095
Paul Lawrence8e3f4512014-09-08 10:11:17 -070096#define RETRY_MOUNT_ATTEMPTS 10
97#define RETRY_MOUNT_DELAY_SECONDS 1
98
Jason parks70a4b3f2011-01-28 10:10:47 -060099static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700100static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600101static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700102static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800103
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700104/* Should we use keymaster? */
105static int keymaster_check_compatibility()
106{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000107 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700108}
109
110/* Create a new keymaster key and store it in this footer */
111static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
112{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800113 if (ftr->keymaster_blob_size) {
114 SLOGI("Already have key");
115 return 0;
116 }
117
Janis Danisevskis015ec302017-01-31 11:31:08 +0000118 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
119 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
120 &ftr->keymaster_blob_size);
121 if (rc) {
122 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
123 SLOGE("Keymaster key blob to large)");
124 ftr->keymaster_blob_size = 0;
125 }
126 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700127 return -1;
128 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000129 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700130}
131
Shawn Willdene17a9c42014-09-08 13:04:08 -0600132/* This signs the given object using the keymaster key. */
133static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600134 const unsigned char *object,
135 const size_t object_size,
136 unsigned char **signature,
137 size_t *signature_size)
138{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600139 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600140 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600141 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600142
Shawn Willdene17a9c42014-09-08 13:04:08 -0600143 // To sign a message with RSA, the message must satisfy two
144 // constraints:
145 //
146 // 1. The message, when interpreted as a big-endian numeric value, must
147 // be strictly less than the public modulus of the RSA key. Note
148 // that because the most significant bit of the public modulus is
149 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
150 // key), an n-bit message with most significant bit 0 always
151 // satisfies this requirement.
152 //
153 // 2. The message must have the same length in bits as the public
154 // modulus of the RSA key. This requirement isn't mathematically
155 // necessary, but is necessary to ensure consistency in
156 // implementations.
157 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600158 case KDF_SCRYPT_KEYMASTER:
159 // This ensures the most significant byte of the signed message
160 // is zero. We could have zero-padded to the left instead, but
161 // this approach is slightly more robust against changes in
162 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600163 // so) because we really should be using a proper deterministic
164 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800165 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600166 SLOGI("Signing safely-padded object");
167 break;
168 default:
169 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000170 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600171 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000172 return keymaster_sign_object_for_cryptfs_scrypt(ftr->keymaster_blob, ftr->keymaster_blob_size,
173 KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign, to_sign_size, signature, signature_size);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600174}
175
Paul Lawrence399317e2014-03-10 13:20:50 -0700176/* Store password when userdata is successfully decrypted and mounted.
177 * Cleared by cryptfs_clear_password
178 *
179 * To avoid a double prompt at boot, we need to store the CryptKeeper
180 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
181 * Since the entire framework is torn down and rebuilt after encryption,
182 * we have to use a daemon or similar to store the password. Since vold
183 * is secured against IPC except from system processes, it seems a reasonable
184 * place to store this.
185 *
186 * password should be cleared once it has been used.
187 *
188 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800189 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700190static char* password = 0;
191static int password_expiry_time = 0;
192static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800193
Josh Gaofec44372017-08-28 13:22:55 -0700194enum class RebootType {reboot, recovery, shutdown};
195static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700196{
Josh Gaofec44372017-08-28 13:22:55 -0700197 switch (rt) {
198 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800199 property_set(ANDROID_RB_PROPERTY, "reboot");
200 break;
201
Josh Gaofec44372017-08-28 13:22:55 -0700202 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800203 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
204 break;
205
Josh Gaofec44372017-08-28 13:22:55 -0700206 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800207 property_set(ANDROID_RB_PROPERTY, "shutdown");
208 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700209 }
Paul Lawrence87999172014-02-20 12:21:31 -0800210
Ken Sumralladfba362013-06-04 16:37:52 -0700211 sleep(20);
212
213 /* Shouldn't get here, reboot should happen before sleep times out */
214 return;
215}
216
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800217static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
218{
219 memset(io, 0, dataSize);
220 io->data_size = dataSize;
221 io->data_start = sizeof(struct dm_ioctl);
222 io->version[0] = 4;
223 io->version[1] = 0;
224 io->version[2] = 0;
225 io->flags = flags;
226 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100227 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800228 }
229}
230
Kenny Rootc4c70f12013-06-14 12:11:38 -0700231/**
232 * Gets the default device scrypt parameters for key derivation time tuning.
233 * The parameters should lead to about one second derivation time for the
234 * given device.
235 */
236static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700237 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000238 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700239
Paul Crowley63c18d32016-02-10 14:02:47 +0000240 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
241 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
242 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
243 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700244 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000245 ftr->N_factor = Nf;
246 ftr->r_factor = rf;
247 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700248}
249
Ken Sumrall3ed82362011-01-28 23:31:16 -0800250static unsigned int get_fs_size(char *dev)
251{
252 int fd, block_size;
253 struct ext4_super_block sb;
254 off64_t len;
255
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700256 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800257 SLOGE("Cannot open device to get filesystem size ");
258 return 0;
259 }
260
261 if (lseek64(fd, 1024, SEEK_SET) < 0) {
262 SLOGE("Cannot seek to superblock");
263 return 0;
264 }
265
266 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
267 SLOGE("Cannot read superblock");
268 return 0;
269 }
270
271 close(fd);
272
Daniel Rosenberge82df162014-08-15 22:19:23 +0000273 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
274 SLOGE("Not a valid ext4 superblock");
275 return 0;
276 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800277 block_size = 1024 << sb.s_log_block_size;
278 /* compute length in bytes */
279 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
280
281 /* return length in sectors */
282 return (unsigned int) (len / 512);
283}
284
Ken Sumrall160b4d62013-04-22 12:15:39 -0700285static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
286{
287 static int cached_data = 0;
288 static off64_t cached_off = 0;
289 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
290 int fd;
291 char key_loc[PROPERTY_VALUE_MAX];
292 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700293 int rc = -1;
294
295 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700296 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700297
298 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700299 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700300 SLOGE("Cannot open real block device %s\n", real_blkdev);
301 return -1;
302 }
303
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900304 unsigned long nr_sec = 0;
305 get_blkdev_size(fd, &nr_sec);
306 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700307 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
308 * encryption info footer and key, and plenty of bytes to spare for future
309 * growth.
310 */
311 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
312 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
313 cached_data = 1;
314 } else {
315 SLOGE("Cannot get size of block device %s\n", real_blkdev);
316 }
317 close(fd);
318 } else {
319 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
320 cached_off = 0;
321 cached_data = 1;
322 }
323 }
324
325 if (cached_data) {
326 if (metadata_fname) {
327 *metadata_fname = cached_metadata_fname;
328 }
329 if (off) {
330 *off = cached_off;
331 }
332 rc = 0;
333 }
334
335 return rc;
336}
337
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800338/* Set sha256 checksum in structure */
339static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
340{
341 SHA256_CTX c;
342 SHA256_Init(&c);
343 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
344 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
345 SHA256_Final(crypt_ftr->sha256, &c);
346}
347
Ken Sumralle8744072011-01-18 22:01:55 -0800348/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800349 * update the failed mount count but not change the key.
350 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700351static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800352{
353 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800354 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700355 /* starting_off is set to the SEEK_SET offset
356 * where the crypto structure starts
357 */
358 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800359 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700360 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700361 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800362
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800363 set_ftr_sha(crypt_ftr);
364
Ken Sumrall160b4d62013-04-22 12:15:39 -0700365 if (get_crypt_ftr_info(&fname, &starting_off)) {
366 SLOGE("Unable to get crypt_ftr_info\n");
367 return -1;
368 }
369 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700370 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700371 return -1;
372 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700373 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700374 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700375 return -1;
376 }
377
378 /* Seek to the start of the crypt footer */
379 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
380 SLOGE("Cannot seek to real block device footer\n");
381 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800382 }
383
384 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
385 SLOGE("Cannot write real block device footer\n");
386 goto errout;
387 }
388
Ken Sumrall3be890f2011-09-14 16:53:46 -0700389 fstat(fd, &statbuf);
390 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700391 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700392 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800393 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800394 goto errout;
395 }
396 }
397
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800398 /* Success! */
399 rc = 0;
400
401errout:
402 close(fd);
403 return rc;
404
405}
406
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800407static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
408{
409 struct crypt_mnt_ftr copy;
410 memcpy(&copy, crypt_ftr, sizeof(copy));
411 set_ftr_sha(&copy);
412 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
413}
414
Ken Sumrall160b4d62013-04-22 12:15:39 -0700415static inline int unix_read(int fd, void* buff, int len)
416{
417 return TEMP_FAILURE_RETRY(read(fd, buff, len));
418}
419
420static inline int unix_write(int fd, const void* buff, int len)
421{
422 return TEMP_FAILURE_RETRY(write(fd, buff, len));
423}
424
425static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
426{
427 memset(pdata, 0, len);
428 pdata->persist_magic = PERSIST_DATA_MAGIC;
429 pdata->persist_valid_entries = 0;
430}
431
432/* A routine to update the passed in crypt_ftr to the lastest version.
433 * fd is open read/write on the device that holds the crypto footer and persistent
434 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
435 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
436 */
437static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
438{
Kenny Root7434b312013-06-14 11:29:53 -0700439 int orig_major = crypt_ftr->major_version;
440 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700441
Kenny Root7434b312013-06-14 11:29:53 -0700442 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
443 struct crypt_persist_data *pdata;
444 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700445
Kenny Rootc4c70f12013-06-14 12:11:38 -0700446 SLOGW("upgrading crypto footer to 1.1");
447
Wei Wang4375f1b2017-02-24 17:43:01 -0800448 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700449 if (pdata == NULL) {
450 SLOGE("Cannot allocate persisent data\n");
451 return;
452 }
453 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
454
455 /* Need to initialize the persistent data area */
456 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
457 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100458 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700459 return;
460 }
461 /* Write all zeros to the first copy, making it invalid */
462 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
463
464 /* Write a valid but empty structure to the second copy */
465 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
466 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
467
468 /* Update the footer */
469 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
470 crypt_ftr->persist_data_offset[0] = pdata_offset;
471 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
472 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100473 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700474 }
475
Paul Lawrencef4faa572014-01-29 13:31:03 -0800476 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700477 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800478 /* But keep the old kdf_type.
479 * It will get updated later to KDF_SCRYPT after the password has been verified.
480 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700481 crypt_ftr->kdf_type = KDF_PBKDF2;
482 get_device_scrypt_params(crypt_ftr);
483 crypt_ftr->minor_version = 2;
484 }
485
Paul Lawrencef4faa572014-01-29 13:31:03 -0800486 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
487 SLOGW("upgrading crypto footer to 1.3");
488 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
489 crypt_ftr->minor_version = 3;
490 }
491
Kenny Root7434b312013-06-14 11:29:53 -0700492 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
493 if (lseek64(fd, offset, SEEK_SET) == -1) {
494 SLOGE("Cannot seek to crypt footer\n");
495 return;
496 }
497 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700498 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700499}
500
501
502static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800503{
504 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800505 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700506 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800507 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700508 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700509 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800510
Ken Sumrall160b4d62013-04-22 12:15:39 -0700511 if (get_crypt_ftr_info(&fname, &starting_off)) {
512 SLOGE("Unable to get crypt_ftr_info\n");
513 return -1;
514 }
515 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700516 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700517 return -1;
518 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700519 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700520 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700521 return -1;
522 }
523
524 /* Make sure it's 16 Kbytes in length */
525 fstat(fd, &statbuf);
526 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
527 SLOGE("footer file %s is not the expected size!\n", fname);
528 goto errout;
529 }
530
531 /* Seek to the start of the crypt footer */
532 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
533 SLOGE("Cannot seek to real block device footer\n");
534 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800535 }
536
537 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
538 SLOGE("Cannot read real block device footer\n");
539 goto errout;
540 }
541
542 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700543 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800544 goto errout;
545 }
546
Kenny Rootc96a5f82013-06-14 12:08:28 -0700547 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
548 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
549 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800550 goto errout;
551 }
552
Kenny Rootc96a5f82013-06-14 12:08:28 -0700553 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
554 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
555 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800556 }
557
Ken Sumrall160b4d62013-04-22 12:15:39 -0700558 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
559 * copy on disk before returning.
560 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700561 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700562 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800563 }
564
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800565 /* Success! */
566 rc = 0;
567
568errout:
569 close(fd);
570 return rc;
571}
572
Ken Sumrall160b4d62013-04-22 12:15:39 -0700573static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
574{
575 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
576 crypt_ftr->persist_data_offset[1]) {
577 SLOGE("Crypt_ftr persist data regions overlap");
578 return -1;
579 }
580
581 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
582 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
583 return -1;
584 }
585
586 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
587 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
588 CRYPT_FOOTER_OFFSET) {
589 SLOGE("Persistent data extends past crypto footer");
590 return -1;
591 }
592
593 return 0;
594}
595
596static int load_persistent_data(void)
597{
598 struct crypt_mnt_ftr crypt_ftr;
599 struct crypt_persist_data *pdata = NULL;
600 char encrypted_state[PROPERTY_VALUE_MAX];
601 char *fname;
602 int found = 0;
603 int fd;
604 int ret;
605 int i;
606
607 if (persist_data) {
608 /* Nothing to do, we've already loaded or initialized it */
609 return 0;
610 }
611
612
613 /* If not encrypted, just allocate an empty table and initialize it */
614 property_get("ro.crypto.state", encrypted_state, "");
615 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800616 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700617 if (pdata) {
618 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
619 persist_data = pdata;
620 return 0;
621 }
622 return -1;
623 }
624
625 if(get_crypt_ftr_and_key(&crypt_ftr)) {
626 return -1;
627 }
628
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700629 if ((crypt_ftr.major_version < 1)
630 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700631 SLOGE("Crypt_ftr version doesn't support persistent data");
632 return -1;
633 }
634
635 if (get_crypt_ftr_info(&fname, NULL)) {
636 return -1;
637 }
638
639 ret = validate_persistent_data_storage(&crypt_ftr);
640 if (ret) {
641 return -1;
642 }
643
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700644 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700645 if (fd < 0) {
646 SLOGE("Cannot open %s metadata file", fname);
647 return -1;
648 }
649
Wei Wang4375f1b2017-02-24 17:43:01 -0800650 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800651 if (pdata == NULL) {
652 SLOGE("Cannot allocate memory for persistent data");
653 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700654 }
655
656 for (i = 0; i < 2; i++) {
657 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
658 SLOGE("Cannot seek to read persistent data on %s", fname);
659 goto err2;
660 }
661 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
662 SLOGE("Error reading persistent data on iteration %d", i);
663 goto err2;
664 }
665 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
666 found = 1;
667 break;
668 }
669 }
670
671 if (!found) {
672 SLOGI("Could not find valid persistent data, creating");
673 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
674 }
675
676 /* Success */
677 persist_data = pdata;
678 close(fd);
679 return 0;
680
681err2:
682 free(pdata);
683
684err:
685 close(fd);
686 return -1;
687}
688
689static int save_persistent_data(void)
690{
691 struct crypt_mnt_ftr crypt_ftr;
692 struct crypt_persist_data *pdata;
693 char *fname;
694 off64_t write_offset;
695 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700696 int fd;
697 int ret;
698
699 if (persist_data == NULL) {
700 SLOGE("No persistent data to save");
701 return -1;
702 }
703
704 if(get_crypt_ftr_and_key(&crypt_ftr)) {
705 return -1;
706 }
707
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700708 if ((crypt_ftr.major_version < 1)
709 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700710 SLOGE("Crypt_ftr version doesn't support persistent data");
711 return -1;
712 }
713
714 ret = validate_persistent_data_storage(&crypt_ftr);
715 if (ret) {
716 return -1;
717 }
718
719 if (get_crypt_ftr_info(&fname, NULL)) {
720 return -1;
721 }
722
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700723 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700724 if (fd < 0) {
725 SLOGE("Cannot open %s metadata file", fname);
726 return -1;
727 }
728
Wei Wang4375f1b2017-02-24 17:43:01 -0800729 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700730 if (pdata == NULL) {
731 SLOGE("Cannot allocate persistant data");
732 goto err;
733 }
734
735 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
736 SLOGE("Cannot seek to read persistent data on %s", fname);
737 goto err2;
738 }
739
740 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
741 SLOGE("Error reading persistent data before save");
742 goto err2;
743 }
744
745 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
746 /* The first copy is the curent valid copy, so write to
747 * the second copy and erase this one */
748 write_offset = crypt_ftr.persist_data_offset[1];
749 erase_offset = crypt_ftr.persist_data_offset[0];
750 } else {
751 /* The second copy must be the valid copy, so write to
752 * the first copy, and erase the second */
753 write_offset = crypt_ftr.persist_data_offset[0];
754 erase_offset = crypt_ftr.persist_data_offset[1];
755 }
756
757 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100758 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700759 SLOGE("Cannot seek to write persistent data");
760 goto err2;
761 }
762 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
763 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100764 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700765 SLOGE("Cannot seek to erase previous persistent data");
766 goto err2;
767 }
768 fsync(fd);
769 memset(pdata, 0, crypt_ftr.persist_data_size);
770 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
771 (int) crypt_ftr.persist_data_size) {
772 SLOGE("Cannot write to erase previous persistent data");
773 goto err2;
774 }
775 fsync(fd);
776 } else {
777 SLOGE("Cannot write to save persistent data");
778 goto err2;
779 }
780
781 /* Success */
782 free(pdata);
783 close(fd);
784 return 0;
785
786err2:
787 free(pdata);
788err:
789 close(fd);
790 return -1;
791}
792
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800793/* Convert a binary key of specified length into an ascii hex string equivalent,
794 * without the leading 0x and with null termination
795 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700796static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700797 unsigned int keysize, char *master_key_ascii) {
798 unsigned int i, a;
799 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800800
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700801 for (i=0, a=0; i<keysize; i++, a+=2) {
802 /* For each byte, write out two ascii hex digits */
803 nibble = (master_key[i] >> 4) & 0xf;
804 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800805
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700806 nibble = master_key[i] & 0xf;
807 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
808 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800809
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700810 /* Add the null termination */
811 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800812
813}
814
Jeff Sharkey9c484982015-03-31 10:35:33 -0700815static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
816 const unsigned char *master_key, const char *real_blk_name,
817 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800818 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800819 struct dm_ioctl *io;
820 struct dm_target_spec *tgt;
821 char *crypt_params;
822 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800823 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800824 int i;
825
826 io = (struct dm_ioctl *) buffer;
827
828 /* Load the mapping table for this device */
829 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
830
831 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
832 io->target_count = 1;
833 tgt->status = 0;
834 tgt->sector_start = 0;
835 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700836 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800837
838 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
839 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800840
841 buff_offset = crypt_params - buffer;
842 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
843 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
844 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800845 crypt_params += strlen(crypt_params) + 1;
846 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
847 tgt->next = crypt_params - buffer;
848
849 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
850 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
851 break;
852 }
853 usleep(500000);
854 }
855
856 if (i == TABLE_LOAD_RETRIES) {
857 /* We failed to load the table, return an error */
858 return -1;
859 } else {
860 return i + 1;
861 }
862}
863
864
865static int get_dm_crypt_version(int fd, const char *name, int *version)
866{
867 char buffer[DM_CRYPT_BUF_SIZE];
868 struct dm_ioctl *io;
869 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800870
871 io = (struct dm_ioctl *) buffer;
872
873 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
874
875 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
876 return -1;
877 }
878
879 /* Iterate over the returned versions, looking for name of "crypt".
880 * When found, get and return the version.
881 */
882 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
883 while (v->next) {
884 if (! strcmp(v->name, "crypt")) {
885 /* We found the crypt driver, return the version, and get out */
886 version[0] = v->version[0];
887 version[1] = v->version[1];
888 version[2] = v->version[2];
889 return 0;
890 }
891 v = (struct dm_target_versions *)(((char *)v) + v->next);
892 }
893
894 return -1;
895}
896
Jeff Sharkey9c484982015-03-31 10:35:33 -0700897static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
898 const unsigned char *master_key, const char *real_blk_name,
899 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800900 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800901 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800902 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -0700903 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800904 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800905 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800906 int version[3];
Wei Wang4375f1b2017-02-24 17:43:01 -0800907 const char *extra_params;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800908 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800909
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700910 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800911 SLOGE("Cannot open device-mapper\n");
912 goto errout;
913 }
914
915 io = (struct dm_ioctl *) buffer;
916
917 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800918 err = ioctl(fd, DM_DEV_CREATE, io);
919 if (err) {
920 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800921 goto errout;
922 }
923
924 /* Get the device status, in particular, the name of it's device file */
925 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
926 if (ioctl(fd, DM_DEV_STATUS, io)) {
927 SLOGE("Cannot retrieve dm-crypt device status\n");
928 goto errout;
929 }
930 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
931 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
932
Ken Sumralldb5e0262013-02-05 17:39:48 -0800933 extra_params = "";
934 if (! get_dm_crypt_version(fd, name, version)) {
935 /* Support for allow_discards was added in version 1.11.0 */
936 if ((version[0] >= 2) ||
937 ((version[0] == 1) && (version[1] >= 11))) {
938 extra_params = "1 allow_discards";
939 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
940 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700941 }
942
Ken Sumralldb5e0262013-02-05 17:39:48 -0800943 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
944 fd, extra_params);
945 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800946 SLOGE("Cannot load dm-crypt mapping table.\n");
947 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800948 } else if (load_count > 1) {
949 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800950 }
951
952 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800953 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800954
955 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
956 SLOGE("Cannot resume the dm-crypt device\n");
957 goto errout;
958 }
959
960 /* We made it here with no errors. Woot! */
961 retval = 0;
962
963errout:
964 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
965
966 return retval;
967}
968
Wei Wang4375f1b2017-02-24 17:43:01 -0800969static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800970{
971 int fd;
972 char buffer[DM_CRYPT_BUF_SIZE];
973 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800974 int retval = -1;
975
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700976 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800977 SLOGE("Cannot open device-mapper\n");
978 goto errout;
979 }
980
981 io = (struct dm_ioctl *) buffer;
982
983 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
984 if (ioctl(fd, DM_DEV_REMOVE, io)) {
985 SLOGE("Cannot remove dm-crypt device\n");
986 goto errout;
987 }
988
989 /* We made it here with no errors. Woot! */
990 retval = 0;
991
992errout:
993 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
994
995 return retval;
996
997}
998
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700999static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001000 unsigned char *ikey, void *params UNUSED)
1001{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001002 SLOGI("Using pbkdf2 for cryptfs KDF");
1003
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001004 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001005 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1006 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1007 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001008}
1009
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001010static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001011 unsigned char *ikey, void *params)
1012{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001013 SLOGI("Using scrypt for cryptfs KDF");
1014
Kenny Rootc4c70f12013-06-14 12:11:38 -07001015 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1016
1017 int N = 1 << ftr->N_factor;
1018 int r = 1 << ftr->r_factor;
1019 int p = 1 << ftr->p_factor;
1020
1021 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001022 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001023 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1024 salt, SALT_LEN, N, r, p, ikey,
1025 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001026
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001027 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001028}
1029
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001030static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1031 unsigned char *ikey, void *params)
1032{
1033 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1034
1035 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001036 size_t signature_size;
1037 unsigned char* signature;
1038 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1039
1040 int N = 1 << ftr->N_factor;
1041 int r = 1 << ftr->r_factor;
1042 int p = 1 << ftr->p_factor;
1043
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001044 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1045 salt, SALT_LEN, N, r, p, ikey,
1046 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001047
1048 if (rc) {
1049 SLOGE("scrypt failed");
1050 return -1;
1051 }
1052
Shawn Willdene17a9c42014-09-08 13:04:08 -06001053 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1054 &signature, &signature_size)) {
1055 SLOGE("Signing failed");
1056 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001057 }
1058
1059 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1060 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1061 free(signature);
1062
1063 if (rc) {
1064 SLOGE("scrypt failed");
1065 return -1;
1066 }
1067
1068 return 0;
1069}
1070
1071static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1072 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001073 unsigned char *encrypted_master_key,
1074 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001075{
1076 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1077 EVP_CIPHER_CTX e_ctx;
1078 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001079 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001080
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001081 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001082 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001083
1084 switch (crypt_ftr->kdf_type) {
1085 case KDF_SCRYPT_KEYMASTER:
1086 if (keymaster_create_key(crypt_ftr)) {
1087 SLOGE("keymaster_create_key failed");
1088 return -1;
1089 }
1090
1091 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1092 SLOGE("scrypt failed");
1093 return -1;
1094 }
1095 break;
1096
1097 case KDF_SCRYPT:
1098 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1099 SLOGE("scrypt failed");
1100 return -1;
1101 }
1102 break;
1103
1104 default:
1105 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001106 return -1;
1107 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001108
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001109 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001110 EVP_CIPHER_CTX_init(&e_ctx);
1111 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001112 SLOGE("EVP_EncryptInit failed\n");
1113 return -1;
1114 }
1115 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001116
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001118 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001119 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001120 SLOGE("EVP_EncryptUpdate failed\n");
1121 return -1;
1122 }
Adam Langley889c4f12014-09-03 14:23:13 -07001123 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001124 SLOGE("EVP_EncryptFinal failed\n");
1125 return -1;
1126 }
1127
1128 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1129 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1130 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001132
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001133 /* Store the scrypt of the intermediate key, so we can validate if it's a
1134 password error or mount error when things go wrong.
1135 Note there's no need to check for errors, since if this is incorrect, we
1136 simply won't wipe userdata, which is the correct default behavior
1137 */
1138 int N = 1 << crypt_ftr->N_factor;
1139 int r = 1 << crypt_ftr->r_factor;
1140 int p = 1 << crypt_ftr->p_factor;
1141
1142 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1143 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1144 crypt_ftr->scrypted_intermediate_key,
1145 sizeof(crypt_ftr->scrypted_intermediate_key));
1146
1147 if (rc) {
1148 SLOGE("encrypt_master_key: crypto_scrypt failed");
1149 }
1150
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001151 EVP_CIPHER_CTX_cleanup(&e_ctx);
1152
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001153 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001154}
1155
Paul Lawrence731a7a22015-04-28 22:14:15 +00001156static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001157 unsigned char *encrypted_master_key,
1158 unsigned char *decrypted_master_key,
1159 kdf_func kdf, void *kdf_params,
1160 unsigned char** intermediate_key,
1161 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001162{
1163 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 -08001164 EVP_CIPHER_CTX d_ctx;
1165 int decrypted_len, final_len;
1166
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001167 /* Turn the password into an intermediate key and IV that can decrypt the
1168 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001169 if (kdf(passwd, salt, ikey, kdf_params)) {
1170 SLOGE("kdf failed");
1171 return -1;
1172 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001173
1174 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001175 EVP_CIPHER_CTX_init(&d_ctx);
1176 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001177 return -1;
1178 }
1179 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1180 /* Decrypt the master key */
1181 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1182 encrypted_master_key, KEY_LEN_BYTES)) {
1183 return -1;
1184 }
Adam Langley889c4f12014-09-03 14:23:13 -07001185 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001186 return -1;
1187 }
1188
1189 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1190 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001191 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001192
1193 /* Copy intermediate key if needed by params */
1194 if (intermediate_key && intermediate_key_size) {
1195 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001196 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001197 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1198 *intermediate_key_size = KEY_LEN_BYTES;
1199 }
1200 }
1201
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001202 EVP_CIPHER_CTX_cleanup(&d_ctx);
1203
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001204 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001205}
1206
Kenny Rootc4c70f12013-06-14 12:11:38 -07001207static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001208{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001209 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001210 *kdf = scrypt_keymaster;
1211 *kdf_params = ftr;
1212 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001213 *kdf = scrypt;
1214 *kdf_params = ftr;
1215 } else {
1216 *kdf = pbkdf2;
1217 *kdf_params = NULL;
1218 }
1219}
1220
Paul Lawrence731a7a22015-04-28 22:14:15 +00001221static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001222 struct crypt_mnt_ftr *crypt_ftr,
1223 unsigned char** intermediate_key,
1224 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001225{
1226 kdf_func kdf;
1227 void *kdf_params;
1228 int ret;
1229
1230 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001231 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1232 decrypted_master_key, kdf, kdf_params,
1233 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001234 if (ret != 0) {
1235 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001236 }
1237
1238 return ret;
1239}
1240
Wei Wang4375f1b2017-02-24 17:43:01 -08001241static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001242 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001243 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001244 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001245
1246 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001247 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001248 read(fd, key_buf, sizeof(key_buf));
1249 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001250 close(fd);
1251
1252 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001253 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001254}
1255
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001256int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001257{
Greg Hackmann955653e2014-09-24 14:55:20 -07001258 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001259#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260
1261 /* Now umount the tmpfs filesystem */
1262 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001263 if (umount(mountpoint) == 0) {
1264 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001265 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001266
1267 if (errno == EINVAL) {
1268 /* EINVAL is returned if the directory is not a mountpoint,
1269 * i.e. there is no filesystem mounted there. So just get out.
1270 */
1271 break;
1272 }
1273
1274 err = errno;
1275
1276 /* If allowed, be increasingly aggressive before the last two retries */
1277 if (kill) {
1278 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1279 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001280 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001281 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1282 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001283 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001284 }
1285 }
1286
1287 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001288 }
1289
1290 if (i < WAIT_UNMOUNT_COUNT) {
1291 SLOGD("unmounting %s succeeded\n", mountpoint);
1292 rc = 0;
1293 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001294 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001295 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001296 rc = -1;
1297 }
1298
1299 return rc;
1300}
1301
Wei Wang42e38102017-06-07 10:46:12 -07001302static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001303{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001304 // NOTE: post_fs_data results in init calling back around to vold, so all
1305 // callers to this method must be async
1306
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001307 /* Do the prep of the /data filesystem */
1308 property_set("vold.post_fs_data_done", "0");
1309 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001310 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001311
Ken Sumrallc5872692013-05-14 15:26:31 -07001312 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001313 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001314 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001315 std::chrono::seconds(15))) {
1316 /* We timed out to prep /data in time. Continue wait. */
1317 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001318 }
Wei Wang42e38102017-06-07 10:46:12 -07001319 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001320}
1321
Paul Lawrence74f29f12014-08-28 15:54:10 -07001322static void cryptfs_set_corrupt()
1323{
1324 // Mark the footer as bad
1325 struct crypt_mnt_ftr crypt_ftr;
1326 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1327 SLOGE("Failed to get crypto footer - panic");
1328 return;
1329 }
1330
1331 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1332 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1333 SLOGE("Failed to set crypto footer - panic");
1334 return;
1335 }
1336}
1337
1338static void cryptfs_trigger_restart_min_framework()
1339{
1340 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1341 SLOGE("Failed to mount tmpfs on data - panic");
1342 return;
1343 }
1344
1345 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1346 SLOGE("Failed to trigger post fs data - panic");
1347 return;
1348 }
1349
1350 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1351 SLOGE("Failed to trigger restart min framework - panic");
1352 return;
1353 }
1354}
1355
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001356/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001357static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001358{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001359 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001360 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001361 static int restart_successful = 0;
1362
1363 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001364 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001365 SLOGE("Encrypted filesystem not validated, aborting");
1366 return -1;
1367 }
1368
1369 if (restart_successful) {
1370 SLOGE("System already restarted with encrypted disk, aborting");
1371 return -1;
1372 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373
Paul Lawrencef4faa572014-01-29 13:31:03 -08001374 if (restart_main) {
1375 /* Here is where we shut down the framework. The init scripts
1376 * start all services in one of three classes: core, main or late_start.
1377 * On boot, we start core and main. Now, we stop main, but not core,
1378 * as core includes vold and a few other really important things that
1379 * we need to keep running. Once main has stopped, we should be able
1380 * to umount the tmpfs /data, then mount the encrypted /data.
1381 * We then restart the class main, and also the class late_start.
1382 * At the moment, I've only put a few things in late_start that I know
1383 * are not needed to bring up the framework, and that also cause problems
1384 * with unmounting the tmpfs /data, but I hope to add add more services
1385 * to the late_start class as we optimize this to decrease the delay
1386 * till the user is asked for the password to the filesystem.
1387 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001388
Paul Lawrencef4faa572014-01-29 13:31:03 -08001389 /* The init files are setup to stop the class main when vold.decrypt is
1390 * set to trigger_reset_main.
1391 */
1392 property_set("vold.decrypt", "trigger_reset_main");
1393 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001394
Paul Lawrencef4faa572014-01-29 13:31:03 -08001395 /* Ugh, shutting down the framework is not synchronous, so until it
1396 * can be fixed, this horrible hack will wait a moment for it all to
1397 * shut down before proceeding. Without it, some devices cannot
1398 * restart the graphics services.
1399 */
1400 sleep(2);
1401 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001402
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001403 /* Now that the framework is shutdown, we should be able to umount()
1404 * the tmpfs filesystem, and mount the real one.
1405 */
1406
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001407 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1408 if (strlen(crypto_blkdev) == 0) {
1409 SLOGE("fs_crypto_blkdev not set\n");
1410 return -1;
1411 }
1412
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001413 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001414 /* If ro.crypto.readonly is set to 1, mount the decrypted
1415 * filesystem readonly. This is used when /data is mounted by
1416 * recovery mode.
1417 */
1418 char ro_prop[PROPERTY_VALUE_MAX];
1419 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001420 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001421 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001422 rec->flags |= MS_RDONLY;
1423 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001424
Ken Sumralle5032c42012-04-01 23:58:44 -07001425 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001426 int retries = RETRY_MOUNT_ATTEMPTS;
1427 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001428
1429 /*
1430 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1431 * partitions in the fsck domain.
1432 */
1433 if (setexeccon(secontextFsck())){
1434 SLOGE("Failed to setexeccon");
1435 return -1;
1436 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001437 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001438 crypto_blkdev, 0))
1439 != 0) {
1440 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1441 /* TODO: invoke something similar to
1442 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1443 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1444 SLOGI("Failed to mount %s because it is busy - waiting",
1445 crypto_blkdev);
1446 if (--retries) {
1447 sleep(RETRY_MOUNT_DELAY_SECONDS);
1448 } else {
1449 /* Let's hope that a reboot clears away whatever is keeping
1450 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001451 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001452 }
1453 } else {
1454 SLOGE("Failed to mount decrypted data");
1455 cryptfs_set_corrupt();
1456 cryptfs_trigger_restart_min_framework();
1457 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001458 if (setexeccon(NULL)) {
1459 SLOGE("Failed to setexeccon");
1460 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001461 return -1;
1462 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001463 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001464 if (setexeccon(NULL)) {
1465 SLOGE("Failed to setexeccon");
1466 return -1;
1467 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001468
Ken Sumralle5032c42012-04-01 23:58:44 -07001469 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001470 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001471 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001472
1473 /* startup service classes main and late_start */
1474 property_set("vold.decrypt", "trigger_restart_framework");
1475 SLOGD("Just triggered restart_framework\n");
1476
1477 /* Give it a few moments to get started */
1478 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001479 }
1480
Ken Sumrall0cc16632011-01-18 20:32:26 -08001481 if (rc == 0) {
1482 restart_successful = 1;
1483 }
1484
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001485 return rc;
1486}
1487
Paul Lawrencef4faa572014-01-29 13:31:03 -08001488int cryptfs_restart(void)
1489{
Paul Lawrence05335c32015-03-05 09:46:23 -08001490 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001491 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001492 SLOGE("cryptfs_restart not valid for file encryption:");
1493 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001494 }
1495
Paul Lawrencef4faa572014-01-29 13:31:03 -08001496 /* Call internal implementation forcing a restart of main service group */
1497 return cryptfs_restart_internal(1);
1498}
1499
Wei Wang4375f1b2017-02-24 17:43:01 -08001500static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001501{
1502 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001503 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001504 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001505
1506 property_get("ro.crypto.state", encrypted_state, "");
1507 if (strcmp(encrypted_state, "encrypted") ) {
1508 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001509 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001510 }
1511
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001512 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001513 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001514 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001515 }
1516
Ken Sumrall160b4d62013-04-22 12:15:39 -07001517 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001518 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001519
Ken Sumralle1a45852011-12-14 21:24:27 -08001520 /*
1521 * Only report this error if key_loc is a file and it exists.
1522 * If the device was never encrypted, and /data is not mountable for
1523 * some reason, returning 1 should prevent the UI from presenting the
1524 * a "enter password" screen, or worse, a "press button to wipe the
1525 * device" screen.
1526 */
1527 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1528 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001529 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001530 } else {
1531 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001532 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001533 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001534 }
1535
Paul Lawrence74f29f12014-08-28 15:54:10 -07001536 // Test for possible error flags
1537 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1538 SLOGE("Encryption process is partway completed\n");
1539 return CRYPTO_COMPLETE_PARTIAL;
1540 }
1541
1542 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1543 SLOGE("Encryption process was interrupted but cannot continue\n");
1544 return CRYPTO_COMPLETE_INCONSISTENT;
1545 }
1546
1547 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1548 SLOGE("Encryption is successful but data is corrupt\n");
1549 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001550 }
1551
1552 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001553 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001554}
1555
Paul Lawrencef4faa572014-01-29 13:31:03 -08001556static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001557 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001558{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001559 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001560 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001561 char crypto_blkdev[MAXPATHLEN];
1562 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001563 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001564 unsigned int orig_failed_decrypt_count;
1565 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001566 int use_keymaster = 0;
1567 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001568 unsigned char* intermediate_key = 0;
1569 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001570 int N = 1 << crypt_ftr->N_factor;
1571 int r = 1 << crypt_ftr->r_factor;
1572 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001573
Paul Lawrencef4faa572014-01-29 13:31:03 -08001574 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1575 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001576
Paul Lawrencef4faa572014-01-29 13:31:03 -08001577 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001578 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1579 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001580 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001581 rc = -1;
1582 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001583 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584 }
1585
Paul Crowleye2ee1522017-09-26 14:05:26 -07001586 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001587
Paul Lawrence74f29f12014-08-28 15:54:10 -07001588 // Create crypto block device - all (non fatal) code paths
1589 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001590 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1591 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001592 SLOGE("Error creating decrypted block device\n");
1593 rc = -1;
1594 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001595 }
1596
Paul Lawrence74f29f12014-08-28 15:54:10 -07001597 /* Work out if the problem is the password or the data */
1598 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1599 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001600
Paul Lawrence74f29f12014-08-28 15:54:10 -07001601 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1602 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1603 N, r, p, scrypted_intermediate_key,
1604 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001605
Paul Lawrence74f29f12014-08-28 15:54:10 -07001606 // Does the key match the crypto footer?
1607 if (rc == 0 && memcmp(scrypted_intermediate_key,
1608 crypt_ftr->scrypted_intermediate_key,
1609 sizeof(scrypted_intermediate_key)) == 0) {
1610 SLOGI("Password matches");
1611 rc = 0;
1612 } else {
1613 /* Try mounting the file system anyway, just in case the problem's with
1614 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001615 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1616 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001617 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001618 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001619 SLOGE("Error temp mounting decrypted block device\n");
1620 delete_crypto_blk_dev(label);
1621
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001622 rc = ++crypt_ftr->failed_decrypt_count;
1623 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001624 } else {
1625 /* Success! */
1626 SLOGI("Password did not match but decrypted drive mounted - continue");
1627 umount(tmp_mount_point);
1628 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001629 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001630 }
1631
1632 if (rc == 0) {
1633 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001634 if (orig_failed_decrypt_count != 0) {
1635 put_crypt_ftr_and_key(crypt_ftr);
1636 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001637
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001638 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001639 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001640 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001641
1642 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001643 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001644 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001645 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001646 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001647 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001648 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001649
Paul Lawrence74f29f12014-08-28 15:54:10 -07001650 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001651 use_keymaster = keymaster_check_compatibility();
1652 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001653 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001654 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1655 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1656 upgrade = 1;
1657 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001658 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001659 upgrade = 1;
1660 }
1661
1662 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001663 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1664 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001665 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001666 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001667 }
1668 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001669
1670 // Do not fail even if upgrade failed - machine is bootable
1671 // Note that if this code is ever hit, there is a *serious* problem
1672 // since KDFs should never fail. You *must* fix the kdf before
1673 // proceeding!
1674 if (rc) {
1675 SLOGW("Upgrade failed with error %d,"
1676 " but continuing with previous state",
1677 rc);
1678 rc = 0;
1679 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001680 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001681 }
1682
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001683 errout:
1684 if (intermediate_key) {
1685 memset(intermediate_key, 0, intermediate_key_size);
1686 free(intermediate_key);
1687 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001688 return rc;
1689}
1690
Ken Sumrall29d8da82011-05-18 17:20:07 -07001691/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001692 * Called by vold when it's asked to mount an encrypted external
1693 * storage volume. The incoming partition has no crypto header/footer,
1694 * as any metadata is been stored in a separate, small partition.
1695 *
1696 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001697 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001698int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1699 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001700 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001701 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001702 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001703 return -1;
1704 }
1705
1706 unsigned long nr_sec = 0;
1707 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001708 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001709
Ken Sumrall29d8da82011-05-18 17:20:07 -07001710 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001711 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001712 return -1;
1713 }
1714
Jeff Sharkey9c484982015-03-31 10:35:33 -07001715 struct crypt_mnt_ftr ext_crypt_ftr;
1716 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1717 ext_crypt_ftr.fs_size = nr_sec;
1718 ext_crypt_ftr.keysize = keysize;
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001719 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
1720 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001721
Jeff Sharkey9c484982015-03-31 10:35:33 -07001722 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1723 out_crypto_blkdev, label);
1724}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001725
Jeff Sharkey9c484982015-03-31 10:35:33 -07001726/*
1727 * Called by vold when it's asked to unmount an encrypted external
1728 * storage volume.
1729 */
1730int cryptfs_revert_ext_volume(const char* label) {
1731 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001732}
1733
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001734int cryptfs_crypto_complete(void)
1735{
1736 return do_crypto_complete("/data");
1737}
1738
Paul Lawrencef4faa572014-01-29 13:31:03 -08001739int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1740{
1741 char encrypted_state[PROPERTY_VALUE_MAX];
1742 property_get("ro.crypto.state", encrypted_state, "");
1743 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1744 SLOGE("encrypted fs already validated or not running with encryption,"
1745 " aborting");
1746 return -1;
1747 }
1748
1749 if (get_crypt_ftr_and_key(crypt_ftr)) {
1750 SLOGE("Error getting crypt footer and key");
1751 return -1;
1752 }
1753
1754 return 0;
1755}
1756
Wei Wang4375f1b2017-02-24 17:43:01 -08001757int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001758{
Paul Lawrence05335c32015-03-05 09:46:23 -08001759 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001760 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001761 SLOGE("cryptfs_check_passwd not valid for file encryption");
1762 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001763 }
1764
Paul Lawrencef4faa572014-01-29 13:31:03 -08001765 struct crypt_mnt_ftr crypt_ftr;
1766 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001767
Paul Lawrencef4faa572014-01-29 13:31:03 -08001768 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001769 if (rc) {
1770 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001771 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001772 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001773
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001774 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001775 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1776 if (rc) {
1777 SLOGE("Password did not match");
1778 return rc;
1779 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001780
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001781 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1782 // Here we have a default actual password but a real password
1783 // we must test against the scrypted value
1784 // First, we must delete the crypto block device that
1785 // test_mount_encrypted_fs leaves behind as a side effect
1786 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1787 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1788 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1789 if (rc) {
1790 SLOGE("Default password did not match on reboot encryption");
1791 return rc;
1792 }
1793
1794 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1795 put_crypt_ftr_and_key(&crypt_ftr);
1796 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1797 if (rc) {
1798 SLOGE("Could not change password on reboot encryption");
1799 return rc;
1800 }
1801 }
1802
1803 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001804 cryptfs_clear_password();
1805 password = strdup(passwd);
1806 struct timespec now;
1807 clock_gettime(CLOCK_BOOTTIME, &now);
1808 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001809 }
1810
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001811 return rc;
1812}
1813
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001814int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001815{
1816 struct crypt_mnt_ftr crypt_ftr;
1817 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001818 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001819 char encrypted_state[PROPERTY_VALUE_MAX];
1820 int rc;
1821
1822 property_get("ro.crypto.state", encrypted_state, "");
1823 if (strcmp(encrypted_state, "encrypted") ) {
1824 SLOGE("device not encrypted, aborting");
1825 return -2;
1826 }
1827
1828 if (!master_key_saved) {
1829 SLOGE("encrypted fs not yet mounted, aborting");
1830 return -1;
1831 }
1832
1833 if (!saved_mount_point) {
1834 SLOGE("encrypted fs failed to save mount point, aborting");
1835 return -1;
1836 }
1837
Ken Sumrall160b4d62013-04-22 12:15:39 -07001838 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001839 SLOGE("Error getting crypt footer and key\n");
1840 return -1;
1841 }
1842
1843 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1844 /* If the device has no password, then just say the password is valid */
1845 rc = 0;
1846 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001847 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001848 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1849 /* They match, the password is correct */
1850 rc = 0;
1851 } else {
1852 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1853 sleep(1);
1854 rc = 1;
1855 }
1856 }
1857
1858 return rc;
1859}
1860
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001861/* Initialize a crypt_mnt_ftr structure. The keysize is
1862 * defaulted to 16 bytes, and the filesystem size to 0.
1863 * Presumably, at a minimum, the caller will update the
1864 * filesystem size and crypto_type_name after calling this function.
1865 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001866static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001867{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001868 off64_t off;
1869
1870 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001871 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001872 ftr->major_version = CURRENT_MAJOR_VERSION;
1873 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001874 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001875 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001876
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001877 switch (keymaster_check_compatibility()) {
1878 case 1:
1879 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1880 break;
1881
1882 case 0:
1883 ftr->kdf_type = KDF_SCRYPT;
1884 break;
1885
1886 default:
1887 SLOGE("keymaster_check_compatibility failed");
1888 return -1;
1889 }
1890
Kenny Rootc4c70f12013-06-14 12:11:38 -07001891 get_device_scrypt_params(ftr);
1892
Ken Sumrall160b4d62013-04-22 12:15:39 -07001893 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1894 if (get_crypt_ftr_info(NULL, &off) == 0) {
1895 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1896 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1897 ftr->persist_data_size;
1898 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001899
1900 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001901}
1902
Ken Sumrall29d8da82011-05-18 17:20:07 -07001903static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001904{
Ken Sumralle550f782013-08-20 13:48:23 -07001905 const char *args[10];
1906 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1907 int num_args;
1908 int status;
1909 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001910 int rc = -1;
1911
Ken Sumrall29d8da82011-05-18 17:20:07 -07001912 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001913 args[0] = "/system/bin/mke2fs";
1914 args[1] = "-M";
1915 args[2] = "/data";
1916 args[3] = "-b";
1917 args[4] = "4096";
1918 args[5] = "-t";
1919 args[6] = "ext4";
1920 args[7] = crypto_blkdev;
1921 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1922 args[8] = size_str;
1923 num_args = 9;
Ken Sumralle550f782013-08-20 13:48:23 -07001924 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1925 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001926 } else if (type == F2FS_FS) {
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001927 args[0] = "/system/bin/make_f2fs";
JP Abgrall62c7af32014-06-16 13:01:23 -07001928 args[1] = "-t";
1929 args[2] = "-d1";
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001930 args[3] = "-f";
1931 args[4] = "-O encrypt";
1932 args[5] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001933 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
Jaegeuk Kimab48bc92017-06-05 10:22:04 -07001934 args[6] = size_str;
1935 num_args = 7;
1936 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s\n",
1937 args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001938 } else {
1939 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1940 return -1;
1941 }
1942
Ken Sumralle550f782013-08-20 13:48:23 -07001943 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1944
1945 if (tmp != 0) {
1946 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001947 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001948 if (WIFEXITED(status)) {
1949 if (WEXITSTATUS(status)) {
1950 SLOGE("Error creating filesystem on %s, exit status %d ",
1951 crypto_blkdev, WEXITSTATUS(status));
1952 } else {
1953 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1954 rc = 0;
1955 }
1956 } else {
1957 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1958 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001959 }
1960
1961 return rc;
1962}
1963
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001964#define CRYPTO_ENABLE_WIPE 1
1965#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001966
1967#define FRAMEWORK_BOOT_WAIT 60
1968
Paul Lawrence87999172014-02-20 12:21:31 -08001969static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1970{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001971 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001972 if (fd == -1) {
1973 SLOGE("Error opening file %s", filename);
1974 return -1;
1975 }
1976
1977 char block[CRYPT_INPLACE_BUFSIZE];
1978 memset(block, 0, sizeof(block));
1979 if (unix_read(fd, block, sizeof(block)) < 0) {
1980 SLOGE("Error reading file %s", filename);
1981 close(fd);
1982 return -1;
1983 }
1984
1985 close(fd);
1986
1987 SHA256_CTX c;
1988 SHA256_Init(&c);
1989 SHA256_Update(&c, block, sizeof(block));
1990 SHA256_Final(buf, &c);
1991
1992 return 0;
1993}
1994
JP Abgrall62c7af32014-06-16 13:01:23 -07001995static int get_fs_type(struct fstab_rec *rec)
1996{
1997 if (!strcmp(rec->fs_type, "ext4")) {
1998 return EXT4_FS;
1999 } else if (!strcmp(rec->fs_type, "f2fs")) {
2000 return F2FS_FS;
2001 } else {
2002 return -1;
2003 }
2004}
2005
Paul Lawrence87999172014-02-20 12:21:31 -08002006static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2007 char *crypto_blkdev, char *real_blkdev,
2008 int previously_encrypted_upto)
2009{
2010 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002011 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002012
Paul Lawrence73d7a022014-06-09 14:10:09 -07002013 if (!is_battery_ok_to_start()) {
2014 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002015 return 0;
2016 }
2017
2018 /* The size of the userdata partition, and add in the vold volumes below */
2019 tot_encryption_size = crypt_ftr->fs_size;
2020
2021 if (how == CRYPTO_ENABLE_WIPE) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07002022 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
JP Abgrall62c7af32014-06-16 13:01:23 -07002023 int fs_type = get_fs_type(rec);
2024 if (fs_type < 0) {
2025 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2026 return -1;
2027 }
2028 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002029 } else if (how == CRYPTO_ENABLE_INPLACE) {
2030 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2031 crypt_ftr->fs_size, &cur_encryption_done,
2032 tot_encryption_size,
2033 previously_encrypted_upto);
2034
JP Abgrall7fc1de82014-10-10 18:43:41 -07002035 if (rc == ENABLE_INPLACE_ERR_DEV) {
2036 /* Hack for b/17898962 */
2037 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
Josh Gaofec44372017-08-28 13:22:55 -07002038 cryptfs_reboot(RebootType::reboot);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002039 }
2040
Paul Lawrence73d7a022014-06-09 14:10:09 -07002041 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002042 crypt_ftr->encrypted_upto = cur_encryption_done;
2043 }
2044
Paul Lawrence73d7a022014-06-09 14:10:09 -07002045 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002046 /* The inplace routine never actually sets the progress to 100% due
2047 * to the round down nature of integer division, so set it here */
2048 property_set("vold.encrypt_progress", "100");
2049 }
2050 } else {
2051 /* Shouldn't happen */
2052 SLOGE("cryptfs_enable: internal error, unknown option\n");
2053 rc = -1;
2054 }
2055
2056 return rc;
2057}
2058
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002059int cryptfs_enable_internal(const char *howarg, int crypt_type, const char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002060 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002061{
2062 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002063 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002064 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002065 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002066 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002067 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002068 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002069 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002070 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002071 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002072 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002073 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002074 bool onlyCreateHeader = false;
2075 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002076
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002077 if (!strcmp(howarg, "wipe")) {
2078 how = CRYPTO_ENABLE_WIPE;
2079 } else if (! strcmp(howarg, "inplace")) {
2080 how = CRYPTO_ENABLE_INPLACE;
2081 } else {
2082 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002083 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002084 }
2085
Paul Lawrence87999172014-02-20 12:21:31 -08002086 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002087 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2088 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2089 /* An encryption was underway and was interrupted */
2090 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2091 crypt_ftr.encrypted_upto = 0;
2092 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002093
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002094 /* At this point, we are in an inconsistent state. Until we successfully
2095 complete encryption, a reboot will leave us broken. So mark the
2096 encryption failed in case that happens.
2097 On successfully completing encryption, remove this flag */
2098 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002099
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002100 put_crypt_ftr_and_key(&crypt_ftr);
2101 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2102 if (!check_ftr_sha(&crypt_ftr)) {
2103 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2104 put_crypt_ftr_and_key(&crypt_ftr);
2105 goto error_unencrypted;
2106 }
2107
2108 /* Doing a reboot-encryption*/
2109 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2110 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2111 rebootEncryption = true;
2112 }
Paul Lawrence87999172014-02-20 12:21:31 -08002113 }
2114
2115 property_get("ro.crypto.state", encrypted_state, "");
2116 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2117 SLOGE("Device is already running encrypted, aborting");
2118 goto error_unencrypted;
2119 }
2120
2121 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002122 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2123 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002124
Ken Sumrall3ed82362011-01-28 23:31:16 -08002125 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002126 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002127 if (fd == -1) {
2128 SLOGE("Cannot open block device %s\n", real_blkdev);
2129 goto error_unencrypted;
2130 }
2131 unsigned long nr_sec;
2132 get_blkdev_size(fd, &nr_sec);
2133 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002134 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2135 goto error_unencrypted;
2136 }
2137 close(fd);
2138
2139 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002140 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002141 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002142 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002143 if (fs_size_sec == 0)
2144 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2145
Paul Lawrence87999172014-02-20 12:21:31 -08002146 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002147
2148 if (fs_size_sec > max_fs_size_sec) {
2149 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2150 goto error_unencrypted;
2151 }
2152 }
2153
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002154 /* Get a wakelock as this may take a while, and we don't want the
2155 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2156 * wants to keep the screen on, it can grab a full wakelock.
2157 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002158 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002159 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2160
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002161 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002162 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002163 */
2164 property_set("vold.decrypt", "trigger_shutdown_framework");
2165 SLOGD("Just asked init to shut down class main\n");
2166
Jeff Sharkey9c484982015-03-31 10:35:33 -07002167 /* Ask vold to unmount all devices that it manages */
2168 if (vold_unmountAll()) {
2169 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002170 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002171
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002172 /* no_ui means we are being called from init, not settings.
2173 Now we always reboot from settings, so !no_ui means reboot
2174 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002175 if (!no_ui) {
2176 /* Try fallback, which is to reboot and try there */
2177 onlyCreateHeader = true;
2178 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2179 if (breadcrumb == 0) {
2180 SLOGE("Failed to create breadcrumb file");
2181 goto error_shutting_down;
2182 }
2183 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002184 }
2185
2186 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002187 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002188 /* Now that /data is unmounted, we need to mount a tmpfs
2189 * /data, set a property saying we're doing inplace encryption,
2190 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002191 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002192 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002193 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002194 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002195 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002196 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002197
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002198 /* restart the framework. */
2199 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002200 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002201
Ken Sumrall92736ef2012-10-17 20:57:14 -07002202 /* Ugh, shutting down the framework is not synchronous, so until it
2203 * can be fixed, this horrible hack will wait a moment for it all to
2204 * shut down before proceeding. Without it, some devices cannot
2205 * restart the graphics services.
2206 */
2207 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002208 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002209
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002210 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002211 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002212 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002213 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2214 goto error_shutting_down;
2215 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002216
Paul Lawrence87999172014-02-20 12:21:31 -08002217 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2218 crypt_ftr.fs_size = nr_sec
2219 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2220 } else {
2221 crypt_ftr.fs_size = nr_sec;
2222 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002223 /* At this point, we are in an inconsistent state. Until we successfully
2224 complete encryption, a reboot will leave us broken. So mark the
2225 encryption failed in case that happens.
2226 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002227 if (onlyCreateHeader) {
2228 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2229 } else {
2230 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2231 }
Paul Lawrence87999172014-02-20 12:21:31 -08002232 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002233 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002234
Paul Lawrence87999172014-02-20 12:21:31 -08002235 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002236 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2237 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002238 SLOGE("Cannot create encrypted master key\n");
2239 goto error_shutting_down;
2240 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002241
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002242 /* Replace scrypted intermediate key if we are preparing for a reboot */
2243 if (onlyCreateHeader) {
2244 unsigned char fake_master_key[KEY_LEN_BYTES];
2245 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2246 memset(fake_master_key, 0, sizeof(fake_master_key));
2247 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2248 encrypted_fake_master_key, &crypt_ftr);
2249 }
2250
Paul Lawrence87999172014-02-20 12:21:31 -08002251 /* Write the key to the end of the partition */
2252 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002253
Paul Lawrence87999172014-02-20 12:21:31 -08002254 /* If any persistent data has been remembered, save it.
2255 * If none, create a valid empty table and save that.
2256 */
2257 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002258 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002259 if (pdata) {
2260 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2261 persist_data = pdata;
2262 }
2263 }
2264 if (persist_data) {
2265 save_persistent_data();
2266 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002267 }
2268
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002269 if (onlyCreateHeader) {
2270 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002271 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002272 }
2273
2274 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002275 /* startup service classes main and late_start */
2276 property_set("vold.decrypt", "trigger_restart_min_framework");
2277 SLOGD("Just triggered restart_min_framework\n");
2278
2279 /* OK, the framework is restarted and will soon be showing a
2280 * progress bar. Time to setup an encrypted mapping, and
2281 * either write a new filesystem, or encrypt in place updating
2282 * the progress bar as we work.
2283 */
2284 }
2285
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002286 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002287 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002288 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002289
Paul Lawrence87999172014-02-20 12:21:31 -08002290 /* If we are continuing, check checksums match */
2291 rc = 0;
2292 if (previously_encrypted_upto) {
2293 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2294 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002295
Paul Lawrence87999172014-02-20 12:21:31 -08002296 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2297 sizeof(hash_first_block)) != 0) {
2298 SLOGE("Checksums do not match - trigger wipe");
2299 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002300 }
2301 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002302
Paul Lawrence87999172014-02-20 12:21:31 -08002303 if (!rc) {
2304 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2305 crypto_blkdev, real_blkdev,
2306 previously_encrypted_upto);
2307 }
2308
2309 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002310 if (!rc && how == CRYPTO_ENABLE_INPLACE
2311 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002312 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2313 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002314 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002315 SLOGE("Error calculating checksum for continuing encryption");
2316 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002317 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002318 }
2319
2320 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002321 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002322
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002323 if (! rc) {
2324 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002325 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002326
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002327 if (how == CRYPTO_ENABLE_INPLACE
2328 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002329 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2330 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002331 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002332 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002333
Paul Lawrence6bfed202014-07-28 12:47:22 -07002334 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002335
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002336 if (how == CRYPTO_ENABLE_WIPE
2337 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002338 char value[PROPERTY_VALUE_MAX];
2339 property_get("ro.crypto.state", value, "");
2340 if (!strcmp(value, "")) {
2341 /* default encryption - continue first boot sequence */
2342 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08002343 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002344 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002345 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2346 // Bring up cryptkeeper that will check the password and set it
2347 property_set("vold.decrypt", "trigger_shutdown_framework");
2348 sleep(2);
2349 property_set("vold.encrypt_progress", "");
2350 cryptfs_trigger_restart_min_framework();
2351 } else {
2352 cryptfs_check_passwd(DEFAULT_PASSWORD);
2353 cryptfs_restart_internal(1);
2354 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002355 return 0;
2356 } else {
2357 sleep(2); /* Give the UI a chance to show 100% progress */
Josh Gaofec44372017-08-28 13:22:55 -07002358 cryptfs_reboot(RebootType::reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002359 }
Paul Lawrence87999172014-02-20 12:21:31 -08002360 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002361 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002362 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002363 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002364 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002365 char value[PROPERTY_VALUE_MAX];
2366
Ken Sumrall319369a2012-06-27 16:30:18 -07002367 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002368 if (!strcmp(value, "1")) {
2369 /* wipe data if encryption failed */
2370 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002371 std::string err;
2372 const std::vector<std::string> options = {
2373 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2374 };
2375 if (!write_bootloader_message(options, &err)) {
2376 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002377 }
Josh Gaofec44372017-08-28 13:22:55 -07002378 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002379 } else {
2380 /* set property to trigger dialog */
2381 property_set("vold.encrypt_progress", "error_partially_encrypted");
2382 release_wake_lock(lockid);
2383 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002384 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002385 }
2386
Ken Sumrall3ed82362011-01-28 23:31:16 -08002387 /* hrm, the encrypt step claims success, but the reboot failed.
2388 * This should not happen.
2389 * Set the property and return. Hope the framework can deal with it.
2390 */
2391 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002392 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002393 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002394
2395error_unencrypted:
2396 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002397 if (lockid[0]) {
2398 release_wake_lock(lockid);
2399 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002400 return -1;
2401
2402error_shutting_down:
2403 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2404 * but the framework is stopped and not restarted to show the error, so it's up to
2405 * vold to restart the system.
2406 */
2407 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002408 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002409
2410 /* shouldn't get here */
2411 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002412 if (lockid[0]) {
2413 release_wake_lock(lockid);
2414 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002415 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002416}
2417
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002418int cryptfs_enable(const char *howarg, int type, const char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002419{
Paul Lawrence569649f2015-09-09 12:13:00 -07002420 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002421}
2422
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002423int cryptfs_enable_default(const char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002424{
2425 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07002426 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002427}
2428
2429int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002430{
Paul Crowley38132a12016-02-09 09:50:32 +00002431 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002432 SLOGE("cryptfs_changepw not valid for file encryption");
2433 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002434 }
2435
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002436 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002437 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002438
2439 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002440 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002441 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002442 return -1;
2443 }
2444
Paul Lawrencef4faa572014-01-29 13:31:03 -08002445 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2446 SLOGE("Invalid crypt_type %d", crypt_type);
2447 return -1;
2448 }
2449
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002450 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002451 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002452 SLOGE("Error getting crypt footer and key");
2453 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002454 }
2455
Paul Lawrencef4faa572014-01-29 13:31:03 -08002456 crypt_ftr.crypt_type = crypt_type;
2457
JP Abgrall933216c2015-02-11 13:44:32 -08002458 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002459 : newpw,
2460 crypt_ftr.salt,
2461 saved_master_key,
2462 crypt_ftr.master_key,
2463 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002464 if (rc) {
2465 SLOGE("Encrypt master key failed: %d", rc);
2466 return -1;
2467 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002468 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002469 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002470
2471 return 0;
2472}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002473
Rubin Xu85c01f92014-10-13 12:49:54 +01002474static unsigned int persist_get_max_entries(int encrypted) {
2475 struct crypt_mnt_ftr crypt_ftr;
2476 unsigned int dsize;
2477 unsigned int max_persistent_entries;
2478
2479 /* If encrypted, use the values from the crypt_ftr, otherwise
2480 * use the values for the current spec.
2481 */
2482 if (encrypted) {
2483 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2484 return -1;
2485 }
2486 dsize = crypt_ftr.persist_data_size;
2487 } else {
2488 dsize = CRYPT_PERSIST_DATA_SIZE;
2489 }
2490
2491 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2492 sizeof(struct crypt_persist_entry);
2493
2494 return max_persistent_entries;
2495}
2496
2497static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002498{
2499 unsigned int i;
2500
2501 if (persist_data == NULL) {
2502 return -1;
2503 }
2504 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2505 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2506 /* We found it! */
2507 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2508 return 0;
2509 }
2510 }
2511
2512 return -1;
2513}
2514
Rubin Xu85c01f92014-10-13 12:49:54 +01002515static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002516{
2517 unsigned int i;
2518 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002519 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002520
2521 if (persist_data == NULL) {
2522 return -1;
2523 }
2524
Rubin Xu85c01f92014-10-13 12:49:54 +01002525 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002526
2527 num = persist_data->persist_valid_entries;
2528
2529 for (i = 0; i < num; i++) {
2530 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2531 /* We found an existing entry, update it! */
2532 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2533 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2534 return 0;
2535 }
2536 }
2537
2538 /* We didn't find it, add it to the end, if there is room */
2539 if (persist_data->persist_valid_entries < max_persistent_entries) {
2540 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2541 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2542 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2543 persist_data->persist_valid_entries++;
2544 return 0;
2545 }
2546
2547 return -1;
2548}
2549
Rubin Xu85c01f92014-10-13 12:49:54 +01002550/**
2551 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2552 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2553 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002554int match_multi_entry(const char *key, const char *field, unsigned index) {
2555 std::string key_ = key;
2556 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002557
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002558 std::string parsed_field;
2559 unsigned parsed_index;
2560
2561 std::string::size_type split = key_.find_last_of('_');
2562 if (split == std::string::npos) {
2563 parsed_field = key_;
2564 parsed_index = 0;
2565 } else {
2566 parsed_field = key_.substr(0, split);
2567 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002568 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002569
2570 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002571}
2572
2573/*
2574 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2575 * remaining entries starting from index will be deleted.
2576 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2577 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2578 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2579 *
2580 */
2581static int persist_del_keys(const char *fieldname, unsigned index)
2582{
2583 unsigned int i;
2584 unsigned int j;
2585 unsigned int num;
2586
2587 if (persist_data == NULL) {
2588 return PERSIST_DEL_KEY_ERROR_OTHER;
2589 }
2590
2591 num = persist_data->persist_valid_entries;
2592
2593 j = 0; // points to the end of non-deleted entries.
2594 // Filter out to-be-deleted entries in place.
2595 for (i = 0; i < num; i++) {
2596 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2597 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2598 j++;
2599 }
2600 }
2601
2602 if (j < num) {
2603 persist_data->persist_valid_entries = j;
2604 // Zeroise the remaining entries
2605 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2606 return PERSIST_DEL_KEY_OK;
2607 } else {
2608 // Did not find an entry matching the given fieldname
2609 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2610 }
2611}
2612
2613static int persist_count_keys(const char *fieldname)
2614{
2615 unsigned int i;
2616 unsigned int count;
2617
2618 if (persist_data == NULL) {
2619 return -1;
2620 }
2621
2622 count = 0;
2623 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2624 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2625 count++;
2626 }
2627 }
2628
2629 return count;
2630}
2631
Ken Sumrall160b4d62013-04-22 12:15:39 -07002632/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002633int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002634{
Paul Crowley38132a12016-02-09 09:50:32 +00002635 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002636 SLOGE("Cannot get field when file encrypted");
2637 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002638 }
2639
Ken Sumrall160b4d62013-04-22 12:15:39 -07002640 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002641 /* CRYPTO_GETFIELD_OK is success,
2642 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2643 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2644 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002645 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002646 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2647 int i;
2648 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002649
2650 if (persist_data == NULL) {
2651 load_persistent_data();
2652 if (persist_data == NULL) {
2653 SLOGE("Getfield error, cannot load persistent data");
2654 goto out;
2655 }
2656 }
2657
Rubin Xu85c01f92014-10-13 12:49:54 +01002658 // Read value from persistent entries. If the original value is split into multiple entries,
2659 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002660 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002661 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2662 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2663 // value too small
2664 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2665 goto out;
2666 }
2667 rc = CRYPTO_GETFIELD_OK;
2668
2669 for (i = 1; /* break explicitly */; i++) {
2670 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2671 (int) sizeof(temp_field)) {
2672 // If the fieldname is very long, we stop as soon as it begins to overflow the
2673 // maximum field length. At this point we have in fact fully read out the original
2674 // value because cryptfs_setfield would not allow fields with longer names to be
2675 // written in the first place.
2676 break;
2677 }
2678 if (!persist_get_key(temp_field, temp_value)) {
2679 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2680 // value too small.
2681 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2682 goto out;
2683 }
2684 } else {
2685 // Exhaust all entries.
2686 break;
2687 }
2688 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002689 } else {
2690 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002691 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002692 }
2693
2694out:
2695 return rc;
2696}
2697
2698/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002699int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002700{
Paul Crowley38132a12016-02-09 09:50:32 +00002701 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002702 SLOGE("Cannot set field when file encrypted");
2703 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002704 }
2705
Ken Sumrall160b4d62013-04-22 12:15:39 -07002706 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002707 /* 0 is success, negative values are error */
2708 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002709 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002710 unsigned int field_id;
2711 char temp_field[PROPERTY_KEY_MAX];
2712 unsigned int num_entries;
2713 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002714
2715 if (persist_data == NULL) {
2716 load_persistent_data();
2717 if (persist_data == NULL) {
2718 SLOGE("Setfield error, cannot load persistent data");
2719 goto out;
2720 }
2721 }
2722
2723 property_get("ro.crypto.state", encrypted_state, "");
2724 if (!strcmp(encrypted_state, "encrypted") ) {
2725 encrypted = 1;
2726 }
2727
Rubin Xu85c01f92014-10-13 12:49:54 +01002728 // Compute the number of entries required to store value, each entry can store up to
2729 // (PROPERTY_VALUE_MAX - 1) chars
2730 if (strlen(value) == 0) {
2731 // Empty value also needs one entry to store.
2732 num_entries = 1;
2733 } else {
2734 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2735 }
2736
2737 max_keylen = strlen(fieldname);
2738 if (num_entries > 1) {
2739 // Need an extra "_%d" suffix.
2740 max_keylen += 1 + log10(num_entries);
2741 }
2742 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2743 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002744 goto out;
2745 }
2746
Rubin Xu85c01f92014-10-13 12:49:54 +01002747 // Make sure we have enough space to write the new value
2748 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2749 persist_get_max_entries(encrypted)) {
2750 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2751 goto out;
2752 }
2753
2754 // Now that we know persist_data has enough space for value, let's delete the old field first
2755 // to make up space.
2756 persist_del_keys(fieldname, 0);
2757
2758 if (persist_set_key(fieldname, value, encrypted)) {
2759 // fail to set key, should not happen as we have already checked the available space
2760 SLOGE("persist_set_key() error during setfield()");
2761 goto out;
2762 }
2763
2764 for (field_id = 1; field_id < num_entries; field_id++) {
2765 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
2766
2767 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2768 // fail to set key, should not happen as we have already checked the available space.
2769 SLOGE("persist_set_key() error during setfield()");
2770 goto out;
2771 }
2772 }
2773
Ken Sumrall160b4d62013-04-22 12:15:39 -07002774 /* If we are running encrypted, save the persistent data now */
2775 if (encrypted) {
2776 if (save_persistent_data()) {
2777 SLOGE("Setfield error, cannot save persistent data");
2778 goto out;
2779 }
2780 }
2781
Rubin Xu85c01f92014-10-13 12:49:54 +01002782 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002783
2784out:
2785 return rc;
2786}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002787
2788/* Checks userdata. Attempt to mount the volume if default-
2789 * encrypted.
2790 * On success trigger next init phase and return 0.
2791 * Currently do not handle failure - see TODO below.
2792 */
2793int cryptfs_mount_default_encrypted(void)
2794{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002795 int crypt_type = cryptfs_get_password_type();
2796 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2797 SLOGE("Bad crypt type - error");
2798 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2799 SLOGD("Password is not default - "
2800 "starting min framework to prompt");
2801 property_set("vold.decrypt", "trigger_restart_min_framework");
2802 return 0;
2803 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2804 SLOGD("Password is default - restarting filesystem");
2805 cryptfs_restart_internal(0);
2806 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002807 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002808 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002809 }
2810
Paul Lawrence6bfed202014-07-28 12:47:22 -07002811 /** Corrupt. Allow us to boot into framework, which will detect bad
2812 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002813 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002814 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002815 return 0;
2816}
2817
2818/* Returns type of the password, default, pattern, pin or password.
2819 */
2820int cryptfs_get_password_type(void)
2821{
Paul Crowley38132a12016-02-09 09:50:32 +00002822 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002823 SLOGE("cryptfs_get_password_type not valid for file encryption");
2824 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002825 }
2826
Paul Lawrencef4faa572014-01-29 13:31:03 -08002827 struct crypt_mnt_ftr crypt_ftr;
2828
2829 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2830 SLOGE("Error getting crypt footer and key\n");
2831 return -1;
2832 }
2833
Paul Lawrence6bfed202014-07-28 12:47:22 -07002834 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2835 return -1;
2836 }
2837
Paul Lawrencef4faa572014-01-29 13:31:03 -08002838 return crypt_ftr.crypt_type;
2839}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002840
Paul Lawrence05335c32015-03-05 09:46:23 -08002841const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002842{
Paul Crowley38132a12016-02-09 09:50:32 +00002843 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002844 SLOGE("cryptfs_get_password not valid for file encryption");
2845 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002846 }
2847
Paul Lawrence399317e2014-03-10 13:20:50 -07002848 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002849 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002850 if (now.tv_sec < password_expiry_time) {
2851 return password;
2852 } else {
2853 cryptfs_clear_password();
2854 return 0;
2855 }
2856}
2857
2858void cryptfs_clear_password()
2859{
2860 if (password) {
2861 size_t len = strlen(password);
2862 memset(password, 0, len);
2863 free(password);
2864 password = 0;
2865 password_expiry_time = 0;
2866 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002867}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002868
Paul Lawrence0c247462015-10-29 10:30:57 -07002869int cryptfs_isConvertibleToFBE()
2870{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002871 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002872 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2873}
2874
Paul Lawrence731a7a22015-04-28 22:14:15 +00002875int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
2876{
2877 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
2878 SLOGE("Failed to initialize crypt_ftr");
2879 return -1;
2880 }
2881
2882 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
2883 crypt_ftr->salt, crypt_ftr)) {
2884 SLOGE("Cannot create encrypted master key\n");
2885 return -1;
2886 }
2887
2888 //crypt_ftr->keysize = key_length / 8;
2889 return 0;
2890}
2891
2892int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
2893 unsigned char* master_key)
2894{
2895 int rc;
2896
Paul Lawrence731a7a22015-04-28 22:14:15 +00002897 unsigned char* intermediate_key = 0;
2898 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002899
2900 if (password == 0 || *password == 0) {
2901 password = DEFAULT_PASSWORD;
2902 }
2903
Paul Lawrence731a7a22015-04-28 22:14:15 +00002904 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
2905 &intermediate_key_size);
2906
Paul Lawrence300dae72016-03-11 11:02:52 -08002907 if (rc) {
2908 SLOGE("Can't calculate intermediate key");
2909 return rc;
2910 }
2911
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002912 int N = 1 << ftr->N_factor;
2913 int r = 1 << ftr->r_factor;
2914 int p = 1 << ftr->p_factor;
2915
2916 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
2917
2918 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
2919 ftr->salt, sizeof(ftr->salt), N, r, p,
2920 scrypted_intermediate_key,
2921 sizeof(scrypted_intermediate_key));
2922
2923 free(intermediate_key);
2924
2925 if (rc) {
Paul Lawrence300dae72016-03-11 11:02:52 -08002926 SLOGE("Can't scrypt intermediate key");
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002927 return rc;
2928 }
2929
2930 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
2931 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00002932}
2933
2934int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
2935 const unsigned char* master_key)
2936{
2937 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
2938 ftr);
2939}
Paul Lawrence6e410592016-05-24 14:20:38 -07002940
Eric Biggersb45caaf2017-02-02 14:52:12 -08002941void cryptfs_get_file_encryption_modes(const char **contents_mode_ret,
2942 const char **filenames_mode_ret)
Paul Lawrence6e410592016-05-24 14:20:38 -07002943{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002944 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Eric Biggersb45caaf2017-02-02 14:52:12 -08002945 fs_mgr_get_file_encryption_modes(rec, contents_mode_ret, filenames_mode_ret);
Paul Lawrence6e410592016-05-24 14:20:38 -07002946}