blob: 95b882f7a478fc58a01aa35745666578b5476b09 [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>
Ken Sumrall3ed82362011-01-28 23:31:16 -080041#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080046#include "cryptfs.h"
47#define LOG_TAG "Cryptfs"
48#include "cutils/log.h"
49#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070050#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080051#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070052#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070053#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070054#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070055#include "crypto_scrypt.h"
Paul Lawrence7053e9c2015-03-26 08:32:18 -070056#include "Ext4Crypt.h"
57#include "ext4_crypt_init_extensions.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080058#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000059#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080060#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080061#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080062
Shawn Willdend1fd8462015-02-24 09:51:34 -070063#include <hardware/keymaster0.h>
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070064
Mark Salyzyn3e971272014-01-21 13:27:04 -080065#define UNUSED __attribute__((unused))
66
Mark Salyzyn5eecc442014-02-12 14:16:14 -080067#define UNUSED __attribute__((unused))
68
Ajay Dudani87701e22014-09-17 21:02:52 -070069#ifdef CONFIG_HW_DISK_ENCRYPTION
70#include "cryptfs_hw.h"
71#endif
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 Lawrencef4faa572014-01-29 13:31:03 -080081// "default_password" encoded into hex (d=0x64 etc)
82#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
83
Ken Sumrall29d8da82011-05-18 17:20:07 -070084#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070085#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070086
Ken Sumralle919efe2012-09-29 17:07:41 -070087#define TABLE_LOAD_RETRIES 10
88
Shawn Willden47ba10d2014-09-03 17:07:06 -060089#define RSA_KEY_SIZE 2048
90#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
91#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070092
Paul Lawrence8e3f4512014-09-08 10:11:17 -070093#define RETRY_MOUNT_ATTEMPTS 10
94#define RETRY_MOUNT_DELAY_SECONDS 1
95
Ken Sumrall8f869aa2010-12-03 03:47:09 -080096char *me = "cryptfs";
97
Jason parks70a4b3f2011-01-28 10:10:47 -060098static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070099static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600100static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700101static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800102
Shawn Willdend1fd8462015-02-24 09:51:34 -0700103static int keymaster_init(keymaster0_device_t **keymaster_dev)
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700104{
105 int rc;
106
107 const hw_module_t* mod;
108 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
109 if (rc) {
110 ALOGE("could not find any keystore module");
111 goto out;
112 }
113
Shawn Willdend1fd8462015-02-24 09:51:34 -0700114 rc = keymaster0_open(mod, keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700115 if (rc) {
116 ALOGE("could not open keymaster device in %s (%s)",
117 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
118 goto out;
119 }
120
121 return 0;
122
123out:
124 *keymaster_dev = NULL;
125 return rc;
126}
127
128/* Should we use keymaster? */
129static int keymaster_check_compatibility()
130{
Shawn Willdend1fd8462015-02-24 09:51:34 -0700131 keymaster0_device_t *keymaster_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700132 int rc = 0;
133
134 if (keymaster_init(&keymaster_dev)) {
135 SLOGE("Failed to init keymaster");
136 rc = -1;
137 goto out;
138 }
139
Paul Lawrence8c008392014-05-06 14:02:48 -0700140 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
141
142 if (keymaster_dev->common.module->module_api_version
143 < KEYMASTER_MODULE_API_VERSION_0_3) {
144 rc = 0;
145 goto out;
146 }
147
Shawn Willden7c49ab02014-10-30 08:12:32 -0600148 if (!(keymaster_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
149 (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700150 rc = 1;
151 }
152
153out:
Shawn Willdend1fd8462015-02-24 09:51:34 -0700154 keymaster0_close(keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700155 return rc;
156}
157
158/* Create a new keymaster key and store it in this footer */
159static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
160{
161 uint8_t* key = 0;
Shawn Willdend1fd8462015-02-24 09:51:34 -0700162 keymaster0_device_t *keymaster_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700163
164 if (keymaster_init(&keymaster_dev)) {
165 SLOGE("Failed to init keymaster");
166 return -1;
167 }
168
169 int rc = 0;
170
171 keymaster_rsa_keygen_params_t params;
172 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600173 params.public_exponent = RSA_EXPONENT;
174 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700175
176 size_t key_size;
177 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
178 &key, &key_size)) {
179 SLOGE("Failed to generate keypair");
180 rc = -1;
181 goto out;
182 }
183
184 if (key_size > KEYMASTER_BLOB_SIZE) {
185 SLOGE("Keymaster key too large for crypto footer");
186 rc = -1;
187 goto out;
188 }
189
190 memcpy(ftr->keymaster_blob, key, key_size);
191 ftr->keymaster_blob_size = key_size;
192
193out:
Shawn Willdend1fd8462015-02-24 09:51:34 -0700194 keymaster0_close(keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700195 free(key);
196 return rc;
197}
198
Shawn Willdene17a9c42014-09-08 13:04:08 -0600199/* This signs the given object using the keymaster key. */
200static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600201 const unsigned char *object,
202 const size_t object_size,
203 unsigned char **signature,
204 size_t *signature_size)
205{
206 int rc = 0;
Shawn Willdend1fd8462015-02-24 09:51:34 -0700207 keymaster0_device_t *keymaster_dev = 0;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600208 if (keymaster_init(&keymaster_dev)) {
209 SLOGE("Failed to init keymaster");
210 return -1;
211 }
212
213 /* We currently set the digest type to DIGEST_NONE because it's the
214 * only supported value for keymaster. A similar issue exists with
215 * PADDING_NONE. Long term both of these should likely change.
216 */
217 keymaster_rsa_sign_params_t params;
218 params.digest_type = DIGEST_NONE;
219 params.padding_type = PADDING_NONE;
220
221 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600222 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600223 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600224
Shawn Willdene17a9c42014-09-08 13:04:08 -0600225 // To sign a message with RSA, the message must satisfy two
226 // constraints:
227 //
228 // 1. The message, when interpreted as a big-endian numeric value, must
229 // be strictly less than the public modulus of the RSA key. Note
230 // that because the most significant bit of the public modulus is
231 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
232 // key), an n-bit message with most significant bit 0 always
233 // satisfies this requirement.
234 //
235 // 2. The message must have the same length in bits as the public
236 // modulus of the RSA key. This requirement isn't mathematically
237 // necessary, but is necessary to ensure consistency in
238 // implementations.
239 switch (ftr->kdf_type) {
240 case KDF_SCRYPT_KEYMASTER_UNPADDED:
241 // This is broken: It produces a message which is shorter than
242 // the public modulus, failing criterion 2.
243 memcpy(to_sign, object, object_size);
244 to_sign_size = object_size;
245 SLOGI("Signing unpadded object");
246 break;
247 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
248 // This is broken: Since the value of object is uniformly
249 // distributed, it produces a message that is larger than the
250 // public modulus with probability 0.25.
251 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
252 SLOGI("Signing end-padded object");
253 break;
254 case KDF_SCRYPT_KEYMASTER:
255 // This ensures the most significant byte of the signed message
256 // is zero. We could have zero-padded to the left instead, but
257 // this approach is slightly more robust against changes in
258 // object size. However, it's still broken (but not unusably
259 // so) because we really should be using a proper RSA padding
260 // function, such as OAEP.
261 //
262 // TODO(paullawrence): When keymaster 0.4 is available, change
263 // this to use the padding options it provides.
264 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
265 SLOGI("Signing safely-padded object");
266 break;
267 default:
268 SLOGE("Unknown KDF type %d", ftr->kdf_type);
269 return -1;
270 }
271
Shawn Willden47ba10d2014-09-03 17:07:06 -0600272 rc = keymaster_dev->sign_data(keymaster_dev,
273 &params,
274 ftr->keymaster_blob,
275 ftr->keymaster_blob_size,
276 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600277 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600278 signature,
279 signature_size);
280
Shawn Willdend1fd8462015-02-24 09:51:34 -0700281 keymaster0_close(keymaster_dev);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600282 return rc;
283}
284
Paul Lawrence399317e2014-03-10 13:20:50 -0700285/* Store password when userdata is successfully decrypted and mounted.
286 * Cleared by cryptfs_clear_password
287 *
288 * To avoid a double prompt at boot, we need to store the CryptKeeper
289 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
290 * Since the entire framework is torn down and rebuilt after encryption,
291 * we have to use a daemon or similar to store the password. Since vold
292 * is secured against IPC except from system processes, it seems a reasonable
293 * place to store this.
294 *
295 * password should be cleared once it has been used.
296 *
297 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800298 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700299static char* password = 0;
300static int password_expiry_time = 0;
301static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800302
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800303extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800304
Paul Lawrence87999172014-02-20 12:21:31 -0800305enum RebootType {reboot, recovery, shutdown};
306static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700307{
Paul Lawrence87999172014-02-20 12:21:31 -0800308 switch(rt) {
309 case reboot:
310 property_set(ANDROID_RB_PROPERTY, "reboot");
311 break;
312
313 case recovery:
314 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
315 break;
316
317 case shutdown:
318 property_set(ANDROID_RB_PROPERTY, "shutdown");
319 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700320 }
Paul Lawrence87999172014-02-20 12:21:31 -0800321
Ken Sumralladfba362013-06-04 16:37:52 -0700322 sleep(20);
323
324 /* Shouldn't get here, reboot should happen before sleep times out */
325 return;
326}
327
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800328static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
329{
330 memset(io, 0, dataSize);
331 io->data_size = dataSize;
332 io->data_start = sizeof(struct dm_ioctl);
333 io->version[0] = 4;
334 io->version[1] = 0;
335 io->version[2] = 0;
336 io->flags = flags;
337 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100338 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800339 }
340}
341
Kenny Rootc4c70f12013-06-14 12:11:38 -0700342/**
343 * Gets the default device scrypt parameters for key derivation time tuning.
344 * The parameters should lead to about one second derivation time for the
345 * given device.
346 */
347static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
348 const int default_params[] = SCRYPT_DEFAULTS;
349 int params[] = SCRYPT_DEFAULTS;
350 char paramstr[PROPERTY_VALUE_MAX];
351 char *token;
352 char *saveptr;
353 int i;
354
355 property_get(SCRYPT_PROP, paramstr, "");
356 if (paramstr[0] != '\0') {
357 /*
358 * The token we're looking for should be three integers separated by
359 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
360 */
Kenny Root2947e342013-08-14 15:54:49 -0700361 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
362 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700363 i++, token = strtok_r(NULL, ":", &saveptr)) {
364 char *endptr;
365 params[i] = strtol(token, &endptr, 10);
366
367 /*
368 * Check that there was a valid number and it's 8-bit. If not,
369 * break out and the end check will take the default values.
370 */
371 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
372 break;
373 }
374 }
375
376 /*
377 * If there were not enough tokens or a token was malformed (not an
378 * integer), it will end up here and the default parameters can be
379 * taken.
380 */
381 if ((i != 3) || (token != NULL)) {
382 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
383 memcpy(params, default_params, sizeof(params));
384 }
385 }
386
387 ftr->N_factor = params[0];
388 ftr->r_factor = params[1];
389 ftr->p_factor = params[2];
390}
391
Ken Sumrall3ed82362011-01-28 23:31:16 -0800392static unsigned int get_fs_size(char *dev)
393{
394 int fd, block_size;
395 struct ext4_super_block sb;
396 off64_t len;
397
398 if ((fd = open(dev, O_RDONLY)) < 0) {
399 SLOGE("Cannot open device to get filesystem size ");
400 return 0;
401 }
402
403 if (lseek64(fd, 1024, SEEK_SET) < 0) {
404 SLOGE("Cannot seek to superblock");
405 return 0;
406 }
407
408 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
409 SLOGE("Cannot read superblock");
410 return 0;
411 }
412
413 close(fd);
414
Daniel Rosenberge82df162014-08-15 22:19:23 +0000415 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
416 SLOGE("Not a valid ext4 superblock");
417 return 0;
418 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800419 block_size = 1024 << sb.s_log_block_size;
420 /* compute length in bytes */
421 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
422
423 /* return length in sectors */
424 return (unsigned int) (len / 512);
425}
426
Ken Sumrall160b4d62013-04-22 12:15:39 -0700427static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
428{
429 static int cached_data = 0;
430 static off64_t cached_off = 0;
431 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
432 int fd;
433 char key_loc[PROPERTY_VALUE_MAX];
434 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700435 int rc = -1;
436
437 if (!cached_data) {
438 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
439
440 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
441 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
442 SLOGE("Cannot open real block device %s\n", real_blkdev);
443 return -1;
444 }
445
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900446 unsigned long nr_sec = 0;
447 get_blkdev_size(fd, &nr_sec);
448 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700449 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
450 * encryption info footer and key, and plenty of bytes to spare for future
451 * growth.
452 */
453 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
454 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
455 cached_data = 1;
456 } else {
457 SLOGE("Cannot get size of block device %s\n", real_blkdev);
458 }
459 close(fd);
460 } else {
461 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
462 cached_off = 0;
463 cached_data = 1;
464 }
465 }
466
467 if (cached_data) {
468 if (metadata_fname) {
469 *metadata_fname = cached_metadata_fname;
470 }
471 if (off) {
472 *off = cached_off;
473 }
474 rc = 0;
475 }
476
477 return rc;
478}
479
Ken Sumralle8744072011-01-18 22:01:55 -0800480/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800481 * update the failed mount count but not change the key.
482 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700483static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800484{
485 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800486 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700487 /* starting_off is set to the SEEK_SET offset
488 * where the crypto structure starts
489 */
490 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800491 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700492 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700493 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800494
Ken Sumrall160b4d62013-04-22 12:15:39 -0700495 if (get_crypt_ftr_info(&fname, &starting_off)) {
496 SLOGE("Unable to get crypt_ftr_info\n");
497 return -1;
498 }
499 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700500 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700501 return -1;
502 }
Ken Sumralle550f782013-08-20 13:48:23 -0700503 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
504 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700505 return -1;
506 }
507
508 /* Seek to the start of the crypt footer */
509 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
510 SLOGE("Cannot seek to real block device footer\n");
511 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800512 }
513
514 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
515 SLOGE("Cannot write real block device footer\n");
516 goto errout;
517 }
518
Ken Sumrall3be890f2011-09-14 16:53:46 -0700519 fstat(fd, &statbuf);
520 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700521 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700522 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800523 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800524 goto errout;
525 }
526 }
527
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800528 /* Success! */
529 rc = 0;
530
531errout:
532 close(fd);
533 return rc;
534
535}
536
Ken Sumrall160b4d62013-04-22 12:15:39 -0700537static inline int unix_read(int fd, void* buff, int len)
538{
539 return TEMP_FAILURE_RETRY(read(fd, buff, len));
540}
541
542static inline int unix_write(int fd, const void* buff, int len)
543{
544 return TEMP_FAILURE_RETRY(write(fd, buff, len));
545}
546
547static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
548{
549 memset(pdata, 0, len);
550 pdata->persist_magic = PERSIST_DATA_MAGIC;
551 pdata->persist_valid_entries = 0;
552}
553
554/* A routine to update the passed in crypt_ftr to the lastest version.
555 * fd is open read/write on the device that holds the crypto footer and persistent
556 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
557 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
558 */
559static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
560{
Kenny Root7434b312013-06-14 11:29:53 -0700561 int orig_major = crypt_ftr->major_version;
562 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700563
Kenny Root7434b312013-06-14 11:29:53 -0700564 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
565 struct crypt_persist_data *pdata;
566 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700567
Kenny Rootc4c70f12013-06-14 12:11:38 -0700568 SLOGW("upgrading crypto footer to 1.1");
569
Kenny Root7434b312013-06-14 11:29:53 -0700570 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
571 if (pdata == NULL) {
572 SLOGE("Cannot allocate persisent data\n");
573 return;
574 }
575 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
576
577 /* Need to initialize the persistent data area */
578 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
579 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100580 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700581 return;
582 }
583 /* Write all zeros to the first copy, making it invalid */
584 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
585
586 /* Write a valid but empty structure to the second copy */
587 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
588 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
589
590 /* Update the footer */
591 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
592 crypt_ftr->persist_data_offset[0] = pdata_offset;
593 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
594 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100595 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700596 }
597
Paul Lawrencef4faa572014-01-29 13:31:03 -0800598 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700599 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800600 /* But keep the old kdf_type.
601 * It will get updated later to KDF_SCRYPT after the password has been verified.
602 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700603 crypt_ftr->kdf_type = KDF_PBKDF2;
604 get_device_scrypt_params(crypt_ftr);
605 crypt_ftr->minor_version = 2;
606 }
607
Paul Lawrencef4faa572014-01-29 13:31:03 -0800608 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
609 SLOGW("upgrading crypto footer to 1.3");
610 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
611 crypt_ftr->minor_version = 3;
612 }
613
Kenny Root7434b312013-06-14 11:29:53 -0700614 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
615 if (lseek64(fd, offset, SEEK_SET) == -1) {
616 SLOGE("Cannot seek to crypt footer\n");
617 return;
618 }
619 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700621}
622
623
624static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800625{
626 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800627 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700628 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800629 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700630 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700631 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800632
Ken Sumrall160b4d62013-04-22 12:15:39 -0700633 if (get_crypt_ftr_info(&fname, &starting_off)) {
634 SLOGE("Unable to get crypt_ftr_info\n");
635 return -1;
636 }
637 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700638 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700639 return -1;
640 }
641 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700642 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700643 return -1;
644 }
645
646 /* Make sure it's 16 Kbytes in length */
647 fstat(fd, &statbuf);
648 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
649 SLOGE("footer file %s is not the expected size!\n", fname);
650 goto errout;
651 }
652
653 /* Seek to the start of the crypt footer */
654 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
655 SLOGE("Cannot seek to real block device footer\n");
656 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800657 }
658
659 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
660 SLOGE("Cannot read real block device footer\n");
661 goto errout;
662 }
663
664 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700665 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800666 goto errout;
667 }
668
Kenny Rootc96a5f82013-06-14 12:08:28 -0700669 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
670 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
671 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800672 goto errout;
673 }
674
Kenny Rootc96a5f82013-06-14 12:08:28 -0700675 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
676 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
677 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800678 }
679
Ken Sumrall160b4d62013-04-22 12:15:39 -0700680 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
681 * copy on disk before returning.
682 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700683 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700684 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800685 }
686
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800687 /* Success! */
688 rc = 0;
689
690errout:
691 close(fd);
692 return rc;
693}
694
Ken Sumrall160b4d62013-04-22 12:15:39 -0700695static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
696{
697 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
698 crypt_ftr->persist_data_offset[1]) {
699 SLOGE("Crypt_ftr persist data regions overlap");
700 return -1;
701 }
702
703 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
704 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
705 return -1;
706 }
707
708 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
709 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
710 CRYPT_FOOTER_OFFSET) {
711 SLOGE("Persistent data extends past crypto footer");
712 return -1;
713 }
714
715 return 0;
716}
717
718static int load_persistent_data(void)
719{
720 struct crypt_mnt_ftr crypt_ftr;
721 struct crypt_persist_data *pdata = NULL;
722 char encrypted_state[PROPERTY_VALUE_MAX];
723 char *fname;
724 int found = 0;
725 int fd;
726 int ret;
727 int i;
728
729 if (persist_data) {
730 /* Nothing to do, we've already loaded or initialized it */
731 return 0;
732 }
733
734
735 /* If not encrypted, just allocate an empty table and initialize it */
736 property_get("ro.crypto.state", encrypted_state, "");
737 if (strcmp(encrypted_state, "encrypted") ) {
738 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
739 if (pdata) {
740 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
741 persist_data = pdata;
742 return 0;
743 }
744 return -1;
745 }
746
747 if(get_crypt_ftr_and_key(&crypt_ftr)) {
748 return -1;
749 }
750
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700751 if ((crypt_ftr.major_version < 1)
752 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700753 SLOGE("Crypt_ftr version doesn't support persistent data");
754 return -1;
755 }
756
757 if (get_crypt_ftr_info(&fname, NULL)) {
758 return -1;
759 }
760
761 ret = validate_persistent_data_storage(&crypt_ftr);
762 if (ret) {
763 return -1;
764 }
765
766 fd = open(fname, O_RDONLY);
767 if (fd < 0) {
768 SLOGE("Cannot open %s metadata file", fname);
769 return -1;
770 }
771
772 if (persist_data == NULL) {
773 pdata = malloc(crypt_ftr.persist_data_size);
774 if (pdata == NULL) {
775 SLOGE("Cannot allocate memory for persistent data");
776 goto err;
777 }
778 }
779
780 for (i = 0; i < 2; i++) {
781 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
782 SLOGE("Cannot seek to read persistent data on %s", fname);
783 goto err2;
784 }
785 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
786 SLOGE("Error reading persistent data on iteration %d", i);
787 goto err2;
788 }
789 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
790 found = 1;
791 break;
792 }
793 }
794
795 if (!found) {
796 SLOGI("Could not find valid persistent data, creating");
797 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
798 }
799
800 /* Success */
801 persist_data = pdata;
802 close(fd);
803 return 0;
804
805err2:
806 free(pdata);
807
808err:
809 close(fd);
810 return -1;
811}
812
813static int save_persistent_data(void)
814{
815 struct crypt_mnt_ftr crypt_ftr;
816 struct crypt_persist_data *pdata;
817 char *fname;
818 off64_t write_offset;
819 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700820 int fd;
821 int ret;
822
823 if (persist_data == NULL) {
824 SLOGE("No persistent data to save");
825 return -1;
826 }
827
828 if(get_crypt_ftr_and_key(&crypt_ftr)) {
829 return -1;
830 }
831
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700832 if ((crypt_ftr.major_version < 1)
833 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700834 SLOGE("Crypt_ftr version doesn't support persistent data");
835 return -1;
836 }
837
838 ret = validate_persistent_data_storage(&crypt_ftr);
839 if (ret) {
840 return -1;
841 }
842
843 if (get_crypt_ftr_info(&fname, NULL)) {
844 return -1;
845 }
846
847 fd = open(fname, O_RDWR);
848 if (fd < 0) {
849 SLOGE("Cannot open %s metadata file", fname);
850 return -1;
851 }
852
853 pdata = malloc(crypt_ftr.persist_data_size);
854 if (pdata == NULL) {
855 SLOGE("Cannot allocate persistant data");
856 goto err;
857 }
858
859 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
860 SLOGE("Cannot seek to read persistent data on %s", fname);
861 goto err2;
862 }
863
864 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
865 SLOGE("Error reading persistent data before save");
866 goto err2;
867 }
868
869 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
870 /* The first copy is the curent valid copy, so write to
871 * the second copy and erase this one */
872 write_offset = crypt_ftr.persist_data_offset[1];
873 erase_offset = crypt_ftr.persist_data_offset[0];
874 } else {
875 /* The second copy must be the valid copy, so write to
876 * the first copy, and erase the second */
877 write_offset = crypt_ftr.persist_data_offset[0];
878 erase_offset = crypt_ftr.persist_data_offset[1];
879 }
880
881 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100882 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700883 SLOGE("Cannot seek to write persistent data");
884 goto err2;
885 }
886 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
887 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100888 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700889 SLOGE("Cannot seek to erase previous persistent data");
890 goto err2;
891 }
892 fsync(fd);
893 memset(pdata, 0, crypt_ftr.persist_data_size);
894 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
895 (int) crypt_ftr.persist_data_size) {
896 SLOGE("Cannot write to erase previous persistent data");
897 goto err2;
898 }
899 fsync(fd);
900 } else {
901 SLOGE("Cannot write to save persistent data");
902 goto err2;
903 }
904
905 /* Success */
906 free(pdata);
907 close(fd);
908 return 0;
909
910err2:
911 free(pdata);
912err:
913 close(fd);
914 return -1;
915}
916
Paul Lawrencef4faa572014-01-29 13:31:03 -0800917static int hexdigit (char c)
918{
919 if (c >= '0' && c <= '9') return c - '0';
920 c = tolower(c);
921 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
922 return -1;
923}
924
925static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
926 unsigned int* out_keysize)
927{
928 unsigned int i;
929 *out_keysize = 0;
930
931 size_t size = strlen (master_key_ascii);
932 if (size % 2) {
933 SLOGE("Trying to convert ascii string of odd length");
934 return NULL;
935 }
936
937 unsigned char* master_key = (unsigned char*) malloc(size / 2);
938 if (master_key == 0) {
939 SLOGE("Cannot allocate");
940 return NULL;
941 }
942
943 for (i = 0; i < size; i += 2) {
944 int high_nibble = hexdigit (master_key_ascii[i]);
945 int low_nibble = hexdigit (master_key_ascii[i + 1]);
946
947 if(high_nibble < 0 || low_nibble < 0) {
948 SLOGE("Invalid hex string");
949 free (master_key);
950 return NULL;
951 }
952
953 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
954 (*out_keysize)++;
955 }
956
957 return master_key;
958}
959
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800960/* Convert a binary key of specified length into an ascii hex string equivalent,
961 * without the leading 0x and with null termination
962 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800963static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800964 char *master_key_ascii)
965{
966 unsigned int i, a;
967 unsigned char nibble;
968
969 for (i=0, a=0; i<keysize; i++, a+=2) {
970 /* For each byte, write out two ascii hex digits */
971 nibble = (master_key[i] >> 4) & 0xf;
972 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
973
974 nibble = master_key[i] & 0xf;
975 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
976 }
977
978 /* Add the null termination */
979 master_key_ascii[a] = '\0';
980
981}
982
Ken Sumralldb5e0262013-02-05 17:39:48 -0800983static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
984 char *real_blk_name, const char *name, int fd,
985 char *extra_params)
986{
Dan Albertc07fa3f2014-12-18 10:00:55 -0800987 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800988 struct dm_ioctl *io;
989 struct dm_target_spec *tgt;
990 char *crypt_params;
991 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
992 int i;
993
994 io = (struct dm_ioctl *) buffer;
995
996 /* Load the mapping table for this device */
997 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
998
999 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1000 io->target_count = 1;
1001 tgt->status = 0;
1002 tgt->sector_start = 0;
1003 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -07001004#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001005 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1006 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1007 }
1008 else {
1009 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1010 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001011#else
1012 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1013#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001014
1015 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1016 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1017 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1018 master_key_ascii, real_blk_name, extra_params);
1019 crypt_params += strlen(crypt_params) + 1;
1020 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1021 tgt->next = crypt_params - buffer;
1022
1023 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1024 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1025 break;
1026 }
1027 usleep(500000);
1028 }
1029
1030 if (i == TABLE_LOAD_RETRIES) {
1031 /* We failed to load the table, return an error */
1032 return -1;
1033 } else {
1034 return i + 1;
1035 }
1036}
1037
1038
1039static int get_dm_crypt_version(int fd, const char *name, int *version)
1040{
1041 char buffer[DM_CRYPT_BUF_SIZE];
1042 struct dm_ioctl *io;
1043 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001044
1045 io = (struct dm_ioctl *) buffer;
1046
1047 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1048
1049 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1050 return -1;
1051 }
1052
1053 /* Iterate over the returned versions, looking for name of "crypt".
1054 * When found, get and return the version.
1055 */
1056 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1057 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001058#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001059 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001060#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001061 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001062#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001063 /* We found the crypt driver, return the version, and get out */
1064 version[0] = v->version[0];
1065 version[1] = v->version[1];
1066 version[2] = v->version[2];
1067 return 0;
1068 }
1069 v = (struct dm_target_versions *)(((char *)v) + v->next);
1070 }
1071
1072 return -1;
1073}
1074
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001075static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001076 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001077{
1078 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001079 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001080 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001081 int fd=0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001082 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001083 int version[3];
1084 char *extra_params;
1085 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001086
1087 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1088 SLOGE("Cannot open device-mapper\n");
1089 goto errout;
1090 }
1091
1092 io = (struct dm_ioctl *) buffer;
1093
1094 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1095 if (ioctl(fd, DM_DEV_CREATE, io)) {
1096 SLOGE("Cannot create dm-crypt device\n");
1097 goto errout;
1098 }
1099
1100 /* Get the device status, in particular, the name of it's device file */
1101 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1102 if (ioctl(fd, DM_DEV_STATUS, io)) {
1103 SLOGE("Cannot retrieve dm-crypt device status\n");
1104 goto errout;
1105 }
1106 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1107 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1108
Ken Sumralldb5e0262013-02-05 17:39:48 -08001109 extra_params = "";
1110 if (! get_dm_crypt_version(fd, name, version)) {
1111 /* Support for allow_discards was added in version 1.11.0 */
1112 if ((version[0] >= 2) ||
1113 ((version[0] == 1) && (version[1] >= 11))) {
1114 extra_params = "1 allow_discards";
1115 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1116 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001117 }
1118
Ken Sumralldb5e0262013-02-05 17:39:48 -08001119 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1120 fd, extra_params);
1121 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001122 SLOGE("Cannot load dm-crypt mapping table.\n");
1123 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001124 } else if (load_count > 1) {
1125 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126 }
1127
1128 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001129 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001130
1131 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1132 SLOGE("Cannot resume the dm-crypt device\n");
1133 goto errout;
1134 }
1135
1136 /* We made it here with no errors. Woot! */
1137 retval = 0;
1138
1139errout:
1140 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1141
1142 return retval;
1143}
1144
Ken Sumrall29d8da82011-05-18 17:20:07 -07001145static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001146{
1147 int fd;
1148 char buffer[DM_CRYPT_BUF_SIZE];
1149 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001150 int retval = -1;
1151
1152 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1153 SLOGE("Cannot open device-mapper\n");
1154 goto errout;
1155 }
1156
1157 io = (struct dm_ioctl *) buffer;
1158
1159 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1160 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1161 SLOGE("Cannot remove dm-crypt device\n");
1162 goto errout;
1163 }
1164
1165 /* We made it here with no errors. Woot! */
1166 retval = 0;
1167
1168errout:
1169 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1170
1171 return retval;
1172
1173}
1174
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001175static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001176 unsigned char *ikey, void *params UNUSED)
1177{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001178 SLOGI("Using pbkdf2 for cryptfs KDF");
1179
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001180 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001181 unsigned int keysize;
1182 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1183 if (!master_key) return -1;
1184 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001185 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001186
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001187 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001188 free (master_key);
1189 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001190}
1191
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001192static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001193 unsigned char *ikey, void *params)
1194{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001195 SLOGI("Using scrypt for cryptfs KDF");
1196
Kenny Rootc4c70f12013-06-14 12:11:38 -07001197 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1198
1199 int N = 1 << ftr->N_factor;
1200 int r = 1 << ftr->r_factor;
1201 int p = 1 << ftr->p_factor;
1202
1203 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001204 unsigned int keysize;
1205 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1206 if (!master_key) return -1;
1207 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001208 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001209
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001210 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001211 free (master_key);
1212 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001213}
1214
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001215static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1216 unsigned char *ikey, void *params)
1217{
1218 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1219
1220 int rc;
1221 unsigned int key_size;
1222 size_t signature_size;
1223 unsigned char* signature;
1224 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1225
1226 int N = 1 << ftr->N_factor;
1227 int r = 1 << ftr->r_factor;
1228 int p = 1 << ftr->p_factor;
1229
1230 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1231 if (!master_key) {
1232 SLOGE("Failed to convert passwd from hex");
1233 return -1;
1234 }
1235
1236 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1237 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1238 memset(master_key, 0, key_size);
1239 free(master_key);
1240
1241 if (rc) {
1242 SLOGE("scrypt failed");
1243 return -1;
1244 }
1245
Shawn Willdene17a9c42014-09-08 13:04:08 -06001246 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1247 &signature, &signature_size)) {
1248 SLOGE("Signing failed");
1249 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001250 }
1251
1252 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1253 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1254 free(signature);
1255
1256 if (rc) {
1257 SLOGE("scrypt failed");
1258 return -1;
1259 }
1260
1261 return 0;
1262}
1263
1264static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1265 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001266 unsigned char *encrypted_master_key,
1267 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001268{
1269 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1270 EVP_CIPHER_CTX e_ctx;
1271 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001272 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001273
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001274 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001275 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001276
1277 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001278 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1279 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001280 case KDF_SCRYPT_KEYMASTER:
1281 if (keymaster_create_key(crypt_ftr)) {
1282 SLOGE("keymaster_create_key failed");
1283 return -1;
1284 }
1285
1286 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1287 SLOGE("scrypt failed");
1288 return -1;
1289 }
1290 break;
1291
1292 case KDF_SCRYPT:
1293 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1294 SLOGE("scrypt failed");
1295 return -1;
1296 }
1297 break;
1298
1299 default:
1300 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001301 return -1;
1302 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001303
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001304 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001305 EVP_CIPHER_CTX_init(&e_ctx);
1306 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001307 SLOGE("EVP_EncryptInit failed\n");
1308 return -1;
1309 }
1310 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001311
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001312 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001313 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence7053e9c2015-03-26 08:32:18 -07001314 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001315 SLOGE("EVP_EncryptUpdate failed\n");
1316 return -1;
1317 }
Adam Langley889c4f12014-09-03 14:23:13 -07001318 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001319 SLOGE("EVP_EncryptFinal failed\n");
1320 return -1;
1321 }
1322
1323 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1324 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1325 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001326 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001327
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001328 /* Store the scrypt of the intermediate key, so we can validate if it's a
1329 password error or mount error when things go wrong.
1330 Note there's no need to check for errors, since if this is incorrect, we
1331 simply won't wipe userdata, which is the correct default behavior
1332 */
1333 int N = 1 << crypt_ftr->N_factor;
1334 int r = 1 << crypt_ftr->r_factor;
1335 int p = 1 << crypt_ftr->p_factor;
1336
1337 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1338 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1339 crypt_ftr->scrypted_intermediate_key,
1340 sizeof(crypt_ftr->scrypted_intermediate_key));
1341
1342 if (rc) {
1343 SLOGE("encrypt_master_key: crypto_scrypt failed");
1344 }
1345
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001346 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001347}
1348
Paul Lawrence7053e9c2015-03-26 08:32:18 -07001349static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001350 unsigned char *encrypted_master_key,
1351 unsigned char *decrypted_master_key,
1352 kdf_func kdf, void *kdf_params,
1353 unsigned char** intermediate_key,
1354 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001355{
1356 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 -08001357 EVP_CIPHER_CTX d_ctx;
1358 int decrypted_len, final_len;
1359
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001360 /* Turn the password into an intermediate key and IV that can decrypt the
1361 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001362 if (kdf(passwd, salt, ikey, kdf_params)) {
1363 SLOGE("kdf failed");
1364 return -1;
1365 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001366
1367 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001368 EVP_CIPHER_CTX_init(&d_ctx);
1369 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001370 return -1;
1371 }
1372 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1373 /* Decrypt the master key */
1374 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1375 encrypted_master_key, KEY_LEN_BYTES)) {
1376 return -1;
1377 }
Adam Langley889c4f12014-09-03 14:23:13 -07001378 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001379 return -1;
1380 }
1381
1382 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1383 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001384 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001385
1386 /* Copy intermediate key if needed by params */
1387 if (intermediate_key && intermediate_key_size) {
1388 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1389 if (intermediate_key) {
1390 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1391 *intermediate_key_size = KEY_LEN_BYTES;
1392 }
1393 }
1394
1395 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001396}
1397
Kenny Rootc4c70f12013-06-14 12:11:38 -07001398static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001399{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001400 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1401 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1402 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001403 *kdf = scrypt_keymaster;
1404 *kdf_params = ftr;
1405 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001406 *kdf = scrypt;
1407 *kdf_params = ftr;
1408 } else {
1409 *kdf = pbkdf2;
1410 *kdf_params = NULL;
1411 }
1412}
1413
Paul Lawrence7053e9c2015-03-26 08:32:18 -07001414static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001415 struct crypt_mnt_ftr *crypt_ftr,
1416 unsigned char** intermediate_key,
1417 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001418{
1419 kdf_func kdf;
1420 void *kdf_params;
1421 int ret;
1422
1423 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001424 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1425 decrypted_master_key, kdf, kdf_params,
1426 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001427 if (ret != 0) {
1428 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001429 }
1430
1431 return ret;
1432}
1433
1434static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1435 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001436 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001437 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001438
1439 /* Get some random bits for a key */
1440 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001441 read(fd, key_buf, sizeof(key_buf));
1442 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001443 close(fd);
1444
1445 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001446 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001447}
1448
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001449static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001450{
Greg Hackmann955653e2014-09-24 14:55:20 -07001451 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001452#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001453
1454 /* Now umount the tmpfs filesystem */
1455 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001456 if (umount(mountpoint) == 0) {
1457 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001458 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001459
1460 if (errno == EINVAL) {
1461 /* EINVAL is returned if the directory is not a mountpoint,
1462 * i.e. there is no filesystem mounted there. So just get out.
1463 */
1464 break;
1465 }
1466
1467 err = errno;
1468
1469 /* If allowed, be increasingly aggressive before the last two retries */
1470 if (kill) {
1471 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1472 SLOGW("sending SIGHUP to processes with open files\n");
1473 vold_killProcessesWithOpenFiles(mountpoint, 1);
1474 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1475 SLOGW("sending SIGKILL to processes with open files\n");
1476 vold_killProcessesWithOpenFiles(mountpoint, 2);
1477 }
1478 }
1479
1480 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001481 }
1482
1483 if (i < WAIT_UNMOUNT_COUNT) {
1484 SLOGD("unmounting %s succeeded\n", mountpoint);
1485 rc = 0;
1486 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001487 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001488 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001489 rc = -1;
1490 }
1491
1492 return rc;
1493}
1494
Ken Sumrallc5872692013-05-14 15:26:31 -07001495#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001496static int prep_data_fs(void)
1497{
1498 int i;
1499
1500 /* Do the prep of the /data filesystem */
1501 property_set("vold.post_fs_data_done", "0");
1502 property_set("vold.decrypt", "trigger_post_fs_data");
1503 SLOGD("Just triggered post_fs_data\n");
1504
Ken Sumrallc5872692013-05-14 15:26:31 -07001505 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001506 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001507 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001508
1509 property_get("vold.post_fs_data_done", p, "0");
1510 if (*p == '1') {
1511 break;
1512 } else {
1513 usleep(250000);
1514 }
1515 }
1516 if (i == DATA_PREP_TIMEOUT) {
1517 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001518 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001519 return -1;
1520 } else {
1521 SLOGD("post_fs_data done\n");
1522 return 0;
1523 }
1524}
1525
Paul Lawrence74f29f12014-08-28 15:54:10 -07001526static void cryptfs_set_corrupt()
1527{
1528 // Mark the footer as bad
1529 struct crypt_mnt_ftr crypt_ftr;
1530 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1531 SLOGE("Failed to get crypto footer - panic");
1532 return;
1533 }
1534
1535 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1536 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1537 SLOGE("Failed to set crypto footer - panic");
1538 return;
1539 }
1540}
1541
1542static void cryptfs_trigger_restart_min_framework()
1543{
1544 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1545 SLOGE("Failed to mount tmpfs on data - panic");
1546 return;
1547 }
1548
1549 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1550 SLOGE("Failed to trigger post fs data - panic");
1551 return;
1552 }
1553
1554 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1555 SLOGE("Failed to trigger restart min framework - panic");
1556 return;
1557 }
1558}
1559
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001560/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001561static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001562{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001563 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001564 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001565 static int restart_successful = 0;
1566
1567 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001568 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001569 SLOGE("Encrypted filesystem not validated, aborting");
1570 return -1;
1571 }
1572
1573 if (restart_successful) {
1574 SLOGE("System already restarted with encrypted disk, aborting");
1575 return -1;
1576 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001577
Paul Lawrencef4faa572014-01-29 13:31:03 -08001578 if (restart_main) {
1579 /* Here is where we shut down the framework. The init scripts
1580 * start all services in one of three classes: core, main or late_start.
1581 * On boot, we start core and main. Now, we stop main, but not core,
1582 * as core includes vold and a few other really important things that
1583 * we need to keep running. Once main has stopped, we should be able
1584 * to umount the tmpfs /data, then mount the encrypted /data.
1585 * We then restart the class main, and also the class late_start.
1586 * At the moment, I've only put a few things in late_start that I know
1587 * are not needed to bring up the framework, and that also cause problems
1588 * with unmounting the tmpfs /data, but I hope to add add more services
1589 * to the late_start class as we optimize this to decrease the delay
1590 * till the user is asked for the password to the filesystem.
1591 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001592
Paul Lawrencef4faa572014-01-29 13:31:03 -08001593 /* The init files are setup to stop the class main when vold.decrypt is
1594 * set to trigger_reset_main.
1595 */
1596 property_set("vold.decrypt", "trigger_reset_main");
1597 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598
Paul Lawrencef4faa572014-01-29 13:31:03 -08001599 /* Ugh, shutting down the framework is not synchronous, so until it
1600 * can be fixed, this horrible hack will wait a moment for it all to
1601 * shut down before proceeding. Without it, some devices cannot
1602 * restart the graphics services.
1603 */
1604 sleep(2);
1605 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001606
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001607 /* Now that the framework is shutdown, we should be able to umount()
1608 * the tmpfs filesystem, and mount the real one.
1609 */
1610
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001611 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1612 if (strlen(crypto_blkdev) == 0) {
1613 SLOGE("fs_crypto_blkdev not set\n");
1614 return -1;
1615 }
1616
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001617 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001618 /* If ro.crypto.readonly is set to 1, mount the decrypted
1619 * filesystem readonly. This is used when /data is mounted by
1620 * recovery mode.
1621 */
1622 char ro_prop[PROPERTY_VALUE_MAX];
1623 property_get("ro.crypto.readonly", ro_prop, "");
1624 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1625 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1626 rec->flags |= MS_RDONLY;
1627 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001628
Ken Sumralle5032c42012-04-01 23:58:44 -07001629 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001630 int retries = RETRY_MOUNT_ATTEMPTS;
1631 int mount_rc;
1632 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1633 crypto_blkdev, 0))
1634 != 0) {
1635 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1636 /* TODO: invoke something similar to
1637 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1638 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1639 SLOGI("Failed to mount %s because it is busy - waiting",
1640 crypto_blkdev);
1641 if (--retries) {
1642 sleep(RETRY_MOUNT_DELAY_SECONDS);
1643 } else {
1644 /* Let's hope that a reboot clears away whatever is keeping
1645 the mount busy */
1646 cryptfs_reboot(reboot);
1647 }
1648 } else {
1649 SLOGE("Failed to mount decrypted data");
1650 cryptfs_set_corrupt();
1651 cryptfs_trigger_restart_min_framework();
1652 SLOGI("Started framework to offer wipe");
1653 return -1;
1654 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001655 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001656
Ken Sumralle5032c42012-04-01 23:58:44 -07001657 property_set("vold.decrypt", "trigger_load_persist_props");
1658 /* Create necessary paths on /data */
1659 if (prep_data_fs()) {
1660 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001661 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001662
1663 /* startup service classes main and late_start */
1664 property_set("vold.decrypt", "trigger_restart_framework");
1665 SLOGD("Just triggered restart_framework\n");
1666
1667 /* Give it a few moments to get started */
1668 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001669 }
1670
Ken Sumrall0cc16632011-01-18 20:32:26 -08001671 if (rc == 0) {
1672 restart_successful = 1;
1673 }
1674
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001675 return rc;
1676}
1677
Paul Lawrencef4faa572014-01-29 13:31:03 -08001678int cryptfs_restart(void)
1679{
Paul Lawrence8175a0b2015-03-05 09:46:23 -08001680 SLOGI("cryptfs_restart");
1681 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
1682 struct fstab_rec* rec;
1683 int rc;
1684
1685 if (e4crypt_restart(DATA_MNT_POINT)) {
1686 SLOGE("Can't unmount e4crypt temp volume\n");
1687 return -1;
1688 }
1689
1690 rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1691 if (!rec) {
1692 SLOGE("Can't get fstab record for %s\n", DATA_MNT_POINT);
1693 return -1;
1694 }
1695
1696 rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, rec->blk_device, 0);
1697 if (rc) {
1698 SLOGE("Can't mount %s\n", DATA_MNT_POINT);
1699 return rc;
1700 }
1701
1702 property_set("vold.decrypt", "trigger_restart_framework");
1703 return 0;
1704 }
1705
Paul Lawrencef4faa572014-01-29 13:31:03 -08001706 /* Call internal implementation forcing a restart of main service group */
1707 return cryptfs_restart_internal(1);
1708}
1709
Paul Lawrence8175a0b2015-03-05 09:46:23 -08001710static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001711{
1712 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001713 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001714 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001715
1716 property_get("ro.crypto.state", encrypted_state, "");
1717 if (strcmp(encrypted_state, "encrypted") ) {
1718 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001719 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001720 }
1721
Paul Lawrence8175a0b2015-03-05 09:46:23 -08001722 if (e4crypt_crypto_complete(mount_point) == 0) {
1723 return CRYPTO_COMPLETE_ENCRYPTED;
1724 }
1725
Ken Sumrall160b4d62013-04-22 12:15:39 -07001726 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001727 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001728
Ken Sumralle1a45852011-12-14 21:24:27 -08001729 /*
1730 * Only report this error if key_loc is a file and it exists.
1731 * If the device was never encrypted, and /data is not mountable for
1732 * some reason, returning 1 should prevent the UI from presenting the
1733 * a "enter password" screen, or worse, a "press button to wipe the
1734 * device" screen.
1735 */
1736 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1737 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001738 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001739 } else {
1740 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001741 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001742 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001743 }
1744
Paul Lawrence74f29f12014-08-28 15:54:10 -07001745 // Test for possible error flags
1746 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1747 SLOGE("Encryption process is partway completed\n");
1748 return CRYPTO_COMPLETE_PARTIAL;
1749 }
1750
1751 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1752 SLOGE("Encryption process was interrupted but cannot continue\n");
1753 return CRYPTO_COMPLETE_INCONSISTENT;
1754 }
1755
1756 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1757 SLOGE("Encryption is successful but data is corrupt\n");
1758 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001759 }
1760
1761 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001762 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001763}
1764
Paul Lawrencef4faa572014-01-29 13:31:03 -08001765static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1766 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001767{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001768 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001769 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001770 char crypto_blkdev[MAXPATHLEN];
1771 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001772 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001773 unsigned int orig_failed_decrypt_count;
1774 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001775 int use_keymaster = 0;
1776 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001777 unsigned char* intermediate_key = 0;
1778 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001779
Paul Lawrencef4faa572014-01-29 13:31:03 -08001780 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1781 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001782
Paul Lawrencef4faa572014-01-29 13:31:03 -08001783 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001784 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1785 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001786 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001787 rc = -1;
1788 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001789 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001790 }
1791
Paul Lawrencef4faa572014-01-29 13:31:03 -08001792 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1793
Ajay Dudani87701e22014-09-17 21:02:52 -07001794#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001795 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1796 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1797 SLOGE("Hardware encryption key does not match");
1798 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001799 }
1800#endif
1801
Paul Lawrence74f29f12014-08-28 15:54:10 -07001802 // Create crypto block device - all (non fatal) code paths
1803 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001804 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1805 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001806 SLOGE("Error creating decrypted block device\n");
1807 rc = -1;
1808 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001809 }
1810
Paul Lawrence74f29f12014-08-28 15:54:10 -07001811 /* Work out if the problem is the password or the data */
1812 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1813 scrypted_intermediate_key)];
1814 int N = 1 << crypt_ftr->N_factor;
1815 int r = 1 << crypt_ftr->r_factor;
1816 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001817
Paul Lawrence74f29f12014-08-28 15:54:10 -07001818 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1819 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1820 N, r, p, scrypted_intermediate_key,
1821 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001822
Paul Lawrence74f29f12014-08-28 15:54:10 -07001823 // Does the key match the crypto footer?
1824 if (rc == 0 && memcmp(scrypted_intermediate_key,
1825 crypt_ftr->scrypted_intermediate_key,
1826 sizeof(scrypted_intermediate_key)) == 0) {
1827 SLOGI("Password matches");
1828 rc = 0;
1829 } else {
1830 /* Try mounting the file system anyway, just in case the problem's with
1831 * the footer, not the key. */
1832 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1833 mkdir(tmp_mount_point, 0755);
1834 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1835 SLOGE("Error temp mounting decrypted block device\n");
1836 delete_crypto_blk_dev(label);
1837
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001838 rc = ++crypt_ftr->failed_decrypt_count;
1839 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001840 } else {
1841 /* Success! */
1842 SLOGI("Password did not match but decrypted drive mounted - continue");
1843 umount(tmp_mount_point);
1844 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001845 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001846 }
1847
1848 if (rc == 0) {
1849 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001850 if (orig_failed_decrypt_count != 0) {
1851 put_crypt_ftr_and_key(crypt_ftr);
1852 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001853
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001854 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001855 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001856 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001857
1858 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001859 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001860 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001861 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001862 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001863 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001864 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001865
Paul Lawrence74f29f12014-08-28 15:54:10 -07001866 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001867 use_keymaster = keymaster_check_compatibility();
1868 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001869 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001870 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1871 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1872 upgrade = 1;
1873 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001874 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001875 upgrade = 1;
1876 }
1877
1878 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001879 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1880 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001881 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001882 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001883 }
1884 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001885
1886 // Do not fail even if upgrade failed - machine is bootable
1887 // Note that if this code is ever hit, there is a *serious* problem
1888 // since KDFs should never fail. You *must* fix the kdf before
1889 // proceeding!
1890 if (rc) {
1891 SLOGW("Upgrade failed with error %d,"
1892 " but continuing with previous state",
1893 rc);
1894 rc = 0;
1895 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001896 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001897 }
1898
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001899 errout:
1900 if (intermediate_key) {
1901 memset(intermediate_key, 0, intermediate_key_size);
1902 free(intermediate_key);
1903 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001904 return rc;
1905}
1906
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001907/* Called by vold when it wants to undo the crypto mapping of a volume it
1908 * manages. This is usually in response to a factory reset, when we want
1909 * to undo the crypto mapping so the volume is formatted in the clear.
1910 */
1911int cryptfs_revert_volume(const char *label)
1912{
1913 return delete_crypto_blk_dev((char *)label);
1914}
1915
Ken Sumrall29d8da82011-05-18 17:20:07 -07001916/*
1917 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1918 * Setup a dm-crypt mapping, use the saved master key from
1919 * setting up the /data mapping, and return the new device path.
1920 */
1921int cryptfs_setup_volume(const char *label, int major, int minor,
1922 char *crypto_sys_path, unsigned int max_path,
1923 int *new_major, int *new_minor)
1924{
1925 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1926 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001927 struct stat statbuf;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001928
1929 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1930
Ken Sumrall160b4d62013-04-22 12:15:39 -07001931 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001932
1933 /* Update the fs_size field to be the size of the volume */
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001934 int fd = open(real_blkdev, O_RDONLY);
1935 if (fd == -1) {
1936 SLOGE("Cannot open volume %s\n", real_blkdev);
1937 return -1;
1938 }
1939
1940 unsigned long nr_sec = 0;
1941 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001942 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001943
Ken Sumrall29d8da82011-05-18 17:20:07 -07001944 if (nr_sec == 0) {
1945 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1946 return -1;
1947 }
1948
1949 sd_crypt_ftr.fs_size = nr_sec;
1950 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1951 crypto_blkdev, label);
1952
JP Abgrall3334c6a2014-10-10 15:52:11 -07001953 if (stat(crypto_blkdev, &statbuf) < 0) {
1954 SLOGE("Error get stat for crypto_blkdev %s. err=%d(%s)\n",
1955 crypto_blkdev, errno, strerror(errno));
1956 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001957 *new_major = MAJOR(statbuf.st_rdev);
1958 *new_minor = MINOR(statbuf.st_rdev);
1959
1960 /* Create path to sys entry for this block device */
1961 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1962
1963 return 0;
1964}
1965
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001966int cryptfs_crypto_complete(void)
1967{
1968 return do_crypto_complete("/data");
1969}
1970
Paul Lawrencef4faa572014-01-29 13:31:03 -08001971int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1972{
1973 char encrypted_state[PROPERTY_VALUE_MAX];
1974 property_get("ro.crypto.state", encrypted_state, "");
1975 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1976 SLOGE("encrypted fs already validated or not running with encryption,"
1977 " aborting");
1978 return -1;
1979 }
1980
1981 if (get_crypt_ftr_and_key(crypt_ftr)) {
1982 SLOGE("Error getting crypt footer and key");
1983 return -1;
1984 }
1985
1986 return 0;
1987}
1988
Paul Lawrencefc615042014-10-04 15:32:29 -07001989/*
1990 * TODO - transition patterns to new format in calling code
1991 * and remove this vile hack, and the use of hex in
1992 * the password passing code.
1993 *
1994 * Patterns are passed in zero based (i.e. the top left dot
1995 * is represented by zero, the top middle one etc), but we want
1996 * to store them '1' based.
1997 * This is to allow us to migrate the calling code to use this
1998 * convention. It also solves a nasty problem whereby scrypt ignores
1999 * trailing zeros, so patterns ending at the top left could be
2000 * truncated, and similarly, you could add the top left to any
2001 * pattern and still match.
2002 * adjust_passwd is a hack function that returns the alternate representation
2003 * if the password appears to be a pattern (hex numbers all less than 09)
2004 * If it succeeds we need to try both, and in particular try the alternate
2005 * first. If the original matches, then we need to update the footer
2006 * with the alternate.
2007 * All code that accepts passwords must adjust them first. Since
2008 * cryptfs_check_passwd is always the first function called after a migration
2009 * (and indeed on any boot) we only need to do the double try in this
2010 * function.
2011 */
2012char* adjust_passwd(const char* passwd)
2013{
2014 size_t index, length;
2015
2016 if (!passwd) {
2017 return 0;
2018 }
2019
2020 // Check even length. Hex encoded passwords are always
2021 // an even length, since each character encodes to two characters.
2022 length = strlen(passwd);
2023 if (length % 2) {
2024 SLOGW("Password not correctly hex encoded.");
2025 return 0;
2026 }
2027
2028 // Check password is old-style pattern - a collection of hex
2029 // encoded bytes less than 9 (00 through 08)
2030 for (index = 0; index < length; index +=2) {
2031 if (passwd[index] != '0'
2032 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
2033 return 0;
2034 }
2035 }
2036
2037 // Allocate room for adjusted passwd and null terminate
2038 char* adjusted = malloc(length + 1);
2039 adjusted[length] = 0;
2040
2041 // Add 0x31 ('1') to each character
2042 for (index = 0; index < length; index += 2) {
2043 // output is 31 through 39 so set first byte to three, second to src + 1
2044 adjusted[index] = '3';
2045 adjusted[index + 1] = passwd[index + 1] + 1;
2046 }
2047
2048 return adjusted;
2049}
2050
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002051int cryptfs_check_passwd(char *passwd)
2052{
Paul Lawrence8175a0b2015-03-05 09:46:23 -08002053 SLOGI("cryptfs_check_passwd");
2054 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
2055 return e4crypt_check_passwd(DATA_MNT_POINT, passwd);
2056 }
2057
Paul Lawrencef4faa572014-01-29 13:31:03 -08002058 struct crypt_mnt_ftr crypt_ftr;
2059 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002060
Paul Lawrencef4faa572014-01-29 13:31:03 -08002061 rc = check_unmounted_and_get_ftr(&crypt_ftr);
2062 if (rc)
2063 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002064
Paul Lawrencefc615042014-10-04 15:32:29 -07002065 char* adjusted_passwd = adjust_passwd(passwd);
2066 if (adjusted_passwd) {
2067 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
2068 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
2069 DATA_MNT_POINT, "userdata");
2070
2071 // Maybe the original one still works?
2072 if (rc) {
2073 // Don't double count this failure
2074 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
2075 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2076 DATA_MNT_POINT, "userdata");
2077 if (!rc) {
2078 // cryptfs_changepw also adjusts so pass original
2079 // Note that adjust_passwd only recognises patterns
2080 // so we can safely use CRYPT_TYPE_PATTERN
2081 SLOGI("Updating pattern to new format");
2082 cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
2083 }
2084 }
2085 free(adjusted_passwd);
2086 } else {
2087 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2088 DATA_MNT_POINT, "userdata");
2089 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002090
2091 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002092 cryptfs_clear_password();
2093 password = strdup(passwd);
2094 struct timespec now;
2095 clock_gettime(CLOCK_BOOTTIME, &now);
2096 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002097 }
2098
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002099 return rc;
2100}
2101
Ken Sumrall3ad90722011-10-04 20:38:29 -07002102int cryptfs_verify_passwd(char *passwd)
2103{
2104 struct crypt_mnt_ftr crypt_ftr;
2105 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002106 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002107 char encrypted_state[PROPERTY_VALUE_MAX];
2108 int rc;
2109
2110 property_get("ro.crypto.state", encrypted_state, "");
2111 if (strcmp(encrypted_state, "encrypted") ) {
2112 SLOGE("device not encrypted, aborting");
2113 return -2;
2114 }
2115
2116 if (!master_key_saved) {
2117 SLOGE("encrypted fs not yet mounted, aborting");
2118 return -1;
2119 }
2120
2121 if (!saved_mount_point) {
2122 SLOGE("encrypted fs failed to save mount point, aborting");
2123 return -1;
2124 }
2125
Ken Sumrall160b4d62013-04-22 12:15:39 -07002126 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002127 SLOGE("Error getting crypt footer and key\n");
2128 return -1;
2129 }
2130
2131 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2132 /* If the device has no password, then just say the password is valid */
2133 rc = 0;
2134 } else {
Paul Lawrencefc615042014-10-04 15:32:29 -07002135 char* adjusted_passwd = adjust_passwd(passwd);
2136 if (adjusted_passwd) {
2137 passwd = adjusted_passwd;
2138 }
2139
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002140 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002141 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2142 /* They match, the password is correct */
2143 rc = 0;
2144 } else {
2145 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2146 sleep(1);
2147 rc = 1;
2148 }
Paul Lawrencefc615042014-10-04 15:32:29 -07002149
2150 free(adjusted_passwd);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002151 }
2152
2153 return rc;
2154}
2155
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002156/* Initialize a crypt_mnt_ftr structure. The keysize is
2157 * defaulted to 16 bytes, and the filesystem size to 0.
2158 * Presumably, at a minimum, the caller will update the
2159 * filesystem size and crypto_type_name after calling this function.
2160 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002161static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002162{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002163 off64_t off;
2164
2165 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002166 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002167 ftr->major_version = CURRENT_MAJOR_VERSION;
2168 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002169 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002170 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002171
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002172 switch (keymaster_check_compatibility()) {
2173 case 1:
2174 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2175 break;
2176
2177 case 0:
2178 ftr->kdf_type = KDF_SCRYPT;
2179 break;
2180
2181 default:
2182 SLOGE("keymaster_check_compatibility failed");
2183 return -1;
2184 }
2185
Kenny Rootc4c70f12013-06-14 12:11:38 -07002186 get_device_scrypt_params(ftr);
2187
Ken Sumrall160b4d62013-04-22 12:15:39 -07002188 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2189 if (get_crypt_ftr_info(NULL, &off) == 0) {
2190 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2191 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2192 ftr->persist_data_size;
2193 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002194
2195 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002196}
2197
Ken Sumrall29d8da82011-05-18 17:20:07 -07002198static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002199{
Ken Sumralle550f782013-08-20 13:48:23 -07002200 const char *args[10];
2201 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2202 int num_args;
2203 int status;
2204 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002205 int rc = -1;
2206
Ken Sumrall29d8da82011-05-18 17:20:07 -07002207 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002208 args[0] = "/system/bin/make_ext4fs";
2209 args[1] = "-a";
2210 args[2] = "/data";
2211 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002212 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002213 args[4] = size_str;
2214 args[5] = crypto_blkdev;
2215 num_args = 6;
2216 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2217 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002218 } else if (type == F2FS_FS) {
2219 args[0] = "/system/bin/mkfs.f2fs";
2220 args[1] = "-t";
2221 args[2] = "-d1";
2222 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002223 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002224 args[4] = size_str;
2225 num_args = 5;
2226 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2227 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002228 } else {
2229 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2230 return -1;
2231 }
2232
Ken Sumralle550f782013-08-20 13:48:23 -07002233 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2234
2235 if (tmp != 0) {
2236 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002237 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002238 if (WIFEXITED(status)) {
2239 if (WEXITSTATUS(status)) {
2240 SLOGE("Error creating filesystem on %s, exit status %d ",
2241 crypto_blkdev, WEXITSTATUS(status));
2242 } else {
2243 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2244 rc = 0;
2245 }
2246 } else {
2247 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2248 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002249 }
2250
2251 return rc;
2252}
2253
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002254#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002255#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2256#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002257
2258/* aligned 32K writes tends to make flash happy.
2259 * SD card association recommends it.
2260 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002261#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002262#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002263#else
2264#define BLOCKS_AT_A_TIME 1024
2265#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002266
2267struct encryptGroupsData
2268{
2269 int realfd;
2270 int cryptofd;
2271 off64_t numblocks;
2272 off64_t one_pct, cur_pct, new_pct;
2273 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002274 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002275 char* real_blkdev, * crypto_blkdev;
2276 int count;
2277 off64_t offset;
2278 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002279 off64_t last_written_sector;
2280 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002281 time_t time_started;
2282 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002283};
2284
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002285static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002286{
2287 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002288
2289 if (is_used) {
2290 data->used_blocks_already_done++;
2291 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002292 if (data->tot_used_blocks) {
2293 data->new_pct = data->used_blocks_already_done / data->one_pct;
2294 } else {
2295 data->new_pct = data->blocks_already_done / data->one_pct;
2296 }
2297
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002298 if (data->new_pct > data->cur_pct) {
2299 char buf[8];
2300 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002301 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002302 property_set("vold.encrypt_progress", buf);
2303 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002304
2305 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002306 struct timespec time_now;
2307 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2308 SLOGW("Error getting time");
2309 } else {
2310 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2311 off64_t remaining_blocks = data->tot_used_blocks
2312 - data->used_blocks_already_done;
2313 int remaining_time = (int)(elapsed_time * remaining_blocks
2314 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002315
Paul Lawrence9c58a872014-09-30 09:12:51 -07002316 // Change time only if not yet set, lower, or a lot higher for
2317 // best user experience
2318 if (data->remaining_time == -1
2319 || remaining_time < data->remaining_time
2320 || remaining_time > data->remaining_time + 60) {
2321 char buf[8];
2322 snprintf(buf, sizeof(buf), "%d", remaining_time);
2323 property_set("vold.encrypt_time_remaining", buf);
2324 data->remaining_time = remaining_time;
2325 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002326 }
2327 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002328}
2329
Paul Lawrence3846be12014-09-22 11:33:54 -07002330static void log_progress(struct encryptGroupsData const* data, bool completed)
2331{
2332 // Precondition - if completed data = 0 else data != 0
2333
2334 // Track progress so we can skip logging blocks
2335 static off64_t offset = -1;
2336
2337 // Need to close existing 'Encrypting from' log?
2338 if (completed || (offset != -1 && data->offset != offset)) {
2339 SLOGI("Encrypted to sector %" PRId64,
2340 offset / info.block_size * CRYPT_SECTOR_SIZE);
2341 offset = -1;
2342 }
2343
2344 // Need to start new 'Encrypting from' log?
2345 if (!completed && offset != data->offset) {
2346 SLOGI("Encrypting from sector %" PRId64,
2347 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2348 }
2349
2350 // Update offset
2351 if (!completed) {
2352 offset = data->offset + (off64_t)data->count * info.block_size;
2353 }
2354}
2355
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002356static int flush_outstanding_data(struct encryptGroupsData* data)
2357{
2358 if (data->count == 0) {
2359 return 0;
2360 }
2361
Elliott Hughes231bdba2014-06-25 18:36:19 -07002362 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002363
2364 if (pread64(data->realfd, data->buffer,
2365 info.block_size * data->count, data->offset)
2366 <= 0) {
2367 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2368 data->real_blkdev);
2369 return -1;
2370 }
2371
2372 if (pwrite64(data->cryptofd, data->buffer,
2373 info.block_size * data->count, data->offset)
2374 <= 0) {
2375 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2376 data->crypto_blkdev);
2377 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002378 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002379 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002380 }
2381
2382 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002383 data->last_written_sector = (data->offset + data->count)
2384 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002385 return 0;
2386}
2387
2388static int encrypt_groups(struct encryptGroupsData* data)
2389{
2390 unsigned int i;
2391 u8 *block_bitmap = 0;
2392 unsigned int block;
2393 off64_t ret;
2394 int rc = -1;
2395
2396 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2397 if (!data->buffer) {
2398 SLOGE("Failed to allocate crypto buffer");
2399 goto errout;
2400 }
2401
2402 block_bitmap = malloc(info.block_size);
2403 if (!block_bitmap) {
2404 SLOGE("failed to allocate block bitmap");
2405 goto errout;
2406 }
2407
2408 for (i = 0; i < aux_info.groups; ++i) {
2409 SLOGI("Encrypting group %d", i);
2410
2411 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2412 u32 block_count = min(info.blocks_per_group,
2413 aux_info.len_blocks - first_block);
2414
2415 off64_t offset = (u64)info.block_size
2416 * aux_info.bg_desc[i].bg_block_bitmap;
2417
2418 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2419 if (ret != (int)info.block_size) {
2420 SLOGE("failed to read all of block group bitmap %d", i);
2421 goto errout;
2422 }
2423
2424 offset = (u64)info.block_size * first_block;
2425
2426 data->count = 0;
2427
2428 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002429 int used = bitmap_get_bit(block_bitmap, block);
2430 update_progress(data, used);
2431 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002432 if (data->count == 0) {
2433 data->offset = offset;
2434 }
2435 data->count++;
2436 } else {
2437 if (flush_outstanding_data(data)) {
2438 goto errout;
2439 }
2440 }
2441
2442 offset += info.block_size;
2443
2444 /* Write data if we are aligned or buffer size reached */
2445 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2446 || data->count == BLOCKS_AT_A_TIME) {
2447 if (flush_outstanding_data(data)) {
2448 goto errout;
2449 }
2450 }
Paul Lawrence87999172014-02-20 12:21:31 -08002451
Paul Lawrence73d7a022014-06-09 14:10:09 -07002452 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002453 SLOGE("Stopping encryption due to low battery");
2454 rc = 0;
2455 goto errout;
2456 }
2457
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002458 }
2459 if (flush_outstanding_data(data)) {
2460 goto errout;
2461 }
2462 }
2463
Paul Lawrence87999172014-02-20 12:21:31 -08002464 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002465 rc = 0;
2466
2467errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002468 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002469 free(data->buffer);
2470 free(block_bitmap);
2471 return rc;
2472}
2473
2474static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2475 char *real_blkdev,
2476 off64_t size,
2477 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002478 off64_t tot_size,
2479 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002480{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002481 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002482 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002483 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002484
Paul Lawrence87999172014-02-20 12:21:31 -08002485 if (previously_encrypted_upto > *size_already_done) {
2486 SLOGD("Not fast encrypting since resuming part way through");
2487 return -1;
2488 }
2489
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002490 memset(&data, 0, sizeof(data));
2491 data.real_blkdev = real_blkdev;
2492 data.crypto_blkdev = crypto_blkdev;
2493
2494 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002495 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2496 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002497 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002498 goto errout;
2499 }
2500
2501 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002502 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002503 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002504 rc = ENABLE_INPLACE_ERR_DEV;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002505 goto errout;
2506 }
2507
2508 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002509 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002510 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002511 goto errout;
2512 }
2513
2514 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002515 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002516 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002517 goto errout;
2518 }
2519
2520 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2521 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2522 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2523
JP Abgrall7fc1de82014-10-10 18:43:41 -07002524 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002525
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002526 data.tot_used_blocks = data.numblocks;
2527 for (i = 0; i < aux_info.groups; ++i) {
2528 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2529 }
2530
2531 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002532 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002533
2534 struct timespec time_started = {0};
2535 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2536 SLOGW("Error getting time at start");
2537 // Note - continue anyway - we'll run with 0
2538 }
2539 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002540 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002541
2542 rc = encrypt_groups(&data);
2543 if (rc) {
2544 SLOGE("Error encrypting groups");
2545 goto errout;
2546 }
2547
Paul Lawrence87999172014-02-20 12:21:31 -08002548 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002549 rc = 0;
2550
2551errout:
2552 close(data.realfd);
2553 close(data.cryptofd);
2554
2555 return rc;
2556}
2557
Paul Lawrence3846be12014-09-22 11:33:54 -07002558static void log_progress_f2fs(u64 block, bool completed)
2559{
2560 // Precondition - if completed data = 0 else data != 0
2561
2562 // Track progress so we can skip logging blocks
2563 static u64 last_block = (u64)-1;
2564
2565 // Need to close existing 'Encrypting from' log?
2566 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2567 SLOGI("Encrypted to block %" PRId64, last_block);
2568 last_block = -1;
2569 }
2570
2571 // Need to start new 'Encrypting from' log?
2572 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2573 SLOGI("Encrypting from block %" PRId64, block);
2574 }
2575
2576 // Update offset
2577 if (!completed) {
2578 last_block = block;
2579 }
2580}
2581
Daniel Rosenberge82df162014-08-15 22:19:23 +00002582static int encrypt_one_block_f2fs(u64 pos, void *data)
2583{
2584 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2585
2586 priv_dat->blocks_already_done = pos - 1;
2587 update_progress(priv_dat, 1);
2588
2589 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2590
2591 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002592 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002593 return -1;
2594 }
2595
2596 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002597 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002598 return -1;
2599 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002600 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002601 }
2602
2603 return 0;
2604}
2605
2606static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2607 char *real_blkdev,
2608 off64_t size,
2609 off64_t *size_already_done,
2610 off64_t tot_size,
2611 off64_t previously_encrypted_upto)
2612{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002613 struct encryptGroupsData data;
2614 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002615 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002616 if (previously_encrypted_upto > *size_already_done) {
2617 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002618 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002619 }
2620 memset(&data, 0, sizeof(data));
2621 data.real_blkdev = real_blkdev;
2622 data.crypto_blkdev = crypto_blkdev;
2623 data.realfd = -1;
2624 data.cryptofd = -1;
2625 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002626 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002627 real_blkdev);
2628 goto errout;
2629 }
2630 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002631 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002632 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002633 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002634 goto errout;
2635 }
2636
2637 f2fs_info = generate_f2fs_info(data.realfd);
2638 if (!f2fs_info)
2639 goto errout;
2640
2641 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2642 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2643 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2644
2645 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2646
2647 data.one_pct = data.tot_used_blocks / 100;
2648 data.cur_pct = 0;
2649 data.time_started = time(NULL);
2650 data.remaining_time = -1;
2651
2652 data.buffer = malloc(f2fs_info->block_size);
2653 if (!data.buffer) {
2654 SLOGE("Failed to allocate crypto buffer");
2655 goto errout;
2656 }
2657
2658 data.count = 0;
2659
2660 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2661 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2662
2663 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002664 SLOGE("Error in running over f2fs blocks");
2665 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002666 goto errout;
2667 }
2668
2669 *size_already_done += size;
2670 rc = 0;
2671
2672errout:
2673 if (rc)
2674 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2675
Paul Lawrence3846be12014-09-22 11:33:54 -07002676 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002677 free(f2fs_info);
2678 free(data.buffer);
2679 close(data.realfd);
2680 close(data.cryptofd);
2681
2682 return rc;
2683}
2684
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002685static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2686 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002687 off64_t tot_size,
2688 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002689{
2690 int realfd, cryptofd;
2691 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002692 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002693 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002694 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002695 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002696
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002697 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2698 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002699 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002700 }
2701
2702 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002703 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2704 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002705 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002706 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002707 }
2708
2709 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2710 * The size passed in is the number of 512 byte sectors in the filesystem.
2711 * So compute the number of whole 4K blocks we should read/write,
2712 * and the remainder.
2713 */
2714 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2715 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002716 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2717 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002718
2719 SLOGE("Encrypting filesystem in place...");
2720
Paul Lawrence87999172014-02-20 12:21:31 -08002721 i = previously_encrypted_upto + 1 - *size_already_done;
2722
2723 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2724 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2725 goto errout;
2726 }
2727
2728 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2729 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2730 goto errout;
2731 }
2732
2733 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2734 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2735 SLOGE("Error reading initial sectors from real_blkdev %s for "
2736 "inplace encrypt\n", crypto_blkdev);
2737 goto errout;
2738 }
2739 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2740 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2741 "inplace encrypt\n", crypto_blkdev);
2742 goto errout;
2743 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002744 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002745 }
2746 }
2747
Ken Sumrall29d8da82011-05-18 17:20:07 -07002748 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002749 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002750 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002751 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002752 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002753 if (new_pct > cur_pct) {
2754 char buf[8];
2755
2756 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002757 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002758 property_set("vold.encrypt_progress", buf);
2759 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002760 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002761 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002762 goto errout;
2763 }
2764 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002765 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2766 goto errout;
2767 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002768 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002769 CRYPT_SECTORS_PER_BUFSIZE,
2770 i * CRYPT_SECTORS_PER_BUFSIZE);
2771 }
2772
Paul Lawrence73d7a022014-06-09 14:10:09 -07002773 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002774 SLOGE("Stopping encryption due to low battery");
2775 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2776 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002777 goto errout;
2778 }
2779 }
2780
2781 /* Do any remaining sectors */
2782 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002783 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2784 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002785 goto errout;
2786 }
Paul Lawrence87999172014-02-20 12:21:31 -08002787 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2788 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002789 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002790 } else {
2791 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002792 }
2793 }
2794
Ken Sumrall29d8da82011-05-18 17:20:07 -07002795 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002796 rc = 0;
2797
2798errout:
2799 close(realfd);
2800 close(cryptofd);
2801
2802 return rc;
2803}
2804
JP Abgrall7fc1de82014-10-10 18:43:41 -07002805/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002806static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2807 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002808 off64_t tot_size,
2809 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002810{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002811 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002812 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002813 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002814 }
2815
2816 if (*size_already_done + size < previously_encrypted_upto) {
2817 *size_already_done += size;
2818 return 0;
2819 }
2820
Daniel Rosenberge82df162014-08-15 22:19:23 +00002821 /* TODO: identify filesystem type.
2822 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2823 * then we will drop down to cryptfs_enable_inplace_f2fs.
2824 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002825 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002826 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002827 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002828 return 0;
2829 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002830 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002831
JP Abgrall7fc1de82014-10-10 18:43:41 -07002832 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002833 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002834 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002835 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002836 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002837 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002838
JP Abgrall7fc1de82014-10-10 18:43:41 -07002839 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002840 size, size_already_done, tot_size,
2841 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002842 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2843
2844 /* Hack for b/17898962, the following is the symptom... */
2845 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2846 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2847 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2848 return ENABLE_INPLACE_ERR_DEV;
2849 }
2850 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002851}
2852
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002853#define CRYPTO_ENABLE_WIPE 1
2854#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002855
2856#define FRAMEWORK_BOOT_WAIT 60
2857
Ken Sumrall29d8da82011-05-18 17:20:07 -07002858static inline int should_encrypt(struct volume_info *volume)
2859{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002860 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002861 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2862}
2863
Paul Lawrence87999172014-02-20 12:21:31 -08002864static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2865{
2866 int fd = open(filename, O_RDONLY);
2867 if (fd == -1) {
2868 SLOGE("Error opening file %s", filename);
2869 return -1;
2870 }
2871
2872 char block[CRYPT_INPLACE_BUFSIZE];
2873 memset(block, 0, sizeof(block));
2874 if (unix_read(fd, block, sizeof(block)) < 0) {
2875 SLOGE("Error reading file %s", filename);
2876 close(fd);
2877 return -1;
2878 }
2879
2880 close(fd);
2881
2882 SHA256_CTX c;
2883 SHA256_Init(&c);
2884 SHA256_Update(&c, block, sizeof(block));
2885 SHA256_Final(buf, &c);
2886
2887 return 0;
2888}
2889
JP Abgrall62c7af32014-06-16 13:01:23 -07002890static int get_fs_type(struct fstab_rec *rec)
2891{
2892 if (!strcmp(rec->fs_type, "ext4")) {
2893 return EXT4_FS;
2894 } else if (!strcmp(rec->fs_type, "f2fs")) {
2895 return F2FS_FS;
2896 } else {
2897 return -1;
2898 }
2899}
2900
Paul Lawrence87999172014-02-20 12:21:31 -08002901static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2902 char *crypto_blkdev, char *real_blkdev,
2903 int previously_encrypted_upto)
2904{
2905 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002906 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002907
Paul Lawrence73d7a022014-06-09 14:10:09 -07002908 if (!is_battery_ok_to_start()) {
2909 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002910 return 0;
2911 }
2912
2913 /* The size of the userdata partition, and add in the vold volumes below */
2914 tot_encryption_size = crypt_ftr->fs_size;
2915
2916 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002917 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2918 int fs_type = get_fs_type(rec);
2919 if (fs_type < 0) {
2920 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2921 return -1;
2922 }
2923 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002924 } else if (how == CRYPTO_ENABLE_INPLACE) {
2925 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2926 crypt_ftr->fs_size, &cur_encryption_done,
2927 tot_encryption_size,
2928 previously_encrypted_upto);
2929
JP Abgrall7fc1de82014-10-10 18:43:41 -07002930 if (rc == ENABLE_INPLACE_ERR_DEV) {
2931 /* Hack for b/17898962 */
2932 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2933 cryptfs_reboot(reboot);
2934 }
2935
Paul Lawrence73d7a022014-06-09 14:10:09 -07002936 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002937 crypt_ftr->encrypted_upto = cur_encryption_done;
2938 }
2939
Paul Lawrence73d7a022014-06-09 14:10:09 -07002940 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002941 /* The inplace routine never actually sets the progress to 100% due
2942 * to the round down nature of integer division, so set it here */
2943 property_set("vold.encrypt_progress", "100");
2944 }
2945 } else {
2946 /* Shouldn't happen */
2947 SLOGE("cryptfs_enable: internal error, unknown option\n");
2948 rc = -1;
2949 }
2950
2951 return rc;
2952}
2953
Paul Lawrence13486032014-02-03 13:28:11 -08002954int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2955 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002956{
2957 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002958 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002959 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002960 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002961 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002962 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002963 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002964 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002965 char key_loc[PROPERTY_VALUE_MAX];
2966 char fuse_sdcard[PROPERTY_VALUE_MAX];
2967 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002968 int num_vols;
2969 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002970 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002971
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002972 if (!strcmp(howarg, "wipe")) {
2973 how = CRYPTO_ENABLE_WIPE;
2974 } else if (! strcmp(howarg, "inplace")) {
2975 how = CRYPTO_ENABLE_INPLACE;
2976 } else {
2977 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002978 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002979 }
2980
Paul Lawrence87999172014-02-20 12:21:31 -08002981 /* See if an encryption was underway and interrupted */
2982 if (how == CRYPTO_ENABLE_INPLACE
2983 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2984 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2985 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2986 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002987 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2988
2989 /* At this point, we are in an inconsistent state. Until we successfully
2990 complete encryption, a reboot will leave us broken. So mark the
2991 encryption failed in case that happens.
2992 On successfully completing encryption, remove this flag */
2993 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2994
2995 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002996 }
2997
2998 property_get("ro.crypto.state", encrypted_state, "");
2999 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
3000 SLOGE("Device is already running encrypted, aborting");
3001 goto error_unencrypted;
3002 }
3003
3004 // TODO refactor fs_mgr_get_crypt_info to get both in one call
3005 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08003006 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003007
Ken Sumrall3ed82362011-01-28 23:31:16 -08003008 /* Get the size of the real block device */
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09003009 int fd = open(real_blkdev, O_RDONLY);
3010 if (fd == -1) {
3011 SLOGE("Cannot open block device %s\n", real_blkdev);
3012 goto error_unencrypted;
3013 }
3014 unsigned long nr_sec;
3015 get_blkdev_size(fd, &nr_sec);
3016 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003017 SLOGE("Cannot get size of block device %s\n", real_blkdev);
3018 goto error_unencrypted;
3019 }
3020 close(fd);
3021
3022 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003023 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003024 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00003025 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00003026 if (fs_size_sec == 0)
3027 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3028
Paul Lawrence87999172014-02-20 12:21:31 -08003029 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003030
3031 if (fs_size_sec > max_fs_size_sec) {
3032 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3033 goto error_unencrypted;
3034 }
3035 }
3036
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003037 /* Get a wakelock as this may take a while, and we don't want the
3038 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3039 * wants to keep the screen on, it can grab a full wakelock.
3040 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003041 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003042 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3043
Jeff Sharkey7382f812012-08-23 14:08:59 -07003044 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07003045 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07003046 if (!sd_mnt_point) {
3047 sd_mnt_point = getenv("EXTERNAL_STORAGE");
3048 }
3049 if (!sd_mnt_point) {
3050 sd_mnt_point = "/mnt/sdcard";
3051 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07003052
Paul Lawrence87999172014-02-20 12:21:31 -08003053 /* TODO
3054 * Currently do not have test devices with multiple encryptable volumes.
3055 * When we acquire some, re-add support.
3056 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003057 num_vols=vold_getNumDirectVolumes();
3058 vol_list = malloc(sizeof(struct volume_info) * num_vols);
3059 vold_getDirectVolumeList(vol_list);
3060
3061 for (i=0; i<num_vols; i++) {
3062 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08003063 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
3064 "%s\n", vol_list[i].label);
3065 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003066 }
3067 }
3068
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003069 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003070 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003071 */
3072 property_set("vold.decrypt", "trigger_shutdown_framework");
3073 SLOGD("Just asked init to shut down class main\n");
3074
Ken Sumrall425524d2012-06-14 20:55:28 -07003075 if (vold_unmountAllAsecs()) {
3076 /* Just report the error. If any are left mounted,
3077 * umounting /data below will fail and handle the error.
3078 */
3079 SLOGE("Error unmounting internal asecs");
3080 }
3081
Ken Sumrall29d8da82011-05-18 17:20:07 -07003082 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
3083 if (!strcmp(fuse_sdcard, "true")) {
3084 /* This is a device using the fuse layer to emulate the sdcard semantics
3085 * on top of the userdata partition. vold does not manage it, it is managed
3086 * by the sdcard service. The sdcard service was killed by the property trigger
3087 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
3088 * unlike the case for vold managed devices above.
3089 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003090 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07003091 goto error_shutting_down;
3092 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003093 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003094
3095 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003096 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07003097 if (allow_reboot) {
3098 goto error_shutting_down;
3099 } else {
3100 goto error_unencrypted;
3101 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003102 }
3103
3104 /* Do extra work for a better UX when doing the long inplace encryption */
3105 if (how == CRYPTO_ENABLE_INPLACE) {
3106 /* Now that /data is unmounted, we need to mount a tmpfs
3107 * /data, set a property saying we're doing inplace encryption,
3108 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003109 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003110 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003111 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003112 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003113 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003114 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003115
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003116 /* restart the framework. */
3117 /* Create necessary paths on /data */
3118 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003119 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003120 }
3121
Ken Sumrall92736ef2012-10-17 20:57:14 -07003122 /* Ugh, shutting down the framework is not synchronous, so until it
3123 * can be fixed, this horrible hack will wait a moment for it all to
3124 * shut down before proceeding. Without it, some devices cannot
3125 * restart the graphics services.
3126 */
3127 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003128 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003129
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003130 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003131 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003132 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003133 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3134 goto error_shutting_down;
3135 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003136
Paul Lawrence87999172014-02-20 12:21:31 -08003137 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3138 crypt_ftr.fs_size = nr_sec
3139 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3140 } else {
3141 crypt_ftr.fs_size = nr_sec;
3142 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003143 /* At this point, we are in an inconsistent state. Until we successfully
3144 complete encryption, a reboot will leave us broken. So mark the
3145 encryption failed in case that happens.
3146 On successfully completing encryption, remove this flag */
3147 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003148 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003149#ifndef CONFIG_HW_DISK_ENCRYPTION
3150 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3151#else
3152 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3153
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003154 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003155 if (!rc) {
3156 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3157 }
3158
3159 rc = set_hw_device_encryption_key(passwd,
3160 (char*) crypt_ftr.crypto_type_name);
3161 if (!rc) {
3162 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3163 goto error_shutting_down;
3164 }
3165#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003166
Paul Lawrence87999172014-02-20 12:21:31 -08003167 /* Make an encrypted master key */
3168 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3169 SLOGE("Cannot create encrypted master key\n");
3170 goto error_shutting_down;
3171 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003172
Paul Lawrence87999172014-02-20 12:21:31 -08003173 /* Write the key to the end of the partition */
3174 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003175
Paul Lawrence87999172014-02-20 12:21:31 -08003176 /* If any persistent data has been remembered, save it.
3177 * If none, create a valid empty table and save that.
3178 */
3179 if (!persist_data) {
3180 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3181 if (pdata) {
3182 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3183 persist_data = pdata;
3184 }
3185 }
3186 if (persist_data) {
3187 save_persistent_data();
3188 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003189 }
3190
Ajay Dudani87701e22014-09-17 21:02:52 -07003191 if (how == CRYPTO_ENABLE_INPLACE) {
3192 /* startup service classes main and late_start */
3193 property_set("vold.decrypt", "trigger_restart_min_framework");
3194 SLOGD("Just triggered restart_min_framework\n");
3195
3196 /* OK, the framework is restarted and will soon be showing a
3197 * progress bar. Time to setup an encrypted mapping, and
3198 * either write a new filesystem, or encrypt in place updating
3199 * the progress bar as we work.
3200 */
3201 }
3202
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003203 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003204 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3205 "userdata");
3206
Paul Lawrence87999172014-02-20 12:21:31 -08003207 /* If we are continuing, check checksums match */
3208 rc = 0;
3209 if (previously_encrypted_upto) {
3210 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3211 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003212
Paul Lawrence87999172014-02-20 12:21:31 -08003213 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3214 sizeof(hash_first_block)) != 0) {
3215 SLOGE("Checksums do not match - trigger wipe");
3216 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003217 }
3218 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003219
Paul Lawrence87999172014-02-20 12:21:31 -08003220 if (!rc) {
3221 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3222 crypto_blkdev, real_blkdev,
3223 previously_encrypted_upto);
3224 }
3225
3226 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003227 if (!rc && how == CRYPTO_ENABLE_INPLACE
3228 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003229 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3230 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003231 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003232 SLOGE("Error calculating checksum for continuing encryption");
3233 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003234 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003235 }
3236
3237 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003238 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003239
3240 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003241
3242 if (! rc) {
3243 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003244 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003245
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003246 if (how == CRYPTO_ENABLE_INPLACE
3247 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003248 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3249 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003250 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003251 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003252
Paul Lawrence6bfed202014-07-28 12:47:22 -07003253 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003254
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003255 if (how == CRYPTO_ENABLE_WIPE
3256 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003257 char value[PROPERTY_VALUE_MAX];
3258 property_get("ro.crypto.state", value, "");
3259 if (!strcmp(value, "")) {
3260 /* default encryption - continue first boot sequence */
3261 property_set("ro.crypto.state", "encrypted");
3262 release_wake_lock(lockid);
3263 cryptfs_check_passwd(DEFAULT_PASSWORD);
3264 cryptfs_restart_internal(1);
3265 return 0;
3266 } else {
3267 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003268 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003269 }
Paul Lawrence87999172014-02-20 12:21:31 -08003270 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003271 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003272 cryptfs_reboot(shutdown);
3273 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003274 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003275 char value[PROPERTY_VALUE_MAX];
3276
Ken Sumrall319369a2012-06-27 16:30:18 -07003277 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003278 if (!strcmp(value, "1")) {
3279 /* wipe data if encryption failed */
3280 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3281 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003282 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003283 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003284 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3285 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003286 close(fd);
3287 } else {
3288 SLOGE("could not open /cache/recovery/command\n");
3289 }
Paul Lawrence87999172014-02-20 12:21:31 -08003290 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003291 } else {
3292 /* set property to trigger dialog */
3293 property_set("vold.encrypt_progress", "error_partially_encrypted");
3294 release_wake_lock(lockid);
3295 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003296 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003297 }
3298
Ken Sumrall3ed82362011-01-28 23:31:16 -08003299 /* hrm, the encrypt step claims success, but the reboot failed.
3300 * This should not happen.
3301 * Set the property and return. Hope the framework can deal with it.
3302 */
3303 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003304 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003305 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003306
3307error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003308 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003309 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003310 if (lockid[0]) {
3311 release_wake_lock(lockid);
3312 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003313 return -1;
3314
3315error_shutting_down:
3316 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3317 * but the framework is stopped and not restarted to show the error, so it's up to
3318 * vold to restart the system.
3319 */
3320 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003321 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003322
3323 /* shouldn't get here */
3324 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003325 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003326 if (lockid[0]) {
3327 release_wake_lock(lockid);
3328 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003329 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003330}
3331
Paul Lawrence45f10532014-04-04 18:11:56 +00003332int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003333{
Paul Lawrencefc615042014-10-04 15:32:29 -07003334 char* adjusted_passwd = adjust_passwd(passwd);
3335 if (adjusted_passwd) {
3336 passwd = adjusted_passwd;
3337 }
3338
3339 int rc = cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3340
3341 free(adjusted_passwd);
3342 return rc;
Paul Lawrence13486032014-02-03 13:28:11 -08003343}
3344
3345int cryptfs_enable_default(char *howarg, int allow_reboot)
3346{
3347 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3348 DEFAULT_PASSWORD, allow_reboot);
3349}
3350
3351int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003352{
Paul Lawrence8175a0b2015-03-05 09:46:23 -08003353 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3354 return e4crypt_change_password(DATA_MNT_POINT, crypt_type, newpw);
3355 }
3356
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003357 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003358
3359 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003360 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003361 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003362 return -1;
3363 }
3364
Paul Lawrencef4faa572014-01-29 13:31:03 -08003365 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3366 SLOGE("Invalid crypt_type %d", crypt_type);
3367 return -1;
3368 }
3369
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003370 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003371 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003372 SLOGE("Error getting crypt footer and key");
3373 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003374 }
3375
Paul Lawrencef4faa572014-01-29 13:31:03 -08003376 crypt_ftr.crypt_type = crypt_type;
3377
Paul Lawrencefc615042014-10-04 15:32:29 -07003378 char* adjusted_passwd = adjust_passwd(newpw);
3379 if (adjusted_passwd) {
3380 newpw = adjusted_passwd;
3381 }
3382
Paul Lawrencef4faa572014-01-29 13:31:03 -08003383 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3384 : newpw,
3385 crypt_ftr.salt,
3386 saved_master_key,
3387 crypt_ftr.master_key,
3388 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003389
Jason parks70a4b3f2011-01-28 10:10:47 -06003390 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003391 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003392
Paul Lawrencefc615042014-10-04 15:32:29 -07003393 free(adjusted_passwd);
Ajay Dudani87701e22014-09-17 21:02:52 -07003394
3395#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003396 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3397 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3398 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3399 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3400 if (!rc)
3401 return -1;
3402 } else {
3403 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3404 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3405 if (!rc)
3406 return -1;
3407 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003408 }
3409#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003410 return 0;
3411}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003412
Rubin Xu85c01f92014-10-13 12:49:54 +01003413static unsigned int persist_get_max_entries(int encrypted) {
3414 struct crypt_mnt_ftr crypt_ftr;
3415 unsigned int dsize;
3416 unsigned int max_persistent_entries;
3417
3418 /* If encrypted, use the values from the crypt_ftr, otherwise
3419 * use the values for the current spec.
3420 */
3421 if (encrypted) {
3422 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3423 return -1;
3424 }
3425 dsize = crypt_ftr.persist_data_size;
3426 } else {
3427 dsize = CRYPT_PERSIST_DATA_SIZE;
3428 }
3429
3430 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3431 sizeof(struct crypt_persist_entry);
3432
3433 return max_persistent_entries;
3434}
3435
3436static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003437{
3438 unsigned int i;
3439
3440 if (persist_data == NULL) {
3441 return -1;
3442 }
3443 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3444 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3445 /* We found it! */
3446 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3447 return 0;
3448 }
3449 }
3450
3451 return -1;
3452}
3453
Rubin Xu85c01f92014-10-13 12:49:54 +01003454static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003455{
3456 unsigned int i;
3457 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003458 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003459
3460 if (persist_data == NULL) {
3461 return -1;
3462 }
3463
Rubin Xu85c01f92014-10-13 12:49:54 +01003464 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003465
3466 num = persist_data->persist_valid_entries;
3467
3468 for (i = 0; i < num; i++) {
3469 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3470 /* We found an existing entry, update it! */
3471 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3472 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3473 return 0;
3474 }
3475 }
3476
3477 /* We didn't find it, add it to the end, if there is room */
3478 if (persist_data->persist_valid_entries < max_persistent_entries) {
3479 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3480 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3481 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3482 persist_data->persist_valid_entries++;
3483 return 0;
3484 }
3485
3486 return -1;
3487}
3488
Rubin Xu85c01f92014-10-13 12:49:54 +01003489/**
3490 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3491 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3492 */
3493static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003494 unsigned int field_len;
3495 unsigned int key_index;
3496 field_len = strlen(field);
3497
3498 if (index == 0) {
3499 // The first key in a multi-entry field is just the filedname itself.
3500 if (!strcmp(key, field)) {
3501 return 1;
3502 }
3503 }
3504 // Match key against "%s_%d" % (field, index)
3505 if (strlen(key) < field_len + 1 + 1) {
3506 // Need at least a '_' and a digit.
3507 return 0;
3508 }
3509 if (strncmp(key, field, field_len)) {
3510 // If the key does not begin with field, it's not a match.
3511 return 0;
3512 }
3513 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3514 return 0;
3515 }
3516 return key_index >= index;
3517}
3518
3519/*
3520 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3521 * remaining entries starting from index will be deleted.
3522 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3523 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3524 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3525 *
3526 */
3527static int persist_del_keys(const char *fieldname, unsigned index)
3528{
3529 unsigned int i;
3530 unsigned int j;
3531 unsigned int num;
3532
3533 if (persist_data == NULL) {
3534 return PERSIST_DEL_KEY_ERROR_OTHER;
3535 }
3536
3537 num = persist_data->persist_valid_entries;
3538
3539 j = 0; // points to the end of non-deleted entries.
3540 // Filter out to-be-deleted entries in place.
3541 for (i = 0; i < num; i++) {
3542 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3543 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3544 j++;
3545 }
3546 }
3547
3548 if (j < num) {
3549 persist_data->persist_valid_entries = j;
3550 // Zeroise the remaining entries
3551 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3552 return PERSIST_DEL_KEY_OK;
3553 } else {
3554 // Did not find an entry matching the given fieldname
3555 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3556 }
3557}
3558
3559static int persist_count_keys(const char *fieldname)
3560{
3561 unsigned int i;
3562 unsigned int count;
3563
3564 if (persist_data == NULL) {
3565 return -1;
3566 }
3567
3568 count = 0;
3569 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3570 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3571 count++;
3572 }
3573 }
3574
3575 return count;
3576}
3577
Ken Sumrall160b4d62013-04-22 12:15:39 -07003578/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003579int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003580{
3581 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003582 /* CRYPTO_GETFIELD_OK is success,
3583 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3584 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3585 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003586 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003587 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3588 int i;
3589 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003590
3591 if (persist_data == NULL) {
3592 load_persistent_data();
3593 if (persist_data == NULL) {
3594 SLOGE("Getfield error, cannot load persistent data");
3595 goto out;
3596 }
3597 }
3598
Rubin Xu85c01f92014-10-13 12:49:54 +01003599 // Read value from persistent entries. If the original value is split into multiple entries,
3600 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003601 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003602 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3603 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3604 // value too small
3605 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3606 goto out;
3607 }
3608 rc = CRYPTO_GETFIELD_OK;
3609
3610 for (i = 1; /* break explicitly */; i++) {
3611 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3612 (int) sizeof(temp_field)) {
3613 // If the fieldname is very long, we stop as soon as it begins to overflow the
3614 // maximum field length. At this point we have in fact fully read out the original
3615 // value because cryptfs_setfield would not allow fields with longer names to be
3616 // written in the first place.
3617 break;
3618 }
3619 if (!persist_get_key(temp_field, temp_value)) {
3620 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3621 // value too small.
3622 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3623 goto out;
3624 }
3625 } else {
3626 // Exhaust all entries.
3627 break;
3628 }
3629 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003630 } else {
3631 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003632 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003633 }
3634
3635out:
3636 return rc;
3637}
3638
3639/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003640int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003641{
Ken Sumrall160b4d62013-04-22 12:15:39 -07003642 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003643 /* 0 is success, negative values are error */
3644 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003645 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003646 unsigned int field_id;
3647 char temp_field[PROPERTY_KEY_MAX];
3648 unsigned int num_entries;
3649 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003650
3651 if (persist_data == NULL) {
3652 load_persistent_data();
3653 if (persist_data == NULL) {
3654 SLOGE("Setfield error, cannot load persistent data");
3655 goto out;
3656 }
3657 }
3658
3659 property_get("ro.crypto.state", encrypted_state, "");
3660 if (!strcmp(encrypted_state, "encrypted") ) {
3661 encrypted = 1;
3662 }
3663
Rubin Xu85c01f92014-10-13 12:49:54 +01003664 // Compute the number of entries required to store value, each entry can store up to
3665 // (PROPERTY_VALUE_MAX - 1) chars
3666 if (strlen(value) == 0) {
3667 // Empty value also needs one entry to store.
3668 num_entries = 1;
3669 } else {
3670 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3671 }
3672
3673 max_keylen = strlen(fieldname);
3674 if (num_entries > 1) {
3675 // Need an extra "_%d" suffix.
3676 max_keylen += 1 + log10(num_entries);
3677 }
3678 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3679 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003680 goto out;
3681 }
3682
Rubin Xu85c01f92014-10-13 12:49:54 +01003683 // Make sure we have enough space to write the new value
3684 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3685 persist_get_max_entries(encrypted)) {
3686 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3687 goto out;
3688 }
3689
3690 // Now that we know persist_data has enough space for value, let's delete the old field first
3691 // to make up space.
3692 persist_del_keys(fieldname, 0);
3693
3694 if (persist_set_key(fieldname, value, encrypted)) {
3695 // fail to set key, should not happen as we have already checked the available space
3696 SLOGE("persist_set_key() error during setfield()");
3697 goto out;
3698 }
3699
3700 for (field_id = 1; field_id < num_entries; field_id++) {
3701 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3702
3703 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3704 // fail to set key, should not happen as we have already checked the available space.
3705 SLOGE("persist_set_key() error during setfield()");
3706 goto out;
3707 }
3708 }
3709
Ken Sumrall160b4d62013-04-22 12:15:39 -07003710 /* If we are running encrypted, save the persistent data now */
3711 if (encrypted) {
3712 if (save_persistent_data()) {
3713 SLOGE("Setfield error, cannot save persistent data");
3714 goto out;
3715 }
3716 }
3717
Rubin Xu85c01f92014-10-13 12:49:54 +01003718 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003719
3720out:
3721 return rc;
3722}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003723
3724/* Checks userdata. Attempt to mount the volume if default-
3725 * encrypted.
3726 * On success trigger next init phase and return 0.
3727 * Currently do not handle failure - see TODO below.
3728 */
3729int cryptfs_mount_default_encrypted(void)
3730{
3731 char decrypt_state[PROPERTY_VALUE_MAX];
3732 property_get("vold.decrypt", decrypt_state, "0");
3733 if (!strcmp(decrypt_state, "0")) {
3734 SLOGE("Not encrypted - should not call here");
3735 } else {
3736 int crypt_type = cryptfs_get_password_type();
3737 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3738 SLOGE("Bad crypt type - error");
3739 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3740 SLOGD("Password is not default - "
3741 "starting min framework to prompt");
3742 property_set("vold.decrypt", "trigger_restart_min_framework");
3743 return 0;
3744 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3745 SLOGD("Password is default - restarting filesystem");
3746 cryptfs_restart_internal(0);
3747 return 0;
3748 } else {
3749 SLOGE("Encrypted, default crypt type but can't decrypt");
3750 }
3751 }
3752
Paul Lawrence6bfed202014-07-28 12:47:22 -07003753 /** Corrupt. Allow us to boot into framework, which will detect bad
3754 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003755 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003756 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003757 return 0;
3758}
3759
3760/* Returns type of the password, default, pattern, pin or password.
3761 */
3762int cryptfs_get_password_type(void)
3763{
Paul Lawrence8175a0b2015-03-05 09:46:23 -08003764 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3765 return e4crypt_get_password_type(DATA_MNT_POINT);
3766 }
3767
Paul Lawrencef4faa572014-01-29 13:31:03 -08003768 struct crypt_mnt_ftr crypt_ftr;
3769
3770 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3771 SLOGE("Error getting crypt footer and key\n");
3772 return -1;
3773 }
3774
Paul Lawrence6bfed202014-07-28 12:47:22 -07003775 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3776 return -1;
3777 }
3778
Paul Lawrencef4faa572014-01-29 13:31:03 -08003779 return crypt_ftr.crypt_type;
3780}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003781
Paul Lawrence8175a0b2015-03-05 09:46:23 -08003782const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003783{
Paul Lawrence8175a0b2015-03-05 09:46:23 -08003784 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3785 return e4crypt_get_password(DATA_MNT_POINT);
3786 }
3787
Paul Lawrence399317e2014-03-10 13:20:50 -07003788 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003789 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003790 if (now.tv_sec < password_expiry_time) {
3791 return password;
3792 } else {
3793 cryptfs_clear_password();
3794 return 0;
3795 }
3796}
3797
3798void cryptfs_clear_password()
3799{
3800 if (password) {
3801 size_t len = strlen(password);
3802 memset(password, 0, len);
3803 free(password);
3804 password = 0;
3805 password_expiry_time = 0;
3806 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003807}
Paul Lawrence7053e9c2015-03-26 08:32:18 -07003808
3809int cryptfs_enable_file()
3810{
3811 return e4crypt_enable(DATA_MNT_POINT);
3812}
3813
3814int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3815{
3816 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3817 SLOGE("Failed to initialize crypt_ftr");
3818 return -1;
3819 }
3820
3821 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3822 crypt_ftr->salt, crypt_ftr)) {
3823 SLOGE("Cannot create encrypted master key\n");
3824 return -1;
3825 }
3826
3827 //crypt_ftr->keysize = key_length / 8;
3828 return 0;
3829}
3830
3831int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3832 unsigned char* master_key)
3833{
3834 int rc;
3835
3836 // ext4enc:TODO check intermediate_key to see if this is valid key
3837 unsigned char* intermediate_key = 0;
3838 size_t intermediate_key_size = 0;
3839 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3840 &intermediate_key_size);
3841
3842 return rc;
3843}
3844
3845int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3846 const unsigned char* master_key)
3847{
3848 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3849 ftr);
3850}