blob: 484a1077f9e8d8cd56b7709e91807f7f3c5b5e97 [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.h>
42#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070058#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000059#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000060#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080061#include "CheckBattery.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070062#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080063#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000064#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080065#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070066#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080067extern "C" {
68#include <crypto_scrypt.h>
69}
Mark Salyzyn3e971272014-01-21 13:27:04 -080070
Mark Salyzyn5eecc442014-02-12 14:16:14 -080071#define UNUSED __attribute__((unused))
72
Ken Sumrall8f869aa2010-12-03 03:47:09 -080073#define DM_CRYPT_BUF_SIZE 4096
74
Jason parks70a4b3f2011-01-28 10:10:47 -060075#define HASH_COUNT 2000
76#define KEY_LEN_BYTES 16
77#define IV_LEN_BYTES 16
78
Ken Sumrall29d8da82011-05-18 17:20:07 -070079#define KEY_IN_FOOTER "footer"
80
Paul Lawrence3bd36d52015-06-09 13:37:44 -070081#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080082
Paul Lawrence3d99eba2015-11-20 07:07:19 -080083#define CRYPTO_BLOCK_DEVICE "userdata"
84
85#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
86
Ken Sumrall29d8da82011-05-18 17:20:07 -070087#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070088#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070089
Ken Sumralle919efe2012-09-29 17:07:41 -070090#define TABLE_LOAD_RETRIES 10
91
Shawn Willden47ba10d2014-09-03 17:07:06 -060092#define RSA_KEY_SIZE 2048
93#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
94#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060095#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070096
Paul Lawrence8e3f4512014-09-08 10:11:17 -070097#define RETRY_MOUNT_ATTEMPTS 10
98#define RETRY_MOUNT_DELAY_SECONDS 1
99
Jason parks70a4b3f2011-01-28 10:10:47 -0600100static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700101static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600102static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700103static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800104
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700105/* Should we use keymaster? */
106static int keymaster_check_compatibility()
107{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000108 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700109}
110
111/* Create a new keymaster key and store it in this footer */
112static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
113{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800114 if (ftr->keymaster_blob_size) {
115 SLOGI("Already have key");
116 return 0;
117 }
118
Janis Danisevskis015ec302017-01-31 11:31:08 +0000119 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
120 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
121 &ftr->keymaster_blob_size);
122 if (rc) {
123 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
124 SLOGE("Keymaster key blob to large)");
125 ftr->keymaster_blob_size = 0;
126 }
127 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700128 return -1;
129 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000130 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700131}
132
Shawn Willdene17a9c42014-09-08 13:04:08 -0600133/* This signs the given object using the keymaster key. */
134static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600135 const unsigned char *object,
136 const size_t object_size,
137 unsigned char **signature,
138 size_t *signature_size)
139{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600140 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600141 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600142 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600143
Shawn Willdene17a9c42014-09-08 13:04:08 -0600144 // To sign a message with RSA, the message must satisfy two
145 // constraints:
146 //
147 // 1. The message, when interpreted as a big-endian numeric value, must
148 // be strictly less than the public modulus of the RSA key. Note
149 // that because the most significant bit of the public modulus is
150 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
151 // key), an n-bit message with most significant bit 0 always
152 // satisfies this requirement.
153 //
154 // 2. The message must have the same length in bits as the public
155 // modulus of the RSA key. This requirement isn't mathematically
156 // necessary, but is necessary to ensure consistency in
157 // implementations.
158 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600159 case KDF_SCRYPT_KEYMASTER:
160 // This ensures the most significant byte of the signed message
161 // is zero. We could have zero-padded to the left instead, but
162 // this approach is slightly more robust against changes in
163 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600164 // so) because we really should be using a proper deterministic
165 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800166 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600167 SLOGI("Signing safely-padded object");
168 break;
169 default:
170 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000171 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600172 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000173 return keymaster_sign_object_for_cryptfs_scrypt(ftr->keymaster_blob, ftr->keymaster_blob_size,
174 KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign, to_sign_size, signature, signature_size);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600175}
176
Paul Lawrence399317e2014-03-10 13:20:50 -0700177/* Store password when userdata is successfully decrypted and mounted.
178 * Cleared by cryptfs_clear_password
179 *
180 * To avoid a double prompt at boot, we need to store the CryptKeeper
181 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
182 * Since the entire framework is torn down and rebuilt after encryption,
183 * we have to use a daemon or similar to store the password. Since vold
184 * is secured against IPC except from system processes, it seems a reasonable
185 * place to store this.
186 *
187 * password should be cleared once it has been used.
188 *
189 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800190 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700191static char* password = 0;
192static int password_expiry_time = 0;
193static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800194
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800195extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800196
Paul Lawrence87999172014-02-20 12:21:31 -0800197enum RebootType {reboot, recovery, shutdown};
198static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700199{
Paul Lawrence87999172014-02-20 12:21:31 -0800200 switch(rt) {
201 case reboot:
202 property_set(ANDROID_RB_PROPERTY, "reboot");
203 break;
204
205 case recovery:
206 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
207 break;
208
209 case shutdown:
210 property_set(ANDROID_RB_PROPERTY, "shutdown");
211 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700212 }
Paul Lawrence87999172014-02-20 12:21:31 -0800213
Ken Sumralladfba362013-06-04 16:37:52 -0700214 sleep(20);
215
216 /* Shouldn't get here, reboot should happen before sleep times out */
217 return;
218}
219
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800220static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
221{
222 memset(io, 0, dataSize);
223 io->data_size = dataSize;
224 io->data_start = sizeof(struct dm_ioctl);
225 io->version[0] = 4;
226 io->version[1] = 0;
227 io->version[2] = 0;
228 io->flags = flags;
229 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100230 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800231 }
232}
233
Kenny Rootc4c70f12013-06-14 12:11:38 -0700234/**
235 * Gets the default device scrypt parameters for key derivation time tuning.
236 * The parameters should lead to about one second derivation time for the
237 * given device.
238 */
239static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700240 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000241 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700242
Paul Crowley63c18d32016-02-10 14:02:47 +0000243 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
244 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
245 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
246 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700247 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000248 ftr->N_factor = Nf;
249 ftr->r_factor = rf;
250 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700251}
252
Ken Sumrall3ed82362011-01-28 23:31:16 -0800253static unsigned int get_fs_size(char *dev)
254{
255 int fd, block_size;
256 struct ext4_super_block sb;
257 off64_t len;
258
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700259 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800260 SLOGE("Cannot open device to get filesystem size ");
261 return 0;
262 }
263
264 if (lseek64(fd, 1024, SEEK_SET) < 0) {
265 SLOGE("Cannot seek to superblock");
266 return 0;
267 }
268
269 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
270 SLOGE("Cannot read superblock");
271 return 0;
272 }
273
274 close(fd);
275
Daniel Rosenberge82df162014-08-15 22:19:23 +0000276 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
277 SLOGE("Not a valid ext4 superblock");
278 return 0;
279 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800280 block_size = 1024 << sb.s_log_block_size;
281 /* compute length in bytes */
282 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
283
284 /* return length in sectors */
285 return (unsigned int) (len / 512);
286}
287
Ken Sumrall160b4d62013-04-22 12:15:39 -0700288static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
289{
290 static int cached_data = 0;
291 static off64_t cached_off = 0;
292 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
293 int fd;
294 char key_loc[PROPERTY_VALUE_MAX];
295 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700296 int rc = -1;
297
298 if (!cached_data) {
299 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
300
301 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700302 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700303 SLOGE("Cannot open real block device %s\n", real_blkdev);
304 return -1;
305 }
306
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900307 unsigned long nr_sec = 0;
308 get_blkdev_size(fd, &nr_sec);
309 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700310 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
311 * encryption info footer and key, and plenty of bytes to spare for future
312 * growth.
313 */
314 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
315 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
316 cached_data = 1;
317 } else {
318 SLOGE("Cannot get size of block device %s\n", real_blkdev);
319 }
320 close(fd);
321 } else {
322 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
323 cached_off = 0;
324 cached_data = 1;
325 }
326 }
327
328 if (cached_data) {
329 if (metadata_fname) {
330 *metadata_fname = cached_metadata_fname;
331 }
332 if (off) {
333 *off = cached_off;
334 }
335 rc = 0;
336 }
337
338 return rc;
339}
340
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800341/* Set sha256 checksum in structure */
342static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
343{
344 SHA256_CTX c;
345 SHA256_Init(&c);
346 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
347 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
348 SHA256_Final(crypt_ftr->sha256, &c);
349}
350
Ken Sumralle8744072011-01-18 22:01:55 -0800351/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800352 * update the failed mount count but not change the key.
353 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700354static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800355{
356 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800357 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700358 /* starting_off is set to the SEEK_SET offset
359 * where the crypto structure starts
360 */
361 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800362 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700363 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700364 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800365
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800366 set_ftr_sha(crypt_ftr);
367
Ken Sumrall160b4d62013-04-22 12:15:39 -0700368 if (get_crypt_ftr_info(&fname, &starting_off)) {
369 SLOGE("Unable to get crypt_ftr_info\n");
370 return -1;
371 }
372 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700373 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700374 return -1;
375 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700376 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700377 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378 return -1;
379 }
380
381 /* Seek to the start of the crypt footer */
382 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
383 SLOGE("Cannot seek to real block device footer\n");
384 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800385 }
386
387 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
388 SLOGE("Cannot write real block device footer\n");
389 goto errout;
390 }
391
Ken Sumrall3be890f2011-09-14 16:53:46 -0700392 fstat(fd, &statbuf);
393 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700394 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700395 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800396 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800397 goto errout;
398 }
399 }
400
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800401 /* Success! */
402 rc = 0;
403
404errout:
405 close(fd);
406 return rc;
407
408}
409
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800410static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
411{
412 struct crypt_mnt_ftr copy;
413 memcpy(&copy, crypt_ftr, sizeof(copy));
414 set_ftr_sha(&copy);
415 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
416}
417
Ken Sumrall160b4d62013-04-22 12:15:39 -0700418static inline int unix_read(int fd, void* buff, int len)
419{
420 return TEMP_FAILURE_RETRY(read(fd, buff, len));
421}
422
423static inline int unix_write(int fd, const void* buff, int len)
424{
425 return TEMP_FAILURE_RETRY(write(fd, buff, len));
426}
427
428static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
429{
430 memset(pdata, 0, len);
431 pdata->persist_magic = PERSIST_DATA_MAGIC;
432 pdata->persist_valid_entries = 0;
433}
434
435/* A routine to update the passed in crypt_ftr to the lastest version.
436 * fd is open read/write on the device that holds the crypto footer and persistent
437 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
438 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
439 */
440static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
441{
Kenny Root7434b312013-06-14 11:29:53 -0700442 int orig_major = crypt_ftr->major_version;
443 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700444
Kenny Root7434b312013-06-14 11:29:53 -0700445 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
446 struct crypt_persist_data *pdata;
447 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700448
Kenny Rootc4c70f12013-06-14 12:11:38 -0700449 SLOGW("upgrading crypto footer to 1.1");
450
Wei Wang4375f1b2017-02-24 17:43:01 -0800451 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700452 if (pdata == NULL) {
453 SLOGE("Cannot allocate persisent data\n");
454 return;
455 }
456 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
457
458 /* Need to initialize the persistent data area */
459 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
460 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100461 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700462 return;
463 }
464 /* Write all zeros to the first copy, making it invalid */
465 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
466
467 /* Write a valid but empty structure to the second copy */
468 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
469 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
470
471 /* Update the footer */
472 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
473 crypt_ftr->persist_data_offset[0] = pdata_offset;
474 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
475 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100476 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700477 }
478
Paul Lawrencef4faa572014-01-29 13:31:03 -0800479 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700480 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800481 /* But keep the old kdf_type.
482 * It will get updated later to KDF_SCRYPT after the password has been verified.
483 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700484 crypt_ftr->kdf_type = KDF_PBKDF2;
485 get_device_scrypt_params(crypt_ftr);
486 crypt_ftr->minor_version = 2;
487 }
488
Paul Lawrencef4faa572014-01-29 13:31:03 -0800489 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
490 SLOGW("upgrading crypto footer to 1.3");
491 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
492 crypt_ftr->minor_version = 3;
493 }
494
Kenny Root7434b312013-06-14 11:29:53 -0700495 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
496 if (lseek64(fd, offset, SEEK_SET) == -1) {
497 SLOGE("Cannot seek to crypt footer\n");
498 return;
499 }
500 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700501 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700502}
503
504
505static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800506{
507 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800508 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700509 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800510 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700511 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700512 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800513
Ken Sumrall160b4d62013-04-22 12:15:39 -0700514 if (get_crypt_ftr_info(&fname, &starting_off)) {
515 SLOGE("Unable to get crypt_ftr_info\n");
516 return -1;
517 }
518 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700519 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700520 return -1;
521 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700522 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700523 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700524 return -1;
525 }
526
527 /* Make sure it's 16 Kbytes in length */
528 fstat(fd, &statbuf);
529 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
530 SLOGE("footer file %s is not the expected size!\n", fname);
531 goto errout;
532 }
533
534 /* Seek to the start of the crypt footer */
535 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
536 SLOGE("Cannot seek to real block device footer\n");
537 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800538 }
539
540 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
541 SLOGE("Cannot read real block device footer\n");
542 goto errout;
543 }
544
545 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700546 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800547 goto errout;
548 }
549
Kenny Rootc96a5f82013-06-14 12:08:28 -0700550 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
551 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
552 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800553 goto errout;
554 }
555
Kenny Rootc96a5f82013-06-14 12:08:28 -0700556 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
557 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
558 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800559 }
560
Ken Sumrall160b4d62013-04-22 12:15:39 -0700561 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
562 * copy on disk before returning.
563 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700564 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700565 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800566 }
567
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800568 /* Success! */
569 rc = 0;
570
571errout:
572 close(fd);
573 return rc;
574}
575
Ken Sumrall160b4d62013-04-22 12:15:39 -0700576static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
577{
578 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
579 crypt_ftr->persist_data_offset[1]) {
580 SLOGE("Crypt_ftr persist data regions overlap");
581 return -1;
582 }
583
584 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
585 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
586 return -1;
587 }
588
589 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
590 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
591 CRYPT_FOOTER_OFFSET) {
592 SLOGE("Persistent data extends past crypto footer");
593 return -1;
594 }
595
596 return 0;
597}
598
599static int load_persistent_data(void)
600{
601 struct crypt_mnt_ftr crypt_ftr;
602 struct crypt_persist_data *pdata = NULL;
603 char encrypted_state[PROPERTY_VALUE_MAX];
604 char *fname;
605 int found = 0;
606 int fd;
607 int ret;
608 int i;
609
610 if (persist_data) {
611 /* Nothing to do, we've already loaded or initialized it */
612 return 0;
613 }
614
615
616 /* If not encrypted, just allocate an empty table and initialize it */
617 property_get("ro.crypto.state", encrypted_state, "");
618 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800619 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620 if (pdata) {
621 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
622 persist_data = pdata;
623 return 0;
624 }
625 return -1;
626 }
627
628 if(get_crypt_ftr_and_key(&crypt_ftr)) {
629 return -1;
630 }
631
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700632 if ((crypt_ftr.major_version < 1)
633 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700634 SLOGE("Crypt_ftr version doesn't support persistent data");
635 return -1;
636 }
637
638 if (get_crypt_ftr_info(&fname, NULL)) {
639 return -1;
640 }
641
642 ret = validate_persistent_data_storage(&crypt_ftr);
643 if (ret) {
644 return -1;
645 }
646
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700647 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700648 if (fd < 0) {
649 SLOGE("Cannot open %s metadata file", fname);
650 return -1;
651 }
652
Wei Wang4375f1b2017-02-24 17:43:01 -0800653 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800654 if (pdata == NULL) {
655 SLOGE("Cannot allocate memory for persistent data");
656 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700657 }
658
659 for (i = 0; i < 2; i++) {
660 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
661 SLOGE("Cannot seek to read persistent data on %s", fname);
662 goto err2;
663 }
664 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
665 SLOGE("Error reading persistent data on iteration %d", i);
666 goto err2;
667 }
668 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
669 found = 1;
670 break;
671 }
672 }
673
674 if (!found) {
675 SLOGI("Could not find valid persistent data, creating");
676 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
677 }
678
679 /* Success */
680 persist_data = pdata;
681 close(fd);
682 return 0;
683
684err2:
685 free(pdata);
686
687err:
688 close(fd);
689 return -1;
690}
691
692static int save_persistent_data(void)
693{
694 struct crypt_mnt_ftr crypt_ftr;
695 struct crypt_persist_data *pdata;
696 char *fname;
697 off64_t write_offset;
698 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700699 int fd;
700 int ret;
701
702 if (persist_data == NULL) {
703 SLOGE("No persistent data to save");
704 return -1;
705 }
706
707 if(get_crypt_ftr_and_key(&crypt_ftr)) {
708 return -1;
709 }
710
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700711 if ((crypt_ftr.major_version < 1)
712 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700713 SLOGE("Crypt_ftr version doesn't support persistent data");
714 return -1;
715 }
716
717 ret = validate_persistent_data_storage(&crypt_ftr);
718 if (ret) {
719 return -1;
720 }
721
722 if (get_crypt_ftr_info(&fname, NULL)) {
723 return -1;
724 }
725
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700726 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700727 if (fd < 0) {
728 SLOGE("Cannot open %s metadata file", fname);
729 return -1;
730 }
731
Wei Wang4375f1b2017-02-24 17:43:01 -0800732 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700733 if (pdata == NULL) {
734 SLOGE("Cannot allocate persistant data");
735 goto err;
736 }
737
738 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
739 SLOGE("Cannot seek to read persistent data on %s", fname);
740 goto err2;
741 }
742
743 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
744 SLOGE("Error reading persistent data before save");
745 goto err2;
746 }
747
748 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
749 /* The first copy is the curent valid copy, so write to
750 * the second copy and erase this one */
751 write_offset = crypt_ftr.persist_data_offset[1];
752 erase_offset = crypt_ftr.persist_data_offset[0];
753 } else {
754 /* The second copy must be the valid copy, so write to
755 * the first copy, and erase the second */
756 write_offset = crypt_ftr.persist_data_offset[0];
757 erase_offset = crypt_ftr.persist_data_offset[1];
758 }
759
760 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100761 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700762 SLOGE("Cannot seek to write persistent data");
763 goto err2;
764 }
765 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
766 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100767 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700768 SLOGE("Cannot seek to erase previous persistent data");
769 goto err2;
770 }
771 fsync(fd);
772 memset(pdata, 0, crypt_ftr.persist_data_size);
773 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
774 (int) crypt_ftr.persist_data_size) {
775 SLOGE("Cannot write to erase previous persistent data");
776 goto err2;
777 }
778 fsync(fd);
779 } else {
780 SLOGE("Cannot write to save persistent data");
781 goto err2;
782 }
783
784 /* Success */
785 free(pdata);
786 close(fd);
787 return 0;
788
789err2:
790 free(pdata);
791err:
792 close(fd);
793 return -1;
794}
795
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800796/* Convert a binary key of specified length into an ascii hex string equivalent,
797 * without the leading 0x and with null termination
798 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700799static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700800 unsigned int keysize, char *master_key_ascii) {
801 unsigned int i, a;
802 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800803
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700804 for (i=0, a=0; i<keysize; i++, a+=2) {
805 /* For each byte, write out two ascii hex digits */
806 nibble = (master_key[i] >> 4) & 0xf;
807 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800808
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700809 nibble = master_key[i] & 0xf;
810 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
811 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800812
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700813 /* Add the null termination */
814 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800815
816}
817
Jeff Sharkey9c484982015-03-31 10:35:33 -0700818static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
819 const unsigned char *master_key, const char *real_blk_name,
820 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800821 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800822 struct dm_ioctl *io;
823 struct dm_target_spec *tgt;
824 char *crypt_params;
825 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800826 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800827 int i;
828
829 io = (struct dm_ioctl *) buffer;
830
831 /* Load the mapping table for this device */
832 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
833
834 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
835 io->target_count = 1;
836 tgt->status = 0;
837 tgt->sector_start = 0;
838 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700839 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800840
841 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
842 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800843
844 buff_offset = crypt_params - buffer;
845 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
846 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
847 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800848 crypt_params += strlen(crypt_params) + 1;
849 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
850 tgt->next = crypt_params - buffer;
851
852 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
853 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
854 break;
855 }
856 usleep(500000);
857 }
858
859 if (i == TABLE_LOAD_RETRIES) {
860 /* We failed to load the table, return an error */
861 return -1;
862 } else {
863 return i + 1;
864 }
865}
866
867
868static int get_dm_crypt_version(int fd, const char *name, int *version)
869{
870 char buffer[DM_CRYPT_BUF_SIZE];
871 struct dm_ioctl *io;
872 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800873
874 io = (struct dm_ioctl *) buffer;
875
876 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
877
878 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
879 return -1;
880 }
881
882 /* Iterate over the returned versions, looking for name of "crypt".
883 * When found, get and return the version.
884 */
885 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
886 while (v->next) {
887 if (! strcmp(v->name, "crypt")) {
888 /* We found the crypt driver, return the version, and get out */
889 version[0] = v->version[0];
890 version[1] = v->version[1];
891 version[2] = v->version[2];
892 return 0;
893 }
894 v = (struct dm_target_versions *)(((char *)v) + v->next);
895 }
896
897 return -1;
898}
899
Jeff Sharkey9c484982015-03-31 10:35:33 -0700900static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
901 const unsigned char *master_key, const char *real_blk_name,
902 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800903 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800904 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800905 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -0700906 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800907 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800908 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800909 int version[3];
Wei Wang4375f1b2017-02-24 17:43:01 -0800910 const char *extra_params;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800911 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800912
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700913 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800914 SLOGE("Cannot open device-mapper\n");
915 goto errout;
916 }
917
918 io = (struct dm_ioctl *) buffer;
919
920 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800921 err = ioctl(fd, DM_DEV_CREATE, io);
922 if (err) {
923 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800924 goto errout;
925 }
926
927 /* Get the device status, in particular, the name of it's device file */
928 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
929 if (ioctl(fd, DM_DEV_STATUS, io)) {
930 SLOGE("Cannot retrieve dm-crypt device status\n");
931 goto errout;
932 }
933 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
934 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
935
Ken Sumralldb5e0262013-02-05 17:39:48 -0800936 extra_params = "";
937 if (! get_dm_crypt_version(fd, name, version)) {
938 /* Support for allow_discards was added in version 1.11.0 */
939 if ((version[0] >= 2) ||
940 ((version[0] == 1) && (version[1] >= 11))) {
941 extra_params = "1 allow_discards";
942 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
943 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700944 }
945
Ken Sumralldb5e0262013-02-05 17:39:48 -0800946 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
947 fd, extra_params);
948 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800949 SLOGE("Cannot load dm-crypt mapping table.\n");
950 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800951 } else if (load_count > 1) {
952 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800953 }
954
955 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800956 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800957
958 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
959 SLOGE("Cannot resume the dm-crypt device\n");
960 goto errout;
961 }
962
963 /* We made it here with no errors. Woot! */
964 retval = 0;
965
966errout:
967 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
968
969 return retval;
970}
971
Wei Wang4375f1b2017-02-24 17:43:01 -0800972static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800973{
974 int fd;
975 char buffer[DM_CRYPT_BUF_SIZE];
976 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800977 int retval = -1;
978
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700979 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800980 SLOGE("Cannot open device-mapper\n");
981 goto errout;
982 }
983
984 io = (struct dm_ioctl *) buffer;
985
986 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
987 if (ioctl(fd, DM_DEV_REMOVE, io)) {
988 SLOGE("Cannot remove dm-crypt device\n");
989 goto errout;
990 }
991
992 /* We made it here with no errors. Woot! */
993 retval = 0;
994
995errout:
996 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
997
998 return retval;
999
1000}
1001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001002static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001003 unsigned char *ikey, void *params UNUSED)
1004{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001005 SLOGI("Using pbkdf2 for cryptfs KDF");
1006
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001007 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001008 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1009 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1010 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001011}
1012
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001013static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001014 unsigned char *ikey, void *params)
1015{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001016 SLOGI("Using scrypt for cryptfs KDF");
1017
Kenny Rootc4c70f12013-06-14 12:11:38 -07001018 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1019
1020 int N = 1 << ftr->N_factor;
1021 int r = 1 << ftr->r_factor;
1022 int p = 1 << ftr->p_factor;
1023
1024 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001025 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001026 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1027 salt, SALT_LEN, N, r, p, ikey,
1028 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001029
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001030 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001031}
1032
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001033static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1034 unsigned char *ikey, void *params)
1035{
1036 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1037
1038 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001039 size_t signature_size;
1040 unsigned char* signature;
1041 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1042
1043 int N = 1 << ftr->N_factor;
1044 int r = 1 << ftr->r_factor;
1045 int p = 1 << ftr->p_factor;
1046
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001047 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1048 salt, SALT_LEN, N, r, p, ikey,
1049 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001050
1051 if (rc) {
1052 SLOGE("scrypt failed");
1053 return -1;
1054 }
1055
Shawn Willdene17a9c42014-09-08 13:04:08 -06001056 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1057 &signature, &signature_size)) {
1058 SLOGE("Signing failed");
1059 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001060 }
1061
1062 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1063 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1064 free(signature);
1065
1066 if (rc) {
1067 SLOGE("scrypt failed");
1068 return -1;
1069 }
1070
1071 return 0;
1072}
1073
1074static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1075 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001076 unsigned char *encrypted_master_key,
1077 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001078{
1079 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1080 EVP_CIPHER_CTX e_ctx;
1081 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001082 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001083
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001084 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001085 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001086
1087 switch (crypt_ftr->kdf_type) {
1088 case KDF_SCRYPT_KEYMASTER:
1089 if (keymaster_create_key(crypt_ftr)) {
1090 SLOGE("keymaster_create_key failed");
1091 return -1;
1092 }
1093
1094 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1095 SLOGE("scrypt failed");
1096 return -1;
1097 }
1098 break;
1099
1100 case KDF_SCRYPT:
1101 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1102 SLOGE("scrypt failed");
1103 return -1;
1104 }
1105 break;
1106
1107 default:
1108 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001109 return -1;
1110 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001111
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001112 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001113 EVP_CIPHER_CTX_init(&e_ctx);
1114 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001115 SLOGE("EVP_EncryptInit failed\n");
1116 return -1;
1117 }
1118 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001119
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001120 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001121 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001122 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001123 SLOGE("EVP_EncryptUpdate failed\n");
1124 return -1;
1125 }
Adam Langley889c4f12014-09-03 14:23:13 -07001126 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001127 SLOGE("EVP_EncryptFinal failed\n");
1128 return -1;
1129 }
1130
1131 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1132 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1133 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001134 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001135
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001136 /* Store the scrypt of the intermediate key, so we can validate if it's a
1137 password error or mount error when things go wrong.
1138 Note there's no need to check for errors, since if this is incorrect, we
1139 simply won't wipe userdata, which is the correct default behavior
1140 */
1141 int N = 1 << crypt_ftr->N_factor;
1142 int r = 1 << crypt_ftr->r_factor;
1143 int p = 1 << crypt_ftr->p_factor;
1144
1145 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1146 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1147 crypt_ftr->scrypted_intermediate_key,
1148 sizeof(crypt_ftr->scrypted_intermediate_key));
1149
1150 if (rc) {
1151 SLOGE("encrypt_master_key: crypto_scrypt failed");
1152 }
1153
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001154 EVP_CIPHER_CTX_cleanup(&e_ctx);
1155
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001156 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157}
1158
Paul Lawrence731a7a22015-04-28 22:14:15 +00001159static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001160 unsigned char *encrypted_master_key,
1161 unsigned char *decrypted_master_key,
1162 kdf_func kdf, void *kdf_params,
1163 unsigned char** intermediate_key,
1164 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165{
1166 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 -08001167 EVP_CIPHER_CTX d_ctx;
1168 int decrypted_len, final_len;
1169
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001170 /* Turn the password into an intermediate key and IV that can decrypt the
1171 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001172 if (kdf(passwd, salt, ikey, kdf_params)) {
1173 SLOGE("kdf failed");
1174 return -1;
1175 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001176
1177 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001178 EVP_CIPHER_CTX_init(&d_ctx);
1179 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001180 return -1;
1181 }
1182 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1183 /* Decrypt the master key */
1184 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1185 encrypted_master_key, KEY_LEN_BYTES)) {
1186 return -1;
1187 }
Adam Langley889c4f12014-09-03 14:23:13 -07001188 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001189 return -1;
1190 }
1191
1192 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1193 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001194 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001195
1196 /* Copy intermediate key if needed by params */
1197 if (intermediate_key && intermediate_key_size) {
1198 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001199 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001200 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1201 *intermediate_key_size = KEY_LEN_BYTES;
1202 }
1203 }
1204
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001205 EVP_CIPHER_CTX_cleanup(&d_ctx);
1206
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001207 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001208}
1209
Kenny Rootc4c70f12013-06-14 12:11:38 -07001210static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001211{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001212 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001213 *kdf = scrypt_keymaster;
1214 *kdf_params = ftr;
1215 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001216 *kdf = scrypt;
1217 *kdf_params = ftr;
1218 } else {
1219 *kdf = pbkdf2;
1220 *kdf_params = NULL;
1221 }
1222}
1223
Paul Lawrence731a7a22015-04-28 22:14:15 +00001224static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001225 struct crypt_mnt_ftr *crypt_ftr,
1226 unsigned char** intermediate_key,
1227 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001228{
1229 kdf_func kdf;
1230 void *kdf_params;
1231 int ret;
1232
1233 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001234 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1235 decrypted_master_key, kdf, kdf_params,
1236 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001237 if (ret != 0) {
1238 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001239 }
1240
1241 return ret;
1242}
1243
Wei Wang4375f1b2017-02-24 17:43:01 -08001244static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001245 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001246 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001247 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001248
1249 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001250 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001251 read(fd, key_buf, sizeof(key_buf));
1252 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001253 close(fd);
1254
1255 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001256 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001257}
1258
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001259int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260{
Greg Hackmann955653e2014-09-24 14:55:20 -07001261 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001262#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001263
1264 /* Now umount the tmpfs filesystem */
1265 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001266 if (umount(mountpoint) == 0) {
1267 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001268 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001269
1270 if (errno == EINVAL) {
1271 /* EINVAL is returned if the directory is not a mountpoint,
1272 * i.e. there is no filesystem mounted there. So just get out.
1273 */
1274 break;
1275 }
1276
1277 err = errno;
1278
1279 /* If allowed, be increasingly aggressive before the last two retries */
1280 if (kill) {
1281 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1282 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001283 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001284 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1285 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001286 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001287 }
1288 }
1289
1290 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001291 }
1292
1293 if (i < WAIT_UNMOUNT_COUNT) {
1294 SLOGD("unmounting %s succeeded\n", mountpoint);
1295 rc = 0;
1296 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001297 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001298 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001299 rc = -1;
1300 }
1301
1302 return rc;
1303}
1304
Wei Wang42e38102017-06-07 10:46:12 -07001305static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001306{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001307 // NOTE: post_fs_data results in init calling back around to vold, so all
1308 // callers to this method must be async
1309
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001310 /* Do the prep of the /data filesystem */
1311 property_set("vold.post_fs_data_done", "0");
1312 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001313 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001314
Ken Sumrallc5872692013-05-14 15:26:31 -07001315 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001316 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001317 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001318 std::chrono::seconds(15))) {
1319 /* We timed out to prep /data in time. Continue wait. */
1320 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001321 }
Wei Wang42e38102017-06-07 10:46:12 -07001322 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001323}
1324
Paul Lawrence74f29f12014-08-28 15:54:10 -07001325static void cryptfs_set_corrupt()
1326{
1327 // Mark the footer as bad
1328 struct crypt_mnt_ftr crypt_ftr;
1329 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1330 SLOGE("Failed to get crypto footer - panic");
1331 return;
1332 }
1333
1334 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1335 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1336 SLOGE("Failed to set crypto footer - panic");
1337 return;
1338 }
1339}
1340
1341static void cryptfs_trigger_restart_min_framework()
1342{
1343 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1344 SLOGE("Failed to mount tmpfs on data - panic");
1345 return;
1346 }
1347
1348 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1349 SLOGE("Failed to trigger post fs data - panic");
1350 return;
1351 }
1352
1353 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1354 SLOGE("Failed to trigger restart min framework - panic");
1355 return;
1356 }
1357}
1358
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001359/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001360static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001361{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001362 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001363 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001364 static int restart_successful = 0;
1365
1366 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001367 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001368 SLOGE("Encrypted filesystem not validated, aborting");
1369 return -1;
1370 }
1371
1372 if (restart_successful) {
1373 SLOGE("System already restarted with encrypted disk, aborting");
1374 return -1;
1375 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001376
Paul Lawrencef4faa572014-01-29 13:31:03 -08001377 if (restart_main) {
1378 /* Here is where we shut down the framework. The init scripts
1379 * start all services in one of three classes: core, main or late_start.
1380 * On boot, we start core and main. Now, we stop main, but not core,
1381 * as core includes vold and a few other really important things that
1382 * we need to keep running. Once main has stopped, we should be able
1383 * to umount the tmpfs /data, then mount the encrypted /data.
1384 * We then restart the class main, and also the class late_start.
1385 * At the moment, I've only put a few things in late_start that I know
1386 * are not needed to bring up the framework, and that also cause problems
1387 * with unmounting the tmpfs /data, but I hope to add add more services
1388 * to the late_start class as we optimize this to decrease the delay
1389 * till the user is asked for the password to the filesystem.
1390 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391
Paul Lawrencef4faa572014-01-29 13:31:03 -08001392 /* The init files are setup to stop the class main when vold.decrypt is
1393 * set to trigger_reset_main.
1394 */
1395 property_set("vold.decrypt", "trigger_reset_main");
1396 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001397
Paul Lawrencef4faa572014-01-29 13:31:03 -08001398 /* Ugh, shutting down the framework is not synchronous, so until it
1399 * can be fixed, this horrible hack will wait a moment for it all to
1400 * shut down before proceeding. Without it, some devices cannot
1401 * restart the graphics services.
1402 */
1403 sleep(2);
1404 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001405
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001406 /* Now that the framework is shutdown, we should be able to umount()
1407 * the tmpfs filesystem, and mount the real one.
1408 */
1409
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001410 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1411 if (strlen(crypto_blkdev) == 0) {
1412 SLOGE("fs_crypto_blkdev not set\n");
1413 return -1;
1414 }
1415
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001416 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001417 /* If ro.crypto.readonly is set to 1, mount the decrypted
1418 * filesystem readonly. This is used when /data is mounted by
1419 * recovery mode.
1420 */
1421 char ro_prop[PROPERTY_VALUE_MAX];
1422 property_get("ro.crypto.readonly", ro_prop, "");
1423 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1424 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1425 rec->flags |= MS_RDONLY;
1426 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001427
Ken Sumralle5032c42012-04-01 23:58:44 -07001428 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001429 int retries = RETRY_MOUNT_ATTEMPTS;
1430 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001431
1432 /*
1433 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1434 * partitions in the fsck domain.
1435 */
1436 if (setexeccon(secontextFsck())){
1437 SLOGE("Failed to setexeccon");
1438 return -1;
1439 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001440 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1441 crypto_blkdev, 0))
1442 != 0) {
1443 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1444 /* TODO: invoke something similar to
1445 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1446 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1447 SLOGI("Failed to mount %s because it is busy - waiting",
1448 crypto_blkdev);
1449 if (--retries) {
1450 sleep(RETRY_MOUNT_DELAY_SECONDS);
1451 } else {
1452 /* Let's hope that a reboot clears away whatever is keeping
1453 the mount busy */
1454 cryptfs_reboot(reboot);
1455 }
1456 } else {
1457 SLOGE("Failed to mount decrypted data");
1458 cryptfs_set_corrupt();
1459 cryptfs_trigger_restart_min_framework();
1460 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001461 if (setexeccon(NULL)) {
1462 SLOGE("Failed to setexeccon");
1463 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001464 return -1;
1465 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001466 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001467 if (setexeccon(NULL)) {
1468 SLOGE("Failed to setexeccon");
1469 return -1;
1470 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001471
Ken Sumralle5032c42012-04-01 23:58:44 -07001472 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001473 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001474 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001475
1476 /* startup service classes main and late_start */
1477 property_set("vold.decrypt", "trigger_restart_framework");
1478 SLOGD("Just triggered restart_framework\n");
1479
1480 /* Give it a few moments to get started */
1481 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001482 }
1483
Ken Sumrall0cc16632011-01-18 20:32:26 -08001484 if (rc == 0) {
1485 restart_successful = 1;
1486 }
1487
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001488 return rc;
1489}
1490
Paul Lawrencef4faa572014-01-29 13:31:03 -08001491int cryptfs_restart(void)
1492{
Paul Lawrence05335c32015-03-05 09:46:23 -08001493 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001494 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001495 SLOGE("cryptfs_restart not valid for file encryption:");
1496 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001497 }
1498
Paul Lawrencef4faa572014-01-29 13:31:03 -08001499 /* Call internal implementation forcing a restart of main service group */
1500 return cryptfs_restart_internal(1);
1501}
1502
Wei Wang4375f1b2017-02-24 17:43:01 -08001503static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001504{
1505 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001506 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001507 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001508
1509 property_get("ro.crypto.state", encrypted_state, "");
1510 if (strcmp(encrypted_state, "encrypted") ) {
1511 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001512 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001513 }
1514
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001515 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001516 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001517 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001518 }
1519
Ken Sumrall160b4d62013-04-22 12:15:39 -07001520 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001521 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001522
Ken Sumralle1a45852011-12-14 21:24:27 -08001523 /*
1524 * Only report this error if key_loc is a file and it exists.
1525 * If the device was never encrypted, and /data is not mountable for
1526 * some reason, returning 1 should prevent the UI from presenting the
1527 * a "enter password" screen, or worse, a "press button to wipe the
1528 * device" screen.
1529 */
1530 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1531 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001532 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001533 } else {
1534 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001535 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001536 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001537 }
1538
Paul Lawrence74f29f12014-08-28 15:54:10 -07001539 // Test for possible error flags
1540 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1541 SLOGE("Encryption process is partway completed\n");
1542 return CRYPTO_COMPLETE_PARTIAL;
1543 }
1544
1545 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1546 SLOGE("Encryption process was interrupted but cannot continue\n");
1547 return CRYPTO_COMPLETE_INCONSISTENT;
1548 }
1549
1550 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1551 SLOGE("Encryption is successful but data is corrupt\n");
1552 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001553 }
1554
1555 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001556 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001557}
1558
Paul Lawrencef4faa572014-01-29 13:31:03 -08001559static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001560 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001561{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001562 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001563 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001564 char crypto_blkdev[MAXPATHLEN];
1565 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001566 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001567 unsigned int orig_failed_decrypt_count;
1568 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001569 int use_keymaster = 0;
1570 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001571 unsigned char* intermediate_key = 0;
1572 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001573 int N = 1 << crypt_ftr->N_factor;
1574 int r = 1 << crypt_ftr->r_factor;
1575 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001576
Paul Lawrencef4faa572014-01-29 13:31:03 -08001577 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1578 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001579
Paul Lawrencef4faa572014-01-29 13:31:03 -08001580 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001581 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1582 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001583 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001584 rc = -1;
1585 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001586 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001587 }
1588
Paul Lawrencef4faa572014-01-29 13:31:03 -08001589 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1590
Paul Lawrence74f29f12014-08-28 15:54:10 -07001591 // Create crypto block device - all (non fatal) code paths
1592 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001593 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1594 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001595 SLOGE("Error creating decrypted block device\n");
1596 rc = -1;
1597 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598 }
1599
Paul Lawrence74f29f12014-08-28 15:54:10 -07001600 /* Work out if the problem is the password or the data */
1601 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1602 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001603
Paul Lawrence74f29f12014-08-28 15:54:10 -07001604 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1605 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1606 N, r, p, scrypted_intermediate_key,
1607 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001608
Paul Lawrence74f29f12014-08-28 15:54:10 -07001609 // Does the key match the crypto footer?
1610 if (rc == 0 && memcmp(scrypted_intermediate_key,
1611 crypt_ftr->scrypted_intermediate_key,
1612 sizeof(scrypted_intermediate_key)) == 0) {
1613 SLOGI("Password matches");
1614 rc = 0;
1615 } else {
1616 /* Try mounting the file system anyway, just in case the problem's with
1617 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001618 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1619 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001620 mkdir(tmp_mount_point, 0755);
1621 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1622 SLOGE("Error temp mounting decrypted block device\n");
1623 delete_crypto_blk_dev(label);
1624
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001625 rc = ++crypt_ftr->failed_decrypt_count;
1626 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001627 } else {
1628 /* Success! */
1629 SLOGI("Password did not match but decrypted drive mounted - continue");
1630 umount(tmp_mount_point);
1631 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001632 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001633 }
1634
1635 if (rc == 0) {
1636 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001637 if (orig_failed_decrypt_count != 0) {
1638 put_crypt_ftr_and_key(crypt_ftr);
1639 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001640
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001641 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001642 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001643 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001644
1645 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001646 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001647 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001648 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001649 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001650 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001651 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001652
Paul Lawrence74f29f12014-08-28 15:54:10 -07001653 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001654 use_keymaster = keymaster_check_compatibility();
1655 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001656 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001657 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1658 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1659 upgrade = 1;
1660 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001661 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001662 upgrade = 1;
1663 }
1664
1665 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001666 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1667 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001668 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001669 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001670 }
1671 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001672
1673 // Do not fail even if upgrade failed - machine is bootable
1674 // Note that if this code is ever hit, there is a *serious* problem
1675 // since KDFs should never fail. You *must* fix the kdf before
1676 // proceeding!
1677 if (rc) {
1678 SLOGW("Upgrade failed with error %d,"
1679 " but continuing with previous state",
1680 rc);
1681 rc = 0;
1682 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001683 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001684 }
1685
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001686 errout:
1687 if (intermediate_key) {
1688 memset(intermediate_key, 0, intermediate_key_size);
1689 free(intermediate_key);
1690 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001691 return rc;
1692}
1693
Ken Sumrall29d8da82011-05-18 17:20:07 -07001694/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001695 * Called by vold when it's asked to mount an encrypted external
1696 * storage volume. The incoming partition has no crypto header/footer,
1697 * as any metadata is been stored in a separate, small partition.
1698 *
1699 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001700 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001701int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1702 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001703 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001704 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001705 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001706 return -1;
1707 }
1708
1709 unsigned long nr_sec = 0;
1710 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001711 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001712
Ken Sumrall29d8da82011-05-18 17:20:07 -07001713 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001714 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001715 return -1;
1716 }
1717
Jeff Sharkey9c484982015-03-31 10:35:33 -07001718 struct crypt_mnt_ftr ext_crypt_ftr;
1719 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1720 ext_crypt_ftr.fs_size = nr_sec;
1721 ext_crypt_ftr.keysize = keysize;
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001722 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
1723 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001724
Jeff Sharkey9c484982015-03-31 10:35:33 -07001725 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1726 out_crypto_blkdev, label);
1727}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001728
Jeff Sharkey9c484982015-03-31 10:35:33 -07001729/*
1730 * Called by vold when it's asked to unmount an encrypted external
1731 * storage volume.
1732 */
1733int cryptfs_revert_ext_volume(const char* label) {
1734 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001735}
1736
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001737int cryptfs_crypto_complete(void)
1738{
1739 return do_crypto_complete("/data");
1740}
1741
Paul Lawrencef4faa572014-01-29 13:31:03 -08001742int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1743{
1744 char encrypted_state[PROPERTY_VALUE_MAX];
1745 property_get("ro.crypto.state", encrypted_state, "");
1746 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1747 SLOGE("encrypted fs already validated or not running with encryption,"
1748 " aborting");
1749 return -1;
1750 }
1751
1752 if (get_crypt_ftr_and_key(crypt_ftr)) {
1753 SLOGE("Error getting crypt footer and key");
1754 return -1;
1755 }
1756
1757 return 0;
1758}
1759
Wei Wang4375f1b2017-02-24 17:43:01 -08001760int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001761{
Paul Lawrence05335c32015-03-05 09:46:23 -08001762 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001763 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001764 SLOGE("cryptfs_check_passwd not valid for file encryption");
1765 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001766 }
1767
Paul Lawrencef4faa572014-01-29 13:31:03 -08001768 struct crypt_mnt_ftr crypt_ftr;
1769 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001770
Paul Lawrencef4faa572014-01-29 13:31:03 -08001771 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001772 if (rc) {
1773 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001774 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001775 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001776
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001777 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001778 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1779 if (rc) {
1780 SLOGE("Password did not match");
1781 return rc;
1782 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001783
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001784 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1785 // Here we have a default actual password but a real password
1786 // we must test against the scrypted value
1787 // First, we must delete the crypto block device that
1788 // test_mount_encrypted_fs leaves behind as a side effect
1789 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1790 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1791 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1792 if (rc) {
1793 SLOGE("Default password did not match on reboot encryption");
1794 return rc;
1795 }
1796
1797 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1798 put_crypt_ftr_and_key(&crypt_ftr);
1799 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1800 if (rc) {
1801 SLOGE("Could not change password on reboot encryption");
1802 return rc;
1803 }
1804 }
1805
1806 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001807 cryptfs_clear_password();
1808 password = strdup(passwd);
1809 struct timespec now;
1810 clock_gettime(CLOCK_BOOTTIME, &now);
1811 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001812 }
1813
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001814 return rc;
1815}
1816
Ken Sumrall3ad90722011-10-04 20:38:29 -07001817int cryptfs_verify_passwd(char *passwd)
1818{
1819 struct crypt_mnt_ftr crypt_ftr;
1820 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001821 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001822 char encrypted_state[PROPERTY_VALUE_MAX];
1823 int rc;
1824
1825 property_get("ro.crypto.state", encrypted_state, "");
1826 if (strcmp(encrypted_state, "encrypted") ) {
1827 SLOGE("device not encrypted, aborting");
1828 return -2;
1829 }
1830
1831 if (!master_key_saved) {
1832 SLOGE("encrypted fs not yet mounted, aborting");
1833 return -1;
1834 }
1835
1836 if (!saved_mount_point) {
1837 SLOGE("encrypted fs failed to save mount point, aborting");
1838 return -1;
1839 }
1840
Ken Sumrall160b4d62013-04-22 12:15:39 -07001841 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001842 SLOGE("Error getting crypt footer and key\n");
1843 return -1;
1844 }
1845
1846 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1847 /* If the device has no password, then just say the password is valid */
1848 rc = 0;
1849 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001850 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001851 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1852 /* They match, the password is correct */
1853 rc = 0;
1854 } else {
1855 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1856 sleep(1);
1857 rc = 1;
1858 }
1859 }
1860
1861 return rc;
1862}
1863
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001864/* Initialize a crypt_mnt_ftr structure. The keysize is
1865 * defaulted to 16 bytes, and the filesystem size to 0.
1866 * Presumably, at a minimum, the caller will update the
1867 * filesystem size and crypto_type_name after calling this function.
1868 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001869static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001870{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001871 off64_t off;
1872
1873 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001874 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001875 ftr->major_version = CURRENT_MAJOR_VERSION;
1876 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001877 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001878 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001879
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001880 switch (keymaster_check_compatibility()) {
1881 case 1:
1882 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1883 break;
1884
1885 case 0:
1886 ftr->kdf_type = KDF_SCRYPT;
1887 break;
1888
1889 default:
1890 SLOGE("keymaster_check_compatibility failed");
1891 return -1;
1892 }
1893
Kenny Rootc4c70f12013-06-14 12:11:38 -07001894 get_device_scrypt_params(ftr);
1895
Ken Sumrall160b4d62013-04-22 12:15:39 -07001896 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1897 if (get_crypt_ftr_info(NULL, &off) == 0) {
1898 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1899 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1900 ftr->persist_data_size;
1901 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001902
1903 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001904}
1905
Ken Sumrall29d8da82011-05-18 17:20:07 -07001906static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001907{
Ken Sumralle550f782013-08-20 13:48:23 -07001908 const char *args[10];
1909 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1910 int num_args;
1911 int status;
1912 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001913 int rc = -1;
1914
Ken Sumrall29d8da82011-05-18 17:20:07 -07001915 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001916#ifdef TARGET_USES_MKE2FS
1917 args[0] = "/system/bin/mke2fs";
1918 args[1] = "-M";
1919 args[2] = "/data";
1920 args[3] = "-b";
1921 args[4] = "4096";
1922 args[5] = "-t";
1923 args[6] = "ext4";
1924 args[7] = crypto_blkdev;
1925 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1926 args[8] = size_str;
1927 num_args = 9;
1928#else
Ken Sumralle550f782013-08-20 13:48:23 -07001929 args[0] = "/system/bin/make_ext4fs";
1930 args[1] = "-a";
1931 args[2] = "/data";
1932 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07001933 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07001934 args[4] = size_str;
1935 args[5] = crypto_blkdev;
1936 num_args = 6;
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001937#endif
Ken Sumralle550f782013-08-20 13:48:23 -07001938 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1939 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001940 } else if (type == F2FS_FS) {
1941 args[0] = "/system/bin/mkfs.f2fs";
1942 args[1] = "-t";
1943 args[2] = "-d1";
1944 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001945 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07001946 args[4] = size_str;
1947 num_args = 5;
1948 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
1949 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001950 } else {
1951 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1952 return -1;
1953 }
1954
Ken Sumralle550f782013-08-20 13:48:23 -07001955 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1956
1957 if (tmp != 0) {
1958 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001959 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001960 if (WIFEXITED(status)) {
1961 if (WEXITSTATUS(status)) {
1962 SLOGE("Error creating filesystem on %s, exit status %d ",
1963 crypto_blkdev, WEXITSTATUS(status));
1964 } else {
1965 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1966 rc = 0;
1967 }
1968 } else {
1969 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1970 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001971 }
1972
1973 return rc;
1974}
1975
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001976#define CRYPTO_ENABLE_WIPE 1
1977#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001978
1979#define FRAMEWORK_BOOT_WAIT 60
1980
Paul Lawrence87999172014-02-20 12:21:31 -08001981static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1982{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001983 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001984 if (fd == -1) {
1985 SLOGE("Error opening file %s", filename);
1986 return -1;
1987 }
1988
1989 char block[CRYPT_INPLACE_BUFSIZE];
1990 memset(block, 0, sizeof(block));
1991 if (unix_read(fd, block, sizeof(block)) < 0) {
1992 SLOGE("Error reading file %s", filename);
1993 close(fd);
1994 return -1;
1995 }
1996
1997 close(fd);
1998
1999 SHA256_CTX c;
2000 SHA256_Init(&c);
2001 SHA256_Update(&c, block, sizeof(block));
2002 SHA256_Final(buf, &c);
2003
2004 return 0;
2005}
2006
JP Abgrall62c7af32014-06-16 13:01:23 -07002007static int get_fs_type(struct fstab_rec *rec)
2008{
2009 if (!strcmp(rec->fs_type, "ext4")) {
2010 return EXT4_FS;
2011 } else if (!strcmp(rec->fs_type, "f2fs")) {
2012 return F2FS_FS;
2013 } else {
2014 return -1;
2015 }
2016}
2017
Paul Lawrence87999172014-02-20 12:21:31 -08002018static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2019 char *crypto_blkdev, char *real_blkdev,
2020 int previously_encrypted_upto)
2021{
2022 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002023 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002024
Paul Lawrence73d7a022014-06-09 14:10:09 -07002025 if (!is_battery_ok_to_start()) {
2026 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002027 return 0;
2028 }
2029
2030 /* The size of the userdata partition, and add in the vold volumes below */
2031 tot_encryption_size = crypt_ftr->fs_size;
2032
2033 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002034 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2035 int fs_type = get_fs_type(rec);
2036 if (fs_type < 0) {
2037 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2038 return -1;
2039 }
2040 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002041 } else if (how == CRYPTO_ENABLE_INPLACE) {
2042 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2043 crypt_ftr->fs_size, &cur_encryption_done,
2044 tot_encryption_size,
2045 previously_encrypted_upto);
2046
JP Abgrall7fc1de82014-10-10 18:43:41 -07002047 if (rc == ENABLE_INPLACE_ERR_DEV) {
2048 /* Hack for b/17898962 */
2049 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2050 cryptfs_reboot(reboot);
2051 }
2052
Paul Lawrence73d7a022014-06-09 14:10:09 -07002053 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002054 crypt_ftr->encrypted_upto = cur_encryption_done;
2055 }
2056
Paul Lawrence73d7a022014-06-09 14:10:09 -07002057 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002058 /* The inplace routine never actually sets the progress to 100% due
2059 * to the round down nature of integer division, so set it here */
2060 property_set("vold.encrypt_progress", "100");
2061 }
2062 } else {
2063 /* Shouldn't happen */
2064 SLOGE("cryptfs_enable: internal error, unknown option\n");
2065 rc = -1;
2066 }
2067
2068 return rc;
2069}
2070
Wei Wang4375f1b2017-02-24 17:43:01 -08002071int cryptfs_enable_internal(char *howarg, int crypt_type, const char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002072 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002073{
2074 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002075 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002076 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002077 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002078 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002079 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002080 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002081 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002082 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002083 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002084 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002085 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002086 bool onlyCreateHeader = false;
2087 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002088
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002089 if (!strcmp(howarg, "wipe")) {
2090 how = CRYPTO_ENABLE_WIPE;
2091 } else if (! strcmp(howarg, "inplace")) {
2092 how = CRYPTO_ENABLE_INPLACE;
2093 } else {
2094 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002095 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002096 }
2097
Paul Lawrence87999172014-02-20 12:21:31 -08002098 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002099 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2100 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2101 /* An encryption was underway and was interrupted */
2102 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2103 crypt_ftr.encrypted_upto = 0;
2104 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002105
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002106 /* At this point, we are in an inconsistent state. Until we successfully
2107 complete encryption, a reboot will leave us broken. So mark the
2108 encryption failed in case that happens.
2109 On successfully completing encryption, remove this flag */
2110 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002111
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002112 put_crypt_ftr_and_key(&crypt_ftr);
2113 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2114 if (!check_ftr_sha(&crypt_ftr)) {
2115 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2116 put_crypt_ftr_and_key(&crypt_ftr);
2117 goto error_unencrypted;
2118 }
2119
2120 /* Doing a reboot-encryption*/
2121 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2122 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2123 rebootEncryption = true;
2124 }
Paul Lawrence87999172014-02-20 12:21:31 -08002125 }
2126
2127 property_get("ro.crypto.state", encrypted_state, "");
2128 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2129 SLOGE("Device is already running encrypted, aborting");
2130 goto error_unencrypted;
2131 }
2132
2133 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2134 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002135 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002136
Ken Sumrall3ed82362011-01-28 23:31:16 -08002137 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002138 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002139 if (fd == -1) {
2140 SLOGE("Cannot open block device %s\n", real_blkdev);
2141 goto error_unencrypted;
2142 }
2143 unsigned long nr_sec;
2144 get_blkdev_size(fd, &nr_sec);
2145 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002146 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2147 goto error_unencrypted;
2148 }
2149 close(fd);
2150
2151 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002152 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002153 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002154 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002155 if (fs_size_sec == 0)
2156 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2157
Paul Lawrence87999172014-02-20 12:21:31 -08002158 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002159
2160 if (fs_size_sec > max_fs_size_sec) {
2161 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2162 goto error_unencrypted;
2163 }
2164 }
2165
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002166 /* Get a wakelock as this may take a while, and we don't want the
2167 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2168 * wants to keep the screen on, it can grab a full wakelock.
2169 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002170 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002171 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2172
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002173 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002174 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002175 */
2176 property_set("vold.decrypt", "trigger_shutdown_framework");
2177 SLOGD("Just asked init to shut down class main\n");
2178
Jeff Sharkey9c484982015-03-31 10:35:33 -07002179 /* Ask vold to unmount all devices that it manages */
2180 if (vold_unmountAll()) {
2181 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002182 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002183
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002184 /* no_ui means we are being called from init, not settings.
2185 Now we always reboot from settings, so !no_ui means reboot
2186 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002187 if (!no_ui) {
2188 /* Try fallback, which is to reboot and try there */
2189 onlyCreateHeader = true;
2190 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2191 if (breadcrumb == 0) {
2192 SLOGE("Failed to create breadcrumb file");
2193 goto error_shutting_down;
2194 }
2195 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002196 }
2197
2198 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002199 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002200 /* Now that /data is unmounted, we need to mount a tmpfs
2201 * /data, set a property saying we're doing inplace encryption,
2202 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002203 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002204 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002205 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002206 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002207 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002208 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002209
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002210 /* restart the framework. */
2211 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002212 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002213
Ken Sumrall92736ef2012-10-17 20:57:14 -07002214 /* Ugh, shutting down the framework is not synchronous, so until it
2215 * can be fixed, this horrible hack will wait a moment for it all to
2216 * shut down before proceeding. Without it, some devices cannot
2217 * restart the graphics services.
2218 */
2219 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002220 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002221
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002222 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002223 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002224 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002225 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2226 goto error_shutting_down;
2227 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002228
Paul Lawrence87999172014-02-20 12:21:31 -08002229 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2230 crypt_ftr.fs_size = nr_sec
2231 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2232 } else {
2233 crypt_ftr.fs_size = nr_sec;
2234 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002235 /* At this point, we are in an inconsistent state. Until we successfully
2236 complete encryption, a reboot will leave us broken. So mark the
2237 encryption failed in case that happens.
2238 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002239 if (onlyCreateHeader) {
2240 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2241 } else {
2242 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2243 }
Paul Lawrence87999172014-02-20 12:21:31 -08002244 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002245 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002246
Paul Lawrence87999172014-02-20 12:21:31 -08002247 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002248 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2249 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002250 SLOGE("Cannot create encrypted master key\n");
2251 goto error_shutting_down;
2252 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002253
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002254 /* Replace scrypted intermediate key if we are preparing for a reboot */
2255 if (onlyCreateHeader) {
2256 unsigned char fake_master_key[KEY_LEN_BYTES];
2257 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2258 memset(fake_master_key, 0, sizeof(fake_master_key));
2259 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2260 encrypted_fake_master_key, &crypt_ftr);
2261 }
2262
Paul Lawrence87999172014-02-20 12:21:31 -08002263 /* Write the key to the end of the partition */
2264 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002265
Paul Lawrence87999172014-02-20 12:21:31 -08002266 /* If any persistent data has been remembered, save it.
2267 * If none, create a valid empty table and save that.
2268 */
2269 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002270 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002271 if (pdata) {
2272 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2273 persist_data = pdata;
2274 }
2275 }
2276 if (persist_data) {
2277 save_persistent_data();
2278 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002279 }
2280
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002281 if (onlyCreateHeader) {
2282 sleep(2);
2283 cryptfs_reboot(reboot);
2284 }
2285
2286 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002287 /* startup service classes main and late_start */
2288 property_set("vold.decrypt", "trigger_restart_min_framework");
2289 SLOGD("Just triggered restart_min_framework\n");
2290
2291 /* OK, the framework is restarted and will soon be showing a
2292 * progress bar. Time to setup an encrypted mapping, and
2293 * either write a new filesystem, or encrypt in place updating
2294 * the progress bar as we work.
2295 */
2296 }
2297
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002298 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002299 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002300 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002301
Paul Lawrence87999172014-02-20 12:21:31 -08002302 /* If we are continuing, check checksums match */
2303 rc = 0;
2304 if (previously_encrypted_upto) {
2305 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2306 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002307
Paul Lawrence87999172014-02-20 12:21:31 -08002308 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2309 sizeof(hash_first_block)) != 0) {
2310 SLOGE("Checksums do not match - trigger wipe");
2311 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002312 }
2313 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002314
Paul Lawrence87999172014-02-20 12:21:31 -08002315 if (!rc) {
2316 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2317 crypto_blkdev, real_blkdev,
2318 previously_encrypted_upto);
2319 }
2320
2321 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002322 if (!rc && how == CRYPTO_ENABLE_INPLACE
2323 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002324 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2325 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002326 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002327 SLOGE("Error calculating checksum for continuing encryption");
2328 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002329 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002330 }
2331
2332 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002333 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002334
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002335 if (! rc) {
2336 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002337 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002338
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002339 if (how == CRYPTO_ENABLE_INPLACE
2340 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002341 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2342 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002343 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002344 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002345
Paul Lawrence6bfed202014-07-28 12:47:22 -07002346 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002347
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002348 if (how == CRYPTO_ENABLE_WIPE
2349 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002350 char value[PROPERTY_VALUE_MAX];
2351 property_get("ro.crypto.state", value, "");
2352 if (!strcmp(value, "")) {
2353 /* default encryption - continue first boot sequence */
2354 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08002355 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002356 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002357 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2358 // Bring up cryptkeeper that will check the password and set it
2359 property_set("vold.decrypt", "trigger_shutdown_framework");
2360 sleep(2);
2361 property_set("vold.encrypt_progress", "");
2362 cryptfs_trigger_restart_min_framework();
2363 } else {
2364 cryptfs_check_passwd(DEFAULT_PASSWORD);
2365 cryptfs_restart_internal(1);
2366 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002367 return 0;
2368 } else {
2369 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002370 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002371 }
Paul Lawrence87999172014-02-20 12:21:31 -08002372 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002373 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08002374 cryptfs_reboot(shutdown);
2375 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002376 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002377 char value[PROPERTY_VALUE_MAX];
2378
Ken Sumrall319369a2012-06-27 16:30:18 -07002379 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002380 if (!strcmp(value, "1")) {
2381 /* wipe data if encryption failed */
2382 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002383 std::string err;
2384 const std::vector<std::string> options = {
2385 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2386 };
2387 if (!write_bootloader_message(options, &err)) {
2388 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002389 }
Paul Lawrence87999172014-02-20 12:21:31 -08002390 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002391 } else {
2392 /* set property to trigger dialog */
2393 property_set("vold.encrypt_progress", "error_partially_encrypted");
2394 release_wake_lock(lockid);
2395 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002396 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002397 }
2398
Ken Sumrall3ed82362011-01-28 23:31:16 -08002399 /* hrm, the encrypt step claims success, but the reboot failed.
2400 * This should not happen.
2401 * Set the property and return. Hope the framework can deal with it.
2402 */
2403 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002404 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002405 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002406
2407error_unencrypted:
2408 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002409 if (lockid[0]) {
2410 release_wake_lock(lockid);
2411 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002412 return -1;
2413
2414error_shutting_down:
2415 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2416 * but the framework is stopped and not restarted to show the error, so it's up to
2417 * vold to restart the system.
2418 */
2419 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08002420 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002421
2422 /* shouldn't get here */
2423 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002424 if (lockid[0]) {
2425 release_wake_lock(lockid);
2426 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002427 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002428}
2429
Paul Lawrence569649f2015-09-09 12:13:00 -07002430int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002431{
Paul Lawrence569649f2015-09-09 12:13:00 -07002432 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002433}
2434
Paul Lawrence569649f2015-09-09 12:13:00 -07002435int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002436{
2437 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07002438 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002439}
2440
2441int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002442{
Paul Crowley38132a12016-02-09 09:50:32 +00002443 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002444 SLOGE("cryptfs_changepw not valid for file encryption");
2445 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002446 }
2447
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002448 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002449 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002450
2451 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002452 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002453 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002454 return -1;
2455 }
2456
Paul Lawrencef4faa572014-01-29 13:31:03 -08002457 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2458 SLOGE("Invalid crypt_type %d", crypt_type);
2459 return -1;
2460 }
2461
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002462 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002463 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002464 SLOGE("Error getting crypt footer and key");
2465 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002466 }
2467
Paul Lawrencef4faa572014-01-29 13:31:03 -08002468 crypt_ftr.crypt_type = crypt_type;
2469
JP Abgrall933216c2015-02-11 13:44:32 -08002470 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002471 : newpw,
2472 crypt_ftr.salt,
2473 saved_master_key,
2474 crypt_ftr.master_key,
2475 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002476 if (rc) {
2477 SLOGE("Encrypt master key failed: %d", rc);
2478 return -1;
2479 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002480 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002481 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002482
2483 return 0;
2484}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002485
Rubin Xu85c01f92014-10-13 12:49:54 +01002486static unsigned int persist_get_max_entries(int encrypted) {
2487 struct crypt_mnt_ftr crypt_ftr;
2488 unsigned int dsize;
2489 unsigned int max_persistent_entries;
2490
2491 /* If encrypted, use the values from the crypt_ftr, otherwise
2492 * use the values for the current spec.
2493 */
2494 if (encrypted) {
2495 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2496 return -1;
2497 }
2498 dsize = crypt_ftr.persist_data_size;
2499 } else {
2500 dsize = CRYPT_PERSIST_DATA_SIZE;
2501 }
2502
2503 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2504 sizeof(struct crypt_persist_entry);
2505
2506 return max_persistent_entries;
2507}
2508
2509static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002510{
2511 unsigned int i;
2512
2513 if (persist_data == NULL) {
2514 return -1;
2515 }
2516 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2517 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2518 /* We found it! */
2519 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2520 return 0;
2521 }
2522 }
2523
2524 return -1;
2525}
2526
Rubin Xu85c01f92014-10-13 12:49:54 +01002527static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002528{
2529 unsigned int i;
2530 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002531 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002532
2533 if (persist_data == NULL) {
2534 return -1;
2535 }
2536
Rubin Xu85c01f92014-10-13 12:49:54 +01002537 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002538
2539 num = persist_data->persist_valid_entries;
2540
2541 for (i = 0; i < num; i++) {
2542 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2543 /* We found an existing entry, update it! */
2544 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2545 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2546 return 0;
2547 }
2548 }
2549
2550 /* We didn't find it, add it to the end, if there is room */
2551 if (persist_data->persist_valid_entries < max_persistent_entries) {
2552 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2553 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2554 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2555 persist_data->persist_valid_entries++;
2556 return 0;
2557 }
2558
2559 return -1;
2560}
2561
Rubin Xu85c01f92014-10-13 12:49:54 +01002562/**
2563 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2564 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2565 */
2566static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002567 unsigned int field_len;
2568 unsigned int key_index;
2569 field_len = strlen(field);
2570
2571 if (index == 0) {
2572 // The first key in a multi-entry field is just the filedname itself.
2573 if (!strcmp(key, field)) {
2574 return 1;
2575 }
2576 }
2577 // Match key against "%s_%d" % (field, index)
2578 if (strlen(key) < field_len + 1 + 1) {
2579 // Need at least a '_' and a digit.
2580 return 0;
2581 }
2582 if (strncmp(key, field, field_len)) {
2583 // If the key does not begin with field, it's not a match.
2584 return 0;
2585 }
2586 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
2587 return 0;
2588 }
2589 return key_index >= index;
2590}
2591
2592/*
2593 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2594 * remaining entries starting from index will be deleted.
2595 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2596 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2597 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2598 *
2599 */
2600static int persist_del_keys(const char *fieldname, unsigned index)
2601{
2602 unsigned int i;
2603 unsigned int j;
2604 unsigned int num;
2605
2606 if (persist_data == NULL) {
2607 return PERSIST_DEL_KEY_ERROR_OTHER;
2608 }
2609
2610 num = persist_data->persist_valid_entries;
2611
2612 j = 0; // points to the end of non-deleted entries.
2613 // Filter out to-be-deleted entries in place.
2614 for (i = 0; i < num; i++) {
2615 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2616 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2617 j++;
2618 }
2619 }
2620
2621 if (j < num) {
2622 persist_data->persist_valid_entries = j;
2623 // Zeroise the remaining entries
2624 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2625 return PERSIST_DEL_KEY_OK;
2626 } else {
2627 // Did not find an entry matching the given fieldname
2628 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2629 }
2630}
2631
2632static int persist_count_keys(const char *fieldname)
2633{
2634 unsigned int i;
2635 unsigned int count;
2636
2637 if (persist_data == NULL) {
2638 return -1;
2639 }
2640
2641 count = 0;
2642 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2643 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2644 count++;
2645 }
2646 }
2647
2648 return count;
2649}
2650
Ken Sumrall160b4d62013-04-22 12:15:39 -07002651/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002652int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002653{
Paul Crowley38132a12016-02-09 09:50:32 +00002654 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002655 SLOGE("Cannot get field when file encrypted");
2656 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002657 }
2658
Ken Sumrall160b4d62013-04-22 12:15:39 -07002659 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002660 /* CRYPTO_GETFIELD_OK is success,
2661 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2662 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2663 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002664 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002665 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2666 int i;
2667 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002668
2669 if (persist_data == NULL) {
2670 load_persistent_data();
2671 if (persist_data == NULL) {
2672 SLOGE("Getfield error, cannot load persistent data");
2673 goto out;
2674 }
2675 }
2676
Rubin Xu85c01f92014-10-13 12:49:54 +01002677 // Read value from persistent entries. If the original value is split into multiple entries,
2678 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002679 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002680 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2681 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2682 // value too small
2683 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2684 goto out;
2685 }
2686 rc = CRYPTO_GETFIELD_OK;
2687
2688 for (i = 1; /* break explicitly */; i++) {
2689 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2690 (int) sizeof(temp_field)) {
2691 // If the fieldname is very long, we stop as soon as it begins to overflow the
2692 // maximum field length. At this point we have in fact fully read out the original
2693 // value because cryptfs_setfield would not allow fields with longer names to be
2694 // written in the first place.
2695 break;
2696 }
2697 if (!persist_get_key(temp_field, temp_value)) {
2698 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2699 // value too small.
2700 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2701 goto out;
2702 }
2703 } else {
2704 // Exhaust all entries.
2705 break;
2706 }
2707 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002708 } else {
2709 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002710 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002711 }
2712
2713out:
2714 return rc;
2715}
2716
2717/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002718int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002719{
Paul Crowley38132a12016-02-09 09:50:32 +00002720 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002721 SLOGE("Cannot set field when file encrypted");
2722 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002723 }
2724
Ken Sumrall160b4d62013-04-22 12:15:39 -07002725 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002726 /* 0 is success, negative values are error */
2727 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002728 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002729 unsigned int field_id;
2730 char temp_field[PROPERTY_KEY_MAX];
2731 unsigned int num_entries;
2732 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002733
2734 if (persist_data == NULL) {
2735 load_persistent_data();
2736 if (persist_data == NULL) {
2737 SLOGE("Setfield error, cannot load persistent data");
2738 goto out;
2739 }
2740 }
2741
2742 property_get("ro.crypto.state", encrypted_state, "");
2743 if (!strcmp(encrypted_state, "encrypted") ) {
2744 encrypted = 1;
2745 }
2746
Rubin Xu85c01f92014-10-13 12:49:54 +01002747 // Compute the number of entries required to store value, each entry can store up to
2748 // (PROPERTY_VALUE_MAX - 1) chars
2749 if (strlen(value) == 0) {
2750 // Empty value also needs one entry to store.
2751 num_entries = 1;
2752 } else {
2753 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2754 }
2755
2756 max_keylen = strlen(fieldname);
2757 if (num_entries > 1) {
2758 // Need an extra "_%d" suffix.
2759 max_keylen += 1 + log10(num_entries);
2760 }
2761 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2762 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002763 goto out;
2764 }
2765
Rubin Xu85c01f92014-10-13 12:49:54 +01002766 // Make sure we have enough space to write the new value
2767 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2768 persist_get_max_entries(encrypted)) {
2769 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2770 goto out;
2771 }
2772
2773 // Now that we know persist_data has enough space for value, let's delete the old field first
2774 // to make up space.
2775 persist_del_keys(fieldname, 0);
2776
2777 if (persist_set_key(fieldname, value, encrypted)) {
2778 // fail to set key, should not happen as we have already checked the available space
2779 SLOGE("persist_set_key() error during setfield()");
2780 goto out;
2781 }
2782
2783 for (field_id = 1; field_id < num_entries; field_id++) {
2784 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
2785
2786 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2787 // fail to set key, should not happen as we have already checked the available space.
2788 SLOGE("persist_set_key() error during setfield()");
2789 goto out;
2790 }
2791 }
2792
Ken Sumrall160b4d62013-04-22 12:15:39 -07002793 /* If we are running encrypted, save the persistent data now */
2794 if (encrypted) {
2795 if (save_persistent_data()) {
2796 SLOGE("Setfield error, cannot save persistent data");
2797 goto out;
2798 }
2799 }
2800
Rubin Xu85c01f92014-10-13 12:49:54 +01002801 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002802
2803out:
2804 return rc;
2805}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002806
2807/* Checks userdata. Attempt to mount the volume if default-
2808 * encrypted.
2809 * On success trigger next init phase and return 0.
2810 * Currently do not handle failure - see TODO below.
2811 */
2812int cryptfs_mount_default_encrypted(void)
2813{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002814 int crypt_type = cryptfs_get_password_type();
2815 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2816 SLOGE("Bad crypt type - error");
2817 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2818 SLOGD("Password is not default - "
2819 "starting min framework to prompt");
2820 property_set("vold.decrypt", "trigger_restart_min_framework");
2821 return 0;
2822 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2823 SLOGD("Password is default - restarting filesystem");
2824 cryptfs_restart_internal(0);
2825 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002826 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002827 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002828 }
2829
Paul Lawrence6bfed202014-07-28 12:47:22 -07002830 /** Corrupt. Allow us to boot into framework, which will detect bad
2831 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002832 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002833 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002834 return 0;
2835}
2836
2837/* Returns type of the password, default, pattern, pin or password.
2838 */
2839int cryptfs_get_password_type(void)
2840{
Paul Crowley38132a12016-02-09 09:50:32 +00002841 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002842 SLOGE("cryptfs_get_password_type not valid for file encryption");
2843 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002844 }
2845
Paul Lawrencef4faa572014-01-29 13:31:03 -08002846 struct crypt_mnt_ftr crypt_ftr;
2847
2848 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2849 SLOGE("Error getting crypt footer and key\n");
2850 return -1;
2851 }
2852
Paul Lawrence6bfed202014-07-28 12:47:22 -07002853 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2854 return -1;
2855 }
2856
Paul Lawrencef4faa572014-01-29 13:31:03 -08002857 return crypt_ftr.crypt_type;
2858}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002859
Paul Lawrence05335c32015-03-05 09:46:23 -08002860const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002861{
Paul Crowley38132a12016-02-09 09:50:32 +00002862 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002863 SLOGE("cryptfs_get_password not valid for file encryption");
2864 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002865 }
2866
Paul Lawrence399317e2014-03-10 13:20:50 -07002867 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002868 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002869 if (now.tv_sec < password_expiry_time) {
2870 return password;
2871 } else {
2872 cryptfs_clear_password();
2873 return 0;
2874 }
2875}
2876
2877void cryptfs_clear_password()
2878{
2879 if (password) {
2880 size_t len = strlen(password);
2881 memset(password, 0, len);
2882 free(password);
2883 password = 0;
2884 password_expiry_time = 0;
2885 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002886}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002887
Paul Lawrence0c247462015-10-29 10:30:57 -07002888int cryptfs_isConvertibleToFBE()
2889{
2890 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2891 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2892}
2893
Paul Lawrence731a7a22015-04-28 22:14:15 +00002894int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
2895{
2896 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
2897 SLOGE("Failed to initialize crypt_ftr");
2898 return -1;
2899 }
2900
2901 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
2902 crypt_ftr->salt, crypt_ftr)) {
2903 SLOGE("Cannot create encrypted master key\n");
2904 return -1;
2905 }
2906
2907 //crypt_ftr->keysize = key_length / 8;
2908 return 0;
2909}
2910
2911int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
2912 unsigned char* master_key)
2913{
2914 int rc;
2915
Paul Lawrence731a7a22015-04-28 22:14:15 +00002916 unsigned char* intermediate_key = 0;
2917 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002918
2919 if (password == 0 || *password == 0) {
2920 password = DEFAULT_PASSWORD;
2921 }
2922
Paul Lawrence731a7a22015-04-28 22:14:15 +00002923 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
2924 &intermediate_key_size);
2925
Paul Lawrence300dae72016-03-11 11:02:52 -08002926 if (rc) {
2927 SLOGE("Can't calculate intermediate key");
2928 return rc;
2929 }
2930
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002931 int N = 1 << ftr->N_factor;
2932 int r = 1 << ftr->r_factor;
2933 int p = 1 << ftr->p_factor;
2934
2935 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
2936
2937 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
2938 ftr->salt, sizeof(ftr->salt), N, r, p,
2939 scrypted_intermediate_key,
2940 sizeof(scrypted_intermediate_key));
2941
2942 free(intermediate_key);
2943
2944 if (rc) {
Paul Lawrence300dae72016-03-11 11:02:52 -08002945 SLOGE("Can't scrypt intermediate key");
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002946 return rc;
2947 }
2948
2949 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
2950 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00002951}
2952
2953int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
2954 const unsigned char* master_key)
2955{
2956 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
2957 ftr);
2958}
Paul Lawrence6e410592016-05-24 14:20:38 -07002959
Eric Biggersb45caaf2017-02-02 14:52:12 -08002960void cryptfs_get_file_encryption_modes(const char **contents_mode_ret,
2961 const char **filenames_mode_ret)
Paul Lawrence6e410592016-05-24 14:20:38 -07002962{
2963 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
Eric Biggersb45caaf2017-02-02 14:52:12 -08002964 fs_mgr_get_file_encryption_modes(rec, contents_mode_ret, filenames_mode_ret);
Paul Lawrence6e410592016-05-24 14:20:38 -07002965}