blob: 27974090c7eb8aaa6fb2ea8ce037ad57829593c4 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070041#include <ext4_utils/ext4.h>
42#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070058#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070059#include "crypto_scrypt.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000060#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000061#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080062#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080063#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000064#include "Keymaster.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080065
Yabin Cui1fb59662016-06-24 14:48:49 -070066#include <bootloader_message/bootloader_message.h>
Mark Salyzyn3e971272014-01-21 13:27:04 -080067
Mark Salyzyn5eecc442014-02-12 14:16:14 -080068#define UNUSED __attribute__((unused))
69
Ajay Dudani87701e22014-09-17 21:02:52 -070070#ifdef CONFIG_HW_DISK_ENCRYPTION
71#include "cryptfs_hw.h"
72#endif
73
Ken Sumrall8f869aa2010-12-03 03:47:09 -080074#define DM_CRYPT_BUF_SIZE 4096
75
Jason parks70a4b3f2011-01-28 10:10:47 -060076#define HASH_COUNT 2000
77#define KEY_LEN_BYTES 16
78#define IV_LEN_BYTES 16
79
Ken Sumrall29d8da82011-05-18 17:20:07 -070080#define KEY_IN_FOOTER "footer"
81
Paul Lawrence3bd36d52015-06-09 13:37:44 -070082#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080083
Paul Lawrence3d99eba2015-11-20 07:07:19 -080084#define CRYPTO_BLOCK_DEVICE "userdata"
85
86#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
87
Ken Sumrall29d8da82011-05-18 17:20:07 -070088#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070089#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070090
Ken Sumralle919efe2012-09-29 17:07:41 -070091#define TABLE_LOAD_RETRIES 10
92
Shawn Willden47ba10d2014-09-03 17:07:06 -060093#define RSA_KEY_SIZE 2048
94#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
95#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060096#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070097
Paul Lawrence8e3f4512014-09-08 10:11:17 -070098#define RETRY_MOUNT_ATTEMPTS 10
99#define RETRY_MOUNT_DELAY_SECONDS 1
100
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800101char *me = "cryptfs";
102
Jason parks70a4b3f2011-01-28 10:10:47 -0600103static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700104static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600105static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700106static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800107
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700108/* Should we use keymaster? */
109static int keymaster_check_compatibility()
110{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000111 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700112}
113
114/* Create a new keymaster key and store it in this footer */
115static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
116{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800117 if (ftr->keymaster_blob_size) {
118 SLOGI("Already have key");
119 return 0;
120 }
121
Janis Danisevskis015ec302017-01-31 11:31:08 +0000122 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
123 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
124 &ftr->keymaster_blob_size);
125 if (rc) {
126 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
127 SLOGE("Keymaster key blob to large)");
128 ftr->keymaster_blob_size = 0;
129 }
130 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700131 return -1;
132 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000133 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700134}
135
Shawn Willdene17a9c42014-09-08 13:04:08 -0600136/* This signs the given object using the keymaster key. */
137static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600138 const unsigned char *object,
139 const size_t object_size,
140 unsigned char **signature,
141 size_t *signature_size)
142{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600143 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600144 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600145 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600146
Shawn Willdene17a9c42014-09-08 13:04:08 -0600147 // To sign a message with RSA, the message must satisfy two
148 // constraints:
149 //
150 // 1. The message, when interpreted as a big-endian numeric value, must
151 // be strictly less than the public modulus of the RSA key. Note
152 // that because the most significant bit of the public modulus is
153 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
154 // key), an n-bit message with most significant bit 0 always
155 // satisfies this requirement.
156 //
157 // 2. The message must have the same length in bits as the public
158 // modulus of the RSA key. This requirement isn't mathematically
159 // necessary, but is necessary to ensure consistency in
160 // implementations.
161 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600162 case KDF_SCRYPT_KEYMASTER:
163 // This ensures the most significant byte of the signed message
164 // is zero. We could have zero-padded to the left instead, but
165 // this approach is slightly more robust against changes in
166 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600167 // so) because we really should be using a proper deterministic
168 // RSA padding function, such as PKCS1.
Shawn Willdene17a9c42014-09-08 13:04:08 -0600169 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
170 SLOGI("Signing safely-padded object");
171 break;
172 default:
173 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000174 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600175 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000176 return keymaster_sign_object_for_cryptfs_scrypt(ftr->keymaster_blob, ftr->keymaster_blob_size,
177 KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign, to_sign_size, signature, signature_size);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600178}
179
Paul Lawrence399317e2014-03-10 13:20:50 -0700180/* Store password when userdata is successfully decrypted and mounted.
181 * Cleared by cryptfs_clear_password
182 *
183 * To avoid a double prompt at boot, we need to store the CryptKeeper
184 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
185 * Since the entire framework is torn down and rebuilt after encryption,
186 * we have to use a daemon or similar to store the password. Since vold
187 * is secured against IPC except from system processes, it seems a reasonable
188 * place to store this.
189 *
190 * password should be cleared once it has been used.
191 *
192 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800193 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700194static char* password = 0;
195static int password_expiry_time = 0;
196static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800197
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800198extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800199
Paul Lawrence87999172014-02-20 12:21:31 -0800200enum RebootType {reboot, recovery, shutdown};
201static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700202{
Paul Lawrence87999172014-02-20 12:21:31 -0800203 switch(rt) {
204 case reboot:
205 property_set(ANDROID_RB_PROPERTY, "reboot");
206 break;
207
208 case recovery:
209 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
210 break;
211
212 case shutdown:
213 property_set(ANDROID_RB_PROPERTY, "shutdown");
214 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700215 }
Paul Lawrence87999172014-02-20 12:21:31 -0800216
Ken Sumralladfba362013-06-04 16:37:52 -0700217 sleep(20);
218
219 /* Shouldn't get here, reboot should happen before sleep times out */
220 return;
221}
222
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800223static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
224{
225 memset(io, 0, dataSize);
226 io->data_size = dataSize;
227 io->data_start = sizeof(struct dm_ioctl);
228 io->version[0] = 4;
229 io->version[1] = 0;
230 io->version[2] = 0;
231 io->flags = flags;
232 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100233 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800234 }
235}
236
Kenny Rootc4c70f12013-06-14 12:11:38 -0700237/**
238 * Gets the default device scrypt parameters for key derivation time tuning.
239 * The parameters should lead to about one second derivation time for the
240 * given device.
241 */
242static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700243 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000244 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700245
Paul Crowley63c18d32016-02-10 14:02:47 +0000246 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
247 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
248 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
249 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700250 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000251 ftr->N_factor = Nf;
252 ftr->r_factor = rf;
253 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700254}
255
Ken Sumrall3ed82362011-01-28 23:31:16 -0800256static unsigned int get_fs_size(char *dev)
257{
258 int fd, block_size;
259 struct ext4_super_block sb;
260 off64_t len;
261
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700262 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800263 SLOGE("Cannot open device to get filesystem size ");
264 return 0;
265 }
266
267 if (lseek64(fd, 1024, SEEK_SET) < 0) {
268 SLOGE("Cannot seek to superblock");
269 return 0;
270 }
271
272 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
273 SLOGE("Cannot read superblock");
274 return 0;
275 }
276
277 close(fd);
278
Daniel Rosenberge82df162014-08-15 22:19:23 +0000279 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
280 SLOGE("Not a valid ext4 superblock");
281 return 0;
282 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800283 block_size = 1024 << sb.s_log_block_size;
284 /* compute length in bytes */
285 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
286
287 /* return length in sectors */
288 return (unsigned int) (len / 512);
289}
290
Ken Sumrall160b4d62013-04-22 12:15:39 -0700291static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
292{
293 static int cached_data = 0;
294 static off64_t cached_off = 0;
295 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
296 int fd;
297 char key_loc[PROPERTY_VALUE_MAX];
298 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700299 int rc = -1;
300
301 if (!cached_data) {
302 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
303
304 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700305 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700306 SLOGE("Cannot open real block device %s\n", real_blkdev);
307 return -1;
308 }
309
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900310 unsigned long nr_sec = 0;
311 get_blkdev_size(fd, &nr_sec);
312 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700313 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
314 * encryption info footer and key, and plenty of bytes to spare for future
315 * growth.
316 */
317 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
318 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
319 cached_data = 1;
320 } else {
321 SLOGE("Cannot get size of block device %s\n", real_blkdev);
322 }
323 close(fd);
324 } else {
325 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
326 cached_off = 0;
327 cached_data = 1;
328 }
329 }
330
331 if (cached_data) {
332 if (metadata_fname) {
333 *metadata_fname = cached_metadata_fname;
334 }
335 if (off) {
336 *off = cached_off;
337 }
338 rc = 0;
339 }
340
341 return rc;
342}
343
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800344/* Set sha256 checksum in structure */
345static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
346{
347 SHA256_CTX c;
348 SHA256_Init(&c);
349 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
350 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
351 SHA256_Final(crypt_ftr->sha256, &c);
352}
353
Ken Sumralle8744072011-01-18 22:01:55 -0800354/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800355 * update the failed mount count but not change the key.
356 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700357static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800358{
359 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800360 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700361 /* starting_off is set to the SEEK_SET offset
362 * where the crypto structure starts
363 */
364 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800365 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700366 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700367 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800368
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800369 set_ftr_sha(crypt_ftr);
370
Ken Sumrall160b4d62013-04-22 12:15:39 -0700371 if (get_crypt_ftr_info(&fname, &starting_off)) {
372 SLOGE("Unable to get crypt_ftr_info\n");
373 return -1;
374 }
375 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700376 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700377 return -1;
378 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700379 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700380 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700381 return -1;
382 }
383
384 /* Seek to the start of the crypt footer */
385 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
386 SLOGE("Cannot seek to real block device footer\n");
387 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800388 }
389
390 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
391 SLOGE("Cannot write real block device footer\n");
392 goto errout;
393 }
394
Ken Sumrall3be890f2011-09-14 16:53:46 -0700395 fstat(fd, &statbuf);
396 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700397 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700398 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800399 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800400 goto errout;
401 }
402 }
403
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800404 /* Success! */
405 rc = 0;
406
407errout:
408 close(fd);
409 return rc;
410
411}
412
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800413static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
414{
415 struct crypt_mnt_ftr copy;
416 memcpy(&copy, crypt_ftr, sizeof(copy));
417 set_ftr_sha(&copy);
418 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
419}
420
Ken Sumrall160b4d62013-04-22 12:15:39 -0700421static inline int unix_read(int fd, void* buff, int len)
422{
423 return TEMP_FAILURE_RETRY(read(fd, buff, len));
424}
425
426static inline int unix_write(int fd, const void* buff, int len)
427{
428 return TEMP_FAILURE_RETRY(write(fd, buff, len));
429}
430
431static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
432{
433 memset(pdata, 0, len);
434 pdata->persist_magic = PERSIST_DATA_MAGIC;
435 pdata->persist_valid_entries = 0;
436}
437
438/* A routine to update the passed in crypt_ftr to the lastest version.
439 * fd is open read/write on the device that holds the crypto footer and persistent
440 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
441 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
442 */
443static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
444{
Kenny Root7434b312013-06-14 11:29:53 -0700445 int orig_major = crypt_ftr->major_version;
446 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700447
Kenny Root7434b312013-06-14 11:29:53 -0700448 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
449 struct crypt_persist_data *pdata;
450 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700451
Kenny Rootc4c70f12013-06-14 12:11:38 -0700452 SLOGW("upgrading crypto footer to 1.1");
453
Kenny Root7434b312013-06-14 11:29:53 -0700454 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
455 if (pdata == NULL) {
456 SLOGE("Cannot allocate persisent data\n");
457 return;
458 }
459 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
460
461 /* Need to initialize the persistent data area */
462 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
463 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100464 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700465 return;
466 }
467 /* Write all zeros to the first copy, making it invalid */
468 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
469
470 /* Write a valid but empty structure to the second copy */
471 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
472 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
473
474 /* Update the footer */
475 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
476 crypt_ftr->persist_data_offset[0] = pdata_offset;
477 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
478 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100479 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700480 }
481
Paul Lawrencef4faa572014-01-29 13:31:03 -0800482 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700483 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800484 /* But keep the old kdf_type.
485 * It will get updated later to KDF_SCRYPT after the password has been verified.
486 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700487 crypt_ftr->kdf_type = KDF_PBKDF2;
488 get_device_scrypt_params(crypt_ftr);
489 crypt_ftr->minor_version = 2;
490 }
491
Paul Lawrencef4faa572014-01-29 13:31:03 -0800492 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
493 SLOGW("upgrading crypto footer to 1.3");
494 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
495 crypt_ftr->minor_version = 3;
496 }
497
Kenny Root7434b312013-06-14 11:29:53 -0700498 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
499 if (lseek64(fd, offset, SEEK_SET) == -1) {
500 SLOGE("Cannot seek to crypt footer\n");
501 return;
502 }
503 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700504 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700505}
506
507
508static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800509{
510 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800511 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700512 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800513 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700514 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700515 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800516
Ken Sumrall160b4d62013-04-22 12:15:39 -0700517 if (get_crypt_ftr_info(&fname, &starting_off)) {
518 SLOGE("Unable to get crypt_ftr_info\n");
519 return -1;
520 }
521 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700522 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700523 return -1;
524 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700525 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700526 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700527 return -1;
528 }
529
530 /* Make sure it's 16 Kbytes in length */
531 fstat(fd, &statbuf);
532 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
533 SLOGE("footer file %s is not the expected size!\n", fname);
534 goto errout;
535 }
536
537 /* Seek to the start of the crypt footer */
538 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
539 SLOGE("Cannot seek to real block device footer\n");
540 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800541 }
542
543 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
544 SLOGE("Cannot read real block device footer\n");
545 goto errout;
546 }
547
548 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700549 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800550 goto errout;
551 }
552
Kenny Rootc96a5f82013-06-14 12:08:28 -0700553 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
554 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
555 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800556 goto errout;
557 }
558
Kenny Rootc96a5f82013-06-14 12:08:28 -0700559 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
560 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
561 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800562 }
563
Ken Sumrall160b4d62013-04-22 12:15:39 -0700564 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
565 * copy on disk before returning.
566 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700567 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700568 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800569 }
570
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800571 /* Success! */
572 rc = 0;
573
574errout:
575 close(fd);
576 return rc;
577}
578
Ken Sumrall160b4d62013-04-22 12:15:39 -0700579static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
580{
581 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
582 crypt_ftr->persist_data_offset[1]) {
583 SLOGE("Crypt_ftr persist data regions overlap");
584 return -1;
585 }
586
587 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
588 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
589 return -1;
590 }
591
592 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
593 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
594 CRYPT_FOOTER_OFFSET) {
595 SLOGE("Persistent data extends past crypto footer");
596 return -1;
597 }
598
599 return 0;
600}
601
602static int load_persistent_data(void)
603{
604 struct crypt_mnt_ftr crypt_ftr;
605 struct crypt_persist_data *pdata = NULL;
606 char encrypted_state[PROPERTY_VALUE_MAX];
607 char *fname;
608 int found = 0;
609 int fd;
610 int ret;
611 int i;
612
613 if (persist_data) {
614 /* Nothing to do, we've already loaded or initialized it */
615 return 0;
616 }
617
618
619 /* If not encrypted, just allocate an empty table and initialize it */
620 property_get("ro.crypto.state", encrypted_state, "");
621 if (strcmp(encrypted_state, "encrypted") ) {
622 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
623 if (pdata) {
624 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
625 persist_data = pdata;
626 return 0;
627 }
628 return -1;
629 }
630
631 if(get_crypt_ftr_and_key(&crypt_ftr)) {
632 return -1;
633 }
634
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700635 if ((crypt_ftr.major_version < 1)
636 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700637 SLOGE("Crypt_ftr version doesn't support persistent data");
638 return -1;
639 }
640
641 if (get_crypt_ftr_info(&fname, NULL)) {
642 return -1;
643 }
644
645 ret = validate_persistent_data_storage(&crypt_ftr);
646 if (ret) {
647 return -1;
648 }
649
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700650 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700651 if (fd < 0) {
652 SLOGE("Cannot open %s metadata file", fname);
653 return -1;
654 }
655
Paul Lawrence300dae72016-03-11 11:02:52 -0800656 pdata = malloc(crypt_ftr.persist_data_size);
657 if (pdata == NULL) {
658 SLOGE("Cannot allocate memory for persistent data");
659 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700660 }
661
662 for (i = 0; i < 2; i++) {
663 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
664 SLOGE("Cannot seek to read persistent data on %s", fname);
665 goto err2;
666 }
667 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
668 SLOGE("Error reading persistent data on iteration %d", i);
669 goto err2;
670 }
671 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
672 found = 1;
673 break;
674 }
675 }
676
677 if (!found) {
678 SLOGI("Could not find valid persistent data, creating");
679 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
680 }
681
682 /* Success */
683 persist_data = pdata;
684 close(fd);
685 return 0;
686
687err2:
688 free(pdata);
689
690err:
691 close(fd);
692 return -1;
693}
694
695static int save_persistent_data(void)
696{
697 struct crypt_mnt_ftr crypt_ftr;
698 struct crypt_persist_data *pdata;
699 char *fname;
700 off64_t write_offset;
701 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700702 int fd;
703 int ret;
704
705 if (persist_data == NULL) {
706 SLOGE("No persistent data to save");
707 return -1;
708 }
709
710 if(get_crypt_ftr_and_key(&crypt_ftr)) {
711 return -1;
712 }
713
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700714 if ((crypt_ftr.major_version < 1)
715 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700716 SLOGE("Crypt_ftr version doesn't support persistent data");
717 return -1;
718 }
719
720 ret = validate_persistent_data_storage(&crypt_ftr);
721 if (ret) {
722 return -1;
723 }
724
725 if (get_crypt_ftr_info(&fname, NULL)) {
726 return -1;
727 }
728
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700729 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700730 if (fd < 0) {
731 SLOGE("Cannot open %s metadata file", fname);
732 return -1;
733 }
734
735 pdata = malloc(crypt_ftr.persist_data_size);
736 if (pdata == NULL) {
737 SLOGE("Cannot allocate persistant data");
738 goto err;
739 }
740
741 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
742 SLOGE("Cannot seek to read persistent data on %s", fname);
743 goto err2;
744 }
745
746 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
747 SLOGE("Error reading persistent data before save");
748 goto err2;
749 }
750
751 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
752 /* The first copy is the curent valid copy, so write to
753 * the second copy and erase this one */
754 write_offset = crypt_ftr.persist_data_offset[1];
755 erase_offset = crypt_ftr.persist_data_offset[0];
756 } else {
757 /* The second copy must be the valid copy, so write to
758 * the first copy, and erase the second */
759 write_offset = crypt_ftr.persist_data_offset[0];
760 erase_offset = crypt_ftr.persist_data_offset[1];
761 }
762
763 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100764 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700765 SLOGE("Cannot seek to write persistent data");
766 goto err2;
767 }
768 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
769 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100770 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700771 SLOGE("Cannot seek to erase previous persistent data");
772 goto err2;
773 }
774 fsync(fd);
775 memset(pdata, 0, crypt_ftr.persist_data_size);
776 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
777 (int) crypt_ftr.persist_data_size) {
778 SLOGE("Cannot write to erase previous persistent data");
779 goto err2;
780 }
781 fsync(fd);
782 } else {
783 SLOGE("Cannot write to save persistent data");
784 goto err2;
785 }
786
787 /* Success */
788 free(pdata);
789 close(fd);
790 return 0;
791
792err2:
793 free(pdata);
794err:
795 close(fd);
796 return -1;
797}
798
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800799/* Convert a binary key of specified length into an ascii hex string equivalent,
800 * without the leading 0x and with null termination
801 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700802static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700803 unsigned int keysize, char *master_key_ascii) {
804 unsigned int i, a;
805 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800806
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700807 for (i=0, a=0; i<keysize; i++, a+=2) {
808 /* For each byte, write out two ascii hex digits */
809 nibble = (master_key[i] >> 4) & 0xf;
810 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800811
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700812 nibble = master_key[i] & 0xf;
813 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
814 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800815
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700816 /* Add the null termination */
817 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800818
819}
820
Jeff Sharkey9c484982015-03-31 10:35:33 -0700821static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
822 const unsigned char *master_key, const char *real_blk_name,
823 const char *name, int fd, const char *extra_params) {
Dan Albertc07fa3f2014-12-18 10:00:55 -0800824 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800825 struct dm_ioctl *io;
826 struct dm_target_spec *tgt;
827 char *crypt_params;
828 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800829 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800830 int i;
831
832 io = (struct dm_ioctl *) buffer;
833
834 /* Load the mapping table for this device */
835 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
836
837 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
838 io->target_count = 1;
839 tgt->status = 0;
840 tgt->sector_start = 0;
841 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700842#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -0800843 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
844 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
845 }
846 else {
847 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
848 }
Ajay Dudani87701e22014-09-17 21:02:52 -0700849#else
850 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
851#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -0800852
853 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
854 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800855
856 buff_offset = crypt_params - buffer;
857 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
858 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
859 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800860 crypt_params += strlen(crypt_params) + 1;
861 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
862 tgt->next = crypt_params - buffer;
863
864 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
865 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
866 break;
867 }
868 usleep(500000);
869 }
870
871 if (i == TABLE_LOAD_RETRIES) {
872 /* We failed to load the table, return an error */
873 return -1;
874 } else {
875 return i + 1;
876 }
877}
878
879
880static int get_dm_crypt_version(int fd, const char *name, int *version)
881{
882 char buffer[DM_CRYPT_BUF_SIZE];
883 struct dm_ioctl *io;
884 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800885
886 io = (struct dm_ioctl *) buffer;
887
888 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
889
890 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
891 return -1;
892 }
893
894 /* Iterate over the returned versions, looking for name of "crypt".
895 * When found, get and return the version.
896 */
897 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
898 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -0700899#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -0800900 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -0700901#else
Ken Sumralldb5e0262013-02-05 17:39:48 -0800902 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -0700903#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -0800904 /* We found the crypt driver, return the version, and get out */
905 version[0] = v->version[0];
906 version[1] = v->version[1];
907 version[2] = v->version[2];
908 return 0;
909 }
910 v = (struct dm_target_versions *)(((char *)v) + v->next);
911 }
912
913 return -1;
914}
915
Jeff Sharkey9c484982015-03-31 10:35:33 -0700916static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
917 const unsigned char *master_key, const char *real_blk_name,
918 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800919 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800920 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800921 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -0700922 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800923 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800924 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800925 int version[3];
926 char *extra_params;
927 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800928
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700929 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800930 SLOGE("Cannot open device-mapper\n");
931 goto errout;
932 }
933
934 io = (struct dm_ioctl *) buffer;
935
936 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800937 err = ioctl(fd, DM_DEV_CREATE, io);
938 if (err) {
939 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800940 goto errout;
941 }
942
943 /* Get the device status, in particular, the name of it's device file */
944 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
945 if (ioctl(fd, DM_DEV_STATUS, io)) {
946 SLOGE("Cannot retrieve dm-crypt device status\n");
947 goto errout;
948 }
949 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
950 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
951
Ken Sumralldb5e0262013-02-05 17:39:48 -0800952 extra_params = "";
953 if (! get_dm_crypt_version(fd, name, version)) {
954 /* Support for allow_discards was added in version 1.11.0 */
955 if ((version[0] >= 2) ||
956 ((version[0] == 1) && (version[1] >= 11))) {
957 extra_params = "1 allow_discards";
958 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
959 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700960 }
961
Ken Sumralldb5e0262013-02-05 17:39:48 -0800962 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
963 fd, extra_params);
964 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800965 SLOGE("Cannot load dm-crypt mapping table.\n");
966 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800967 } else if (load_count > 1) {
968 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800969 }
970
971 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800972 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800973
974 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
975 SLOGE("Cannot resume the dm-crypt device\n");
976 goto errout;
977 }
978
979 /* We made it here with no errors. Woot! */
980 retval = 0;
981
982errout:
983 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
984
985 return retval;
986}
987
Ken Sumrall29d8da82011-05-18 17:20:07 -0700988static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800989{
990 int fd;
991 char buffer[DM_CRYPT_BUF_SIZE];
992 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800993 int retval = -1;
994
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700995 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800996 SLOGE("Cannot open device-mapper\n");
997 goto errout;
998 }
999
1000 io = (struct dm_ioctl *) buffer;
1001
1002 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1003 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1004 SLOGE("Cannot remove dm-crypt device\n");
1005 goto errout;
1006 }
1007
1008 /* We made it here with no errors. Woot! */
1009 retval = 0;
1010
1011errout:
1012 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1013
1014 return retval;
1015
1016}
1017
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001018static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001019 unsigned char *ikey, void *params UNUSED)
1020{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001021 SLOGI("Using pbkdf2 for cryptfs KDF");
1022
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001023 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001024 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1025 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1026 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001027}
1028
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001029static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001030 unsigned char *ikey, void *params)
1031{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001032 SLOGI("Using scrypt for cryptfs KDF");
1033
Kenny Rootc4c70f12013-06-14 12:11:38 -07001034 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1035
1036 int N = 1 << ftr->N_factor;
1037 int r = 1 << ftr->r_factor;
1038 int p = 1 << ftr->p_factor;
1039
1040 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001041 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001042 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1043 salt, SALT_LEN, N, r, p, ikey,
1044 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001045
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001046 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001047}
1048
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001049static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1050 unsigned char *ikey, void *params)
1051{
1052 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1053
1054 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001055 size_t signature_size;
1056 unsigned char* signature;
1057 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1058
1059 int N = 1 << ftr->N_factor;
1060 int r = 1 << ftr->r_factor;
1061 int p = 1 << ftr->p_factor;
1062
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001063 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1064 salt, SALT_LEN, N, r, p, ikey,
1065 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001066
1067 if (rc) {
1068 SLOGE("scrypt failed");
1069 return -1;
1070 }
1071
Shawn Willdene17a9c42014-09-08 13:04:08 -06001072 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1073 &signature, &signature_size)) {
1074 SLOGE("Signing failed");
1075 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001076 }
1077
1078 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1079 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1080 free(signature);
1081
1082 if (rc) {
1083 SLOGE("scrypt failed");
1084 return -1;
1085 }
1086
1087 return 0;
1088}
1089
1090static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1091 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001092 unsigned char *encrypted_master_key,
1093 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001094{
1095 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1096 EVP_CIPHER_CTX e_ctx;
1097 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001098 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001099
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001100 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001101 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001102
1103 switch (crypt_ftr->kdf_type) {
1104 case KDF_SCRYPT_KEYMASTER:
1105 if (keymaster_create_key(crypt_ftr)) {
1106 SLOGE("keymaster_create_key failed");
1107 return -1;
1108 }
1109
1110 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1111 SLOGE("scrypt failed");
1112 return -1;
1113 }
1114 break;
1115
1116 case KDF_SCRYPT:
1117 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1118 SLOGE("scrypt failed");
1119 return -1;
1120 }
1121 break;
1122
1123 default:
1124 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001125 return -1;
1126 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001127
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001128 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001129 EVP_CIPHER_CTX_init(&e_ctx);
1130 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131 SLOGE("EVP_EncryptInit failed\n");
1132 return -1;
1133 }
1134 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001135
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001136 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001137 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001138 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001139 SLOGE("EVP_EncryptUpdate failed\n");
1140 return -1;
1141 }
Adam Langley889c4f12014-09-03 14:23:13 -07001142 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001143 SLOGE("EVP_EncryptFinal failed\n");
1144 return -1;
1145 }
1146
1147 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1148 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1149 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001150 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001151
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001152 /* Store the scrypt of the intermediate key, so we can validate if it's a
1153 password error or mount error when things go wrong.
1154 Note there's no need to check for errors, since if this is incorrect, we
1155 simply won't wipe userdata, which is the correct default behavior
1156 */
1157 int N = 1 << crypt_ftr->N_factor;
1158 int r = 1 << crypt_ftr->r_factor;
1159 int p = 1 << crypt_ftr->p_factor;
1160
1161 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1162 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1163 crypt_ftr->scrypted_intermediate_key,
1164 sizeof(crypt_ftr->scrypted_intermediate_key));
1165
1166 if (rc) {
1167 SLOGE("encrypt_master_key: crypto_scrypt failed");
1168 }
1169
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001170 EVP_CIPHER_CTX_cleanup(&e_ctx);
1171
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001172 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001173}
1174
Paul Lawrence731a7a22015-04-28 22:14:15 +00001175static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001176 unsigned char *encrypted_master_key,
1177 unsigned char *decrypted_master_key,
1178 kdf_func kdf, void *kdf_params,
1179 unsigned char** intermediate_key,
1180 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001181{
1182 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 -08001183 EVP_CIPHER_CTX d_ctx;
1184 int decrypted_len, final_len;
1185
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001186 /* Turn the password into an intermediate key and IV that can decrypt the
1187 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001188 if (kdf(passwd, salt, ikey, kdf_params)) {
1189 SLOGE("kdf failed");
1190 return -1;
1191 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001192
1193 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001194 EVP_CIPHER_CTX_init(&d_ctx);
1195 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001196 return -1;
1197 }
1198 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1199 /* Decrypt the master key */
1200 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1201 encrypted_master_key, KEY_LEN_BYTES)) {
1202 return -1;
1203 }
Adam Langley889c4f12014-09-03 14:23:13 -07001204 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001205 return -1;
1206 }
1207
1208 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1209 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001210 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001211
1212 /* Copy intermediate key if needed by params */
1213 if (intermediate_key && intermediate_key_size) {
1214 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001215 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001216 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1217 *intermediate_key_size = KEY_LEN_BYTES;
1218 }
1219 }
1220
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001221 EVP_CIPHER_CTX_cleanup(&d_ctx);
1222
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001223 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001224}
1225
Kenny Rootc4c70f12013-06-14 12:11:38 -07001226static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001227{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001228 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001229 *kdf = scrypt_keymaster;
1230 *kdf_params = ftr;
1231 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001232 *kdf = scrypt;
1233 *kdf_params = ftr;
1234 } else {
1235 *kdf = pbkdf2;
1236 *kdf_params = NULL;
1237 }
1238}
1239
Paul Lawrence731a7a22015-04-28 22:14:15 +00001240static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001241 struct crypt_mnt_ftr *crypt_ftr,
1242 unsigned char** intermediate_key,
1243 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001244{
1245 kdf_func kdf;
1246 void *kdf_params;
1247 int ret;
1248
1249 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001250 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1251 decrypted_master_key, kdf, kdf_params,
1252 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001253 if (ret != 0) {
1254 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001255 }
1256
1257 return ret;
1258}
1259
1260static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1261 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001262 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001263 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001264
1265 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001266 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001267 read(fd, key_buf, sizeof(key_buf));
1268 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001269 close(fd);
1270
1271 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001272 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001273}
1274
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001275int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001276{
Greg Hackmann955653e2014-09-24 14:55:20 -07001277 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001278#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001279
1280 /* Now umount the tmpfs filesystem */
1281 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001282 if (umount(mountpoint) == 0) {
1283 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001284 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001285
1286 if (errno == EINVAL) {
1287 /* EINVAL is returned if the directory is not a mountpoint,
1288 * i.e. there is no filesystem mounted there. So just get out.
1289 */
1290 break;
1291 }
1292
1293 err = errno;
1294
1295 /* If allowed, be increasingly aggressive before the last two retries */
1296 if (kill) {
1297 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1298 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001299 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001300 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1301 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001302 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001303 }
1304 }
1305
1306 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001307 }
1308
1309 if (i < WAIT_UNMOUNT_COUNT) {
1310 SLOGD("unmounting %s succeeded\n", mountpoint);
1311 rc = 0;
1312 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001313 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001314 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001315 rc = -1;
1316 }
1317
1318 return rc;
1319}
1320
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001321#define DATA_PREP_TIMEOUT 1000
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001322static int prep_data_fs(void)
1323{
1324 int i;
1325
Jeff Sharkey47695b22016-02-01 17:02:29 -07001326 // NOTE: post_fs_data results in init calling back around to vold, so all
1327 // callers to this method must be async
1328
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001329 /* Do the prep of the /data filesystem */
1330 property_set("vold.post_fs_data_done", "0");
1331 property_set("vold.decrypt", "trigger_post_fs_data");
1332 SLOGD("Just triggered post_fs_data\n");
1333
Ken Sumrallc5872692013-05-14 15:26:31 -07001334 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001335 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001336 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001337
1338 property_get("vold.post_fs_data_done", p, "0");
1339 if (*p == '1') {
1340 break;
1341 } else {
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001342 usleep(50000);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001343 }
1344 }
1345 if (i == DATA_PREP_TIMEOUT) {
1346 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001347 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001348 return -1;
1349 } else {
1350 SLOGD("post_fs_data done\n");
1351 return 0;
1352 }
1353}
1354
Paul Lawrence74f29f12014-08-28 15:54:10 -07001355static void cryptfs_set_corrupt()
1356{
1357 // Mark the footer as bad
1358 struct crypt_mnt_ftr crypt_ftr;
1359 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1360 SLOGE("Failed to get crypto footer - panic");
1361 return;
1362 }
1363
1364 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1365 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1366 SLOGE("Failed to set crypto footer - panic");
1367 return;
1368 }
1369}
1370
1371static void cryptfs_trigger_restart_min_framework()
1372{
1373 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1374 SLOGE("Failed to mount tmpfs on data - panic");
1375 return;
1376 }
1377
1378 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1379 SLOGE("Failed to trigger post fs data - panic");
1380 return;
1381 }
1382
1383 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1384 SLOGE("Failed to trigger restart min framework - panic");
1385 return;
1386 }
1387}
1388
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001389/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001390static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001392 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001393 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001394 static int restart_successful = 0;
1395
1396 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001397 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001398 SLOGE("Encrypted filesystem not validated, aborting");
1399 return -1;
1400 }
1401
1402 if (restart_successful) {
1403 SLOGE("System already restarted with encrypted disk, aborting");
1404 return -1;
1405 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001406
Paul Lawrencef4faa572014-01-29 13:31:03 -08001407 if (restart_main) {
1408 /* Here is where we shut down the framework. The init scripts
1409 * start all services in one of three classes: core, main or late_start.
1410 * On boot, we start core and main. Now, we stop main, but not core,
1411 * as core includes vold and a few other really important things that
1412 * we need to keep running. Once main has stopped, we should be able
1413 * to umount the tmpfs /data, then mount the encrypted /data.
1414 * We then restart the class main, and also the class late_start.
1415 * At the moment, I've only put a few things in late_start that I know
1416 * are not needed to bring up the framework, and that also cause problems
1417 * with unmounting the tmpfs /data, but I hope to add add more services
1418 * to the late_start class as we optimize this to decrease the delay
1419 * till the user is asked for the password to the filesystem.
1420 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001421
Paul Lawrencef4faa572014-01-29 13:31:03 -08001422 /* The init files are setup to stop the class main when vold.decrypt is
1423 * set to trigger_reset_main.
1424 */
1425 property_set("vold.decrypt", "trigger_reset_main");
1426 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427
Paul Lawrencef4faa572014-01-29 13:31:03 -08001428 /* Ugh, shutting down the framework is not synchronous, so until it
1429 * can be fixed, this horrible hack will wait a moment for it all to
1430 * shut down before proceeding. Without it, some devices cannot
1431 * restart the graphics services.
1432 */
1433 sleep(2);
1434 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001435
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001436 /* Now that the framework is shutdown, we should be able to umount()
1437 * the tmpfs filesystem, and mount the real one.
1438 */
1439
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001440 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1441 if (strlen(crypto_blkdev) == 0) {
1442 SLOGE("fs_crypto_blkdev not set\n");
1443 return -1;
1444 }
1445
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001446 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001447 /* If ro.crypto.readonly is set to 1, mount the decrypted
1448 * filesystem readonly. This is used when /data is mounted by
1449 * recovery mode.
1450 */
1451 char ro_prop[PROPERTY_VALUE_MAX];
1452 property_get("ro.crypto.readonly", ro_prop, "");
1453 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1454 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1455 rec->flags |= MS_RDONLY;
1456 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001457
Ken Sumralle5032c42012-04-01 23:58:44 -07001458 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001459 int retries = RETRY_MOUNT_ATTEMPTS;
1460 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001461
1462 /*
1463 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1464 * partitions in the fsck domain.
1465 */
1466 if (setexeccon(secontextFsck())){
1467 SLOGE("Failed to setexeccon");
1468 return -1;
1469 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001470 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1471 crypto_blkdev, 0))
1472 != 0) {
1473 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1474 /* TODO: invoke something similar to
1475 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1476 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1477 SLOGI("Failed to mount %s because it is busy - waiting",
1478 crypto_blkdev);
1479 if (--retries) {
1480 sleep(RETRY_MOUNT_DELAY_SECONDS);
1481 } else {
1482 /* Let's hope that a reboot clears away whatever is keeping
1483 the mount busy */
1484 cryptfs_reboot(reboot);
1485 }
1486 } else {
1487 SLOGE("Failed to mount decrypted data");
1488 cryptfs_set_corrupt();
1489 cryptfs_trigger_restart_min_framework();
1490 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001491 if (setexeccon(NULL)) {
1492 SLOGE("Failed to setexeccon");
1493 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001494 return -1;
1495 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001496 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001497 if (setexeccon(NULL)) {
1498 SLOGE("Failed to setexeccon");
1499 return -1;
1500 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001501
Ken Sumralle5032c42012-04-01 23:58:44 -07001502 /* Create necessary paths on /data */
1503 if (prep_data_fs()) {
1504 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001505 }
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001506 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001507
1508 /* startup service classes main and late_start */
1509 property_set("vold.decrypt", "trigger_restart_framework");
1510 SLOGD("Just triggered restart_framework\n");
1511
1512 /* Give it a few moments to get started */
1513 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001514 }
1515
Ken Sumrall0cc16632011-01-18 20:32:26 -08001516 if (rc == 0) {
1517 restart_successful = 1;
1518 }
1519
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001520 return rc;
1521}
1522
Paul Lawrencef4faa572014-01-29 13:31:03 -08001523int cryptfs_restart(void)
1524{
Paul Lawrence05335c32015-03-05 09:46:23 -08001525 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001526 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001527 SLOGE("cryptfs_restart not valid for file encryption:");
1528 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001529 }
1530
Paul Lawrencef4faa572014-01-29 13:31:03 -08001531 /* Call internal implementation forcing a restart of main service group */
1532 return cryptfs_restart_internal(1);
1533}
1534
Paul Lawrence05335c32015-03-05 09:46:23 -08001535static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001536{
1537 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001538 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001539 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001540
1541 property_get("ro.crypto.state", encrypted_state, "");
1542 if (strcmp(encrypted_state, "encrypted") ) {
1543 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001544 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001545 }
1546
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001547 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001548 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001549 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001550 }
1551
Ken Sumrall160b4d62013-04-22 12:15:39 -07001552 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001553 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001554
Ken Sumralle1a45852011-12-14 21:24:27 -08001555 /*
1556 * Only report this error if key_loc is a file and it exists.
1557 * If the device was never encrypted, and /data is not mountable for
1558 * some reason, returning 1 should prevent the UI from presenting the
1559 * a "enter password" screen, or worse, a "press button to wipe the
1560 * device" screen.
1561 */
1562 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1563 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001564 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001565 } else {
1566 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001567 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001568 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001569 }
1570
Paul Lawrence74f29f12014-08-28 15:54:10 -07001571 // Test for possible error flags
1572 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1573 SLOGE("Encryption process is partway completed\n");
1574 return CRYPTO_COMPLETE_PARTIAL;
1575 }
1576
1577 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1578 SLOGE("Encryption process was interrupted but cannot continue\n");
1579 return CRYPTO_COMPLETE_INCONSISTENT;
1580 }
1581
1582 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1583 SLOGE("Encryption is successful but data is corrupt\n");
1584 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001585 }
1586
1587 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001588 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001589}
1590
Paul Lawrencef4faa572014-01-29 13:31:03 -08001591static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1592 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001593{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001594 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001595 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596 char crypto_blkdev[MAXPATHLEN];
1597 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001599 unsigned int orig_failed_decrypt_count;
1600 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001601 int use_keymaster = 0;
1602 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001603 unsigned char* intermediate_key = 0;
1604 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001605
Paul Lawrencef4faa572014-01-29 13:31:03 -08001606 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1607 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001608
Paul Lawrencef4faa572014-01-29 13:31:03 -08001609 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001610 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1611 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001612 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001613 rc = -1;
1614 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001615 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001616 }
1617
Paul Lawrencef4faa572014-01-29 13:31:03 -08001618 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1619
Ajay Dudani87701e22014-09-17 21:02:52 -07001620#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001621 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1622 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1623 SLOGE("Hardware encryption key does not match");
1624 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001625 }
1626#endif
1627
Paul Lawrence74f29f12014-08-28 15:54:10 -07001628 // Create crypto block device - all (non fatal) code paths
1629 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001630 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1631 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001632 SLOGE("Error creating decrypted block device\n");
1633 rc = -1;
1634 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001635 }
1636
Paul Lawrence74f29f12014-08-28 15:54:10 -07001637 /* Work out if the problem is the password or the data */
1638 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1639 scrypted_intermediate_key)];
1640 int N = 1 << crypt_ftr->N_factor;
1641 int r = 1 << crypt_ftr->r_factor;
1642 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001643
Paul Lawrence74f29f12014-08-28 15:54:10 -07001644 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1645 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1646 N, r, p, scrypted_intermediate_key,
1647 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001648
Paul Lawrence74f29f12014-08-28 15:54:10 -07001649 // Does the key match the crypto footer?
1650 if (rc == 0 && memcmp(scrypted_intermediate_key,
1651 crypt_ftr->scrypted_intermediate_key,
1652 sizeof(scrypted_intermediate_key)) == 0) {
1653 SLOGI("Password matches");
1654 rc = 0;
1655 } else {
1656 /* Try mounting the file system anyway, just in case the problem's with
1657 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001658 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1659 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001660 mkdir(tmp_mount_point, 0755);
1661 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1662 SLOGE("Error temp mounting decrypted block device\n");
1663 delete_crypto_blk_dev(label);
1664
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001665 rc = ++crypt_ftr->failed_decrypt_count;
1666 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001667 } else {
1668 /* Success! */
1669 SLOGI("Password did not match but decrypted drive mounted - continue");
1670 umount(tmp_mount_point);
1671 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001672 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001673 }
1674
1675 if (rc == 0) {
1676 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001677 if (orig_failed_decrypt_count != 0) {
1678 put_crypt_ftr_and_key(crypt_ftr);
1679 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001680
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001681 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001682 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001683 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001684
1685 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001686 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001687 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001688 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001689 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001690 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001691 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001692
Paul Lawrence74f29f12014-08-28 15:54:10 -07001693 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001694 use_keymaster = keymaster_check_compatibility();
1695 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001696 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001697 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1698 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1699 upgrade = 1;
1700 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001701 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001702 upgrade = 1;
1703 }
1704
1705 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001706 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1707 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001708 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001709 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001710 }
1711 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001712
1713 // Do not fail even if upgrade failed - machine is bootable
1714 // Note that if this code is ever hit, there is a *serious* problem
1715 // since KDFs should never fail. You *must* fix the kdf before
1716 // proceeding!
1717 if (rc) {
1718 SLOGW("Upgrade failed with error %d,"
1719 " but continuing with previous state",
1720 rc);
1721 rc = 0;
1722 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001723 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724 }
1725
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001726 errout:
1727 if (intermediate_key) {
1728 memset(intermediate_key, 0, intermediate_key_size);
1729 free(intermediate_key);
1730 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001731 return rc;
1732}
1733
Ken Sumrall29d8da82011-05-18 17:20:07 -07001734/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001735 * Called by vold when it's asked to mount an encrypted external
1736 * storage volume. The incoming partition has no crypto header/footer,
1737 * as any metadata is been stored in a separate, small partition.
1738 *
1739 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001740 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001741int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1742 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001743 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001744 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001745 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001746 return -1;
1747 }
1748
1749 unsigned long nr_sec = 0;
1750 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001751 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001752
Ken Sumrall29d8da82011-05-18 17:20:07 -07001753 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001754 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001755 return -1;
1756 }
1757
Jeff Sharkey9c484982015-03-31 10:35:33 -07001758 struct crypt_mnt_ftr ext_crypt_ftr;
1759 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1760 ext_crypt_ftr.fs_size = nr_sec;
1761 ext_crypt_ftr.keysize = keysize;
1762 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001763
Jeff Sharkey9c484982015-03-31 10:35:33 -07001764 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1765 out_crypto_blkdev, label);
1766}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001767
Jeff Sharkey9c484982015-03-31 10:35:33 -07001768/*
1769 * Called by vold when it's asked to unmount an encrypted external
1770 * storage volume.
1771 */
1772int cryptfs_revert_ext_volume(const char* label) {
1773 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001774}
1775
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001776int cryptfs_crypto_complete(void)
1777{
1778 return do_crypto_complete("/data");
1779}
1780
Paul Lawrencef4faa572014-01-29 13:31:03 -08001781int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1782{
1783 char encrypted_state[PROPERTY_VALUE_MAX];
1784 property_get("ro.crypto.state", encrypted_state, "");
1785 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1786 SLOGE("encrypted fs already validated or not running with encryption,"
1787 " aborting");
1788 return -1;
1789 }
1790
1791 if (get_crypt_ftr_and_key(crypt_ftr)) {
1792 SLOGE("Error getting crypt footer and key");
1793 return -1;
1794 }
1795
1796 return 0;
1797}
1798
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001799int cryptfs_check_passwd(char *passwd)
1800{
Paul Lawrence05335c32015-03-05 09:46:23 -08001801 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001802 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001803 SLOGE("cryptfs_check_passwd not valid for file encryption");
1804 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001805 }
1806
Paul Lawrencef4faa572014-01-29 13:31:03 -08001807 struct crypt_mnt_ftr crypt_ftr;
1808 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001809
Paul Lawrencef4faa572014-01-29 13:31:03 -08001810 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001811 if (rc) {
1812 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001813 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001814 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001815
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001816 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001817 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1818 if (rc) {
1819 SLOGE("Password did not match");
1820 return rc;
1821 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001822
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001823 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1824 // Here we have a default actual password but a real password
1825 // we must test against the scrypted value
1826 // First, we must delete the crypto block device that
1827 // test_mount_encrypted_fs leaves behind as a side effect
1828 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1829 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1830 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1831 if (rc) {
1832 SLOGE("Default password did not match on reboot encryption");
1833 return rc;
1834 }
1835
1836 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1837 put_crypt_ftr_and_key(&crypt_ftr);
1838 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1839 if (rc) {
1840 SLOGE("Could not change password on reboot encryption");
1841 return rc;
1842 }
1843 }
1844
1845 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001846 cryptfs_clear_password();
1847 password = strdup(passwd);
1848 struct timespec now;
1849 clock_gettime(CLOCK_BOOTTIME, &now);
1850 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001851 }
1852
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001853 return rc;
1854}
1855
Ken Sumrall3ad90722011-10-04 20:38:29 -07001856int cryptfs_verify_passwd(char *passwd)
1857{
1858 struct crypt_mnt_ftr crypt_ftr;
1859 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001860 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001861 char encrypted_state[PROPERTY_VALUE_MAX];
1862 int rc;
1863
1864 property_get("ro.crypto.state", encrypted_state, "");
1865 if (strcmp(encrypted_state, "encrypted") ) {
1866 SLOGE("device not encrypted, aborting");
1867 return -2;
1868 }
1869
1870 if (!master_key_saved) {
1871 SLOGE("encrypted fs not yet mounted, aborting");
1872 return -1;
1873 }
1874
1875 if (!saved_mount_point) {
1876 SLOGE("encrypted fs failed to save mount point, aborting");
1877 return -1;
1878 }
1879
Ken Sumrall160b4d62013-04-22 12:15:39 -07001880 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001881 SLOGE("Error getting crypt footer and key\n");
1882 return -1;
1883 }
1884
1885 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1886 /* If the device has no password, then just say the password is valid */
1887 rc = 0;
1888 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001889 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001890 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1891 /* They match, the password is correct */
1892 rc = 0;
1893 } else {
1894 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1895 sleep(1);
1896 rc = 1;
1897 }
1898 }
1899
1900 return rc;
1901}
1902
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903/* Initialize a crypt_mnt_ftr structure. The keysize is
1904 * defaulted to 16 bytes, and the filesystem size to 0.
1905 * Presumably, at a minimum, the caller will update the
1906 * filesystem size and crypto_type_name after calling this function.
1907 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001908static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001909{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001910 off64_t off;
1911
1912 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001913 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001914 ftr->major_version = CURRENT_MAJOR_VERSION;
1915 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001916 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001917 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001918
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001919 switch (keymaster_check_compatibility()) {
1920 case 1:
1921 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1922 break;
1923
1924 case 0:
1925 ftr->kdf_type = KDF_SCRYPT;
1926 break;
1927
1928 default:
1929 SLOGE("keymaster_check_compatibility failed");
1930 return -1;
1931 }
1932
Kenny Rootc4c70f12013-06-14 12:11:38 -07001933 get_device_scrypt_params(ftr);
1934
Ken Sumrall160b4d62013-04-22 12:15:39 -07001935 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1936 if (get_crypt_ftr_info(NULL, &off) == 0) {
1937 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1938 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1939 ftr->persist_data_size;
1940 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001941
1942 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001943}
1944
Ken Sumrall29d8da82011-05-18 17:20:07 -07001945static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001946{
Ken Sumralle550f782013-08-20 13:48:23 -07001947 const char *args[10];
1948 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1949 int num_args;
1950 int status;
1951 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001952 int rc = -1;
1953
Ken Sumrall29d8da82011-05-18 17:20:07 -07001954 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001955#ifdef TARGET_USES_MKE2FS
1956 args[0] = "/system/bin/mke2fs";
1957 args[1] = "-M";
1958 args[2] = "/data";
1959 args[3] = "-b";
1960 args[4] = "4096";
1961 args[5] = "-t";
1962 args[6] = "ext4";
1963 args[7] = crypto_blkdev;
1964 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1965 args[8] = size_str;
1966 num_args = 9;
1967#else
Ken Sumralle550f782013-08-20 13:48:23 -07001968 args[0] = "/system/bin/make_ext4fs";
1969 args[1] = "-a";
1970 args[2] = "/data";
1971 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07001972 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07001973 args[4] = size_str;
1974 args[5] = crypto_blkdev;
1975 num_args = 6;
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001976#endif
Ken Sumralle550f782013-08-20 13:48:23 -07001977 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1978 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001979 } else if (type == F2FS_FS) {
1980 args[0] = "/system/bin/mkfs.f2fs";
1981 args[1] = "-t";
1982 args[2] = "-d1";
1983 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001984 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07001985 args[4] = size_str;
1986 num_args = 5;
1987 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
1988 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001989 } else {
1990 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1991 return -1;
1992 }
1993
Ken Sumralle550f782013-08-20 13:48:23 -07001994 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1995
1996 if (tmp != 0) {
1997 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001998 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001999 if (WIFEXITED(status)) {
2000 if (WEXITSTATUS(status)) {
2001 SLOGE("Error creating filesystem on %s, exit status %d ",
2002 crypto_blkdev, WEXITSTATUS(status));
2003 } else {
2004 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2005 rc = 0;
2006 }
2007 } else {
2008 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2009 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002010 }
2011
2012 return rc;
2013}
2014
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002015#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002016#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2017#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002018
2019/* aligned 32K writes tends to make flash happy.
2020 * SD card association recommends it.
2021 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002022#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002023#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002024#else
2025#define BLOCKS_AT_A_TIME 1024
2026#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002027
2028struct encryptGroupsData
2029{
2030 int realfd;
2031 int cryptofd;
2032 off64_t numblocks;
2033 off64_t one_pct, cur_pct, new_pct;
2034 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002035 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002036 char* real_blkdev, * crypto_blkdev;
2037 int count;
2038 off64_t offset;
2039 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002040 off64_t last_written_sector;
2041 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002042 time_t time_started;
2043 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002044};
2045
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002046static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002047{
2048 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002049
2050 if (is_used) {
2051 data->used_blocks_already_done++;
2052 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002053 if (data->tot_used_blocks) {
2054 data->new_pct = data->used_blocks_already_done / data->one_pct;
2055 } else {
2056 data->new_pct = data->blocks_already_done / data->one_pct;
2057 }
2058
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002059 if (data->new_pct > data->cur_pct) {
2060 char buf[8];
2061 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002062 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002063 property_set("vold.encrypt_progress", buf);
2064 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002065
2066 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002067 struct timespec time_now;
2068 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2069 SLOGW("Error getting time");
2070 } else {
2071 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2072 off64_t remaining_blocks = data->tot_used_blocks
2073 - data->used_blocks_already_done;
2074 int remaining_time = (int)(elapsed_time * remaining_blocks
2075 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002076
Paul Lawrence9c58a872014-09-30 09:12:51 -07002077 // Change time only if not yet set, lower, or a lot higher for
2078 // best user experience
2079 if (data->remaining_time == -1
2080 || remaining_time < data->remaining_time
2081 || remaining_time > data->remaining_time + 60) {
2082 char buf[8];
2083 snprintf(buf, sizeof(buf), "%d", remaining_time);
2084 property_set("vold.encrypt_time_remaining", buf);
2085 data->remaining_time = remaining_time;
2086 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002087 }
2088 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002089}
2090
Paul Lawrence3846be12014-09-22 11:33:54 -07002091static void log_progress(struct encryptGroupsData const* data, bool completed)
2092{
2093 // Precondition - if completed data = 0 else data != 0
2094
2095 // Track progress so we can skip logging blocks
2096 static off64_t offset = -1;
2097
2098 // Need to close existing 'Encrypting from' log?
2099 if (completed || (offset != -1 && data->offset != offset)) {
2100 SLOGI("Encrypted to sector %" PRId64,
2101 offset / info.block_size * CRYPT_SECTOR_SIZE);
2102 offset = -1;
2103 }
2104
2105 // Need to start new 'Encrypting from' log?
2106 if (!completed && offset != data->offset) {
2107 SLOGI("Encrypting from sector %" PRId64,
2108 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2109 }
2110
2111 // Update offset
2112 if (!completed) {
2113 offset = data->offset + (off64_t)data->count * info.block_size;
2114 }
2115}
2116
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002117static int flush_outstanding_data(struct encryptGroupsData* data)
2118{
2119 if (data->count == 0) {
2120 return 0;
2121 }
2122
Elliott Hughes231bdba2014-06-25 18:36:19 -07002123 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002124
2125 if (pread64(data->realfd, data->buffer,
2126 info.block_size * data->count, data->offset)
2127 <= 0) {
2128 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2129 data->real_blkdev);
2130 return -1;
2131 }
2132
2133 if (pwrite64(data->cryptofd, data->buffer,
2134 info.block_size * data->count, data->offset)
2135 <= 0) {
2136 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2137 data->crypto_blkdev);
2138 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002139 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002140 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002141 }
2142
2143 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002144 data->last_written_sector = (data->offset + data->count)
2145 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002146 return 0;
2147}
2148
2149static int encrypt_groups(struct encryptGroupsData* data)
2150{
2151 unsigned int i;
2152 u8 *block_bitmap = 0;
2153 unsigned int block;
2154 off64_t ret;
2155 int rc = -1;
2156
2157 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2158 if (!data->buffer) {
2159 SLOGE("Failed to allocate crypto buffer");
2160 goto errout;
2161 }
2162
2163 block_bitmap = malloc(info.block_size);
2164 if (!block_bitmap) {
2165 SLOGE("failed to allocate block bitmap");
2166 goto errout;
2167 }
2168
2169 for (i = 0; i < aux_info.groups; ++i) {
2170 SLOGI("Encrypting group %d", i);
2171
2172 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2173 u32 block_count = min(info.blocks_per_group,
2174 aux_info.len_blocks - first_block);
2175
2176 off64_t offset = (u64)info.block_size
2177 * aux_info.bg_desc[i].bg_block_bitmap;
2178
2179 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2180 if (ret != (int)info.block_size) {
2181 SLOGE("failed to read all of block group bitmap %d", i);
2182 goto errout;
2183 }
2184
2185 offset = (u64)info.block_size * first_block;
2186
2187 data->count = 0;
2188
2189 for (block = 0; block < block_count; block++) {
liminghaoaa08e582016-01-06 10:30:49 +08002190 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
2191 0 : bitmap_get_bit(block_bitmap, block);
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002192 update_progress(data, used);
2193 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002194 if (data->count == 0) {
2195 data->offset = offset;
2196 }
2197 data->count++;
2198 } else {
2199 if (flush_outstanding_data(data)) {
2200 goto errout;
2201 }
2202 }
2203
2204 offset += info.block_size;
2205
2206 /* Write data if we are aligned or buffer size reached */
2207 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2208 || data->count == BLOCKS_AT_A_TIME) {
2209 if (flush_outstanding_data(data)) {
2210 goto errout;
2211 }
2212 }
Paul Lawrence87999172014-02-20 12:21:31 -08002213
Paul Lawrence73d7a022014-06-09 14:10:09 -07002214 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002215 SLOGE("Stopping encryption due to low battery");
2216 rc = 0;
2217 goto errout;
2218 }
2219
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002220 }
2221 if (flush_outstanding_data(data)) {
2222 goto errout;
2223 }
2224 }
2225
Paul Lawrence87999172014-02-20 12:21:31 -08002226 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002227 rc = 0;
2228
2229errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002230 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002231 free(data->buffer);
2232 free(block_bitmap);
2233 return rc;
2234}
2235
2236static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2237 char *real_blkdev,
2238 off64_t size,
2239 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002240 off64_t tot_size,
2241 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002242{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002243 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002244 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002245 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002246
Paul Lawrence87999172014-02-20 12:21:31 -08002247 if (previously_encrypted_upto > *size_already_done) {
2248 SLOGD("Not fast encrypting since resuming part way through");
2249 return -1;
2250 }
2251
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002252 memset(&data, 0, sizeof(data));
2253 data.real_blkdev = real_blkdev;
2254 data.crypto_blkdev = crypto_blkdev;
2255
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002256 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002257 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2258 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002259 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002260 goto errout;
2261 }
2262
David Ng82fd8042015-01-21 13:55:21 -08002263 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2264 int retries = RETRY_MOUNT_ATTEMPTS;
2265 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2266 if (--retries) {
2267 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2268 crypto_blkdev, errno, strerror(errno));
2269 sleep(RETRY_MOUNT_DELAY_SECONDS);
2270 } else {
2271 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2272 crypto_blkdev, errno, strerror(errno));
2273 rc = ENABLE_INPLACE_ERR_DEV;
2274 goto errout;
2275 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002276 }
2277
2278 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002279 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002280 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002281 goto errout;
2282 }
2283
2284 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002285 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002286 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002287 goto errout;
2288 }
2289
2290 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2291 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2292 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2293
JP Abgrall7fc1de82014-10-10 18:43:41 -07002294 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002295
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002296 data.tot_used_blocks = data.numblocks;
2297 for (i = 0; i < aux_info.groups; ++i) {
2298 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2299 }
2300
2301 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002302 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002303
2304 struct timespec time_started = {0};
2305 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2306 SLOGW("Error getting time at start");
2307 // Note - continue anyway - we'll run with 0
2308 }
2309 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002310 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002311
2312 rc = encrypt_groups(&data);
2313 if (rc) {
2314 SLOGE("Error encrypting groups");
2315 goto errout;
2316 }
2317
Paul Lawrence87999172014-02-20 12:21:31 -08002318 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002319 rc = 0;
2320
2321errout:
2322 close(data.realfd);
2323 close(data.cryptofd);
2324
2325 return rc;
2326}
2327
Paul Lawrence3846be12014-09-22 11:33:54 -07002328static void log_progress_f2fs(u64 block, bool completed)
2329{
2330 // Precondition - if completed data = 0 else data != 0
2331
2332 // Track progress so we can skip logging blocks
2333 static u64 last_block = (u64)-1;
2334
2335 // Need to close existing 'Encrypting from' log?
2336 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2337 SLOGI("Encrypted to block %" PRId64, last_block);
2338 last_block = -1;
2339 }
2340
2341 // Need to start new 'Encrypting from' log?
2342 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2343 SLOGI("Encrypting from block %" PRId64, block);
2344 }
2345
2346 // Update offset
2347 if (!completed) {
2348 last_block = block;
2349 }
2350}
2351
Daniel Rosenberge82df162014-08-15 22:19:23 +00002352static int encrypt_one_block_f2fs(u64 pos, void *data)
2353{
2354 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2355
2356 priv_dat->blocks_already_done = pos - 1;
2357 update_progress(priv_dat, 1);
2358
2359 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2360
2361 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002362 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002363 return -1;
2364 }
2365
2366 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002367 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002368 return -1;
2369 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002370 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002371 }
2372
2373 return 0;
2374}
2375
2376static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2377 char *real_blkdev,
2378 off64_t size,
2379 off64_t *size_already_done,
2380 off64_t tot_size,
2381 off64_t previously_encrypted_upto)
2382{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002383 struct encryptGroupsData data;
2384 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002385 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002386 if (previously_encrypted_upto > *size_already_done) {
2387 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002388 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002389 }
2390 memset(&data, 0, sizeof(data));
2391 data.real_blkdev = real_blkdev;
2392 data.crypto_blkdev = crypto_blkdev;
2393 data.realfd = -1;
2394 data.cryptofd = -1;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002395 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002396 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002397 real_blkdev);
2398 goto errout;
2399 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002400 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002401 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002402 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002403 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002404 goto errout;
2405 }
2406
2407 f2fs_info = generate_f2fs_info(data.realfd);
2408 if (!f2fs_info)
2409 goto errout;
2410
2411 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2412 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2413 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2414
2415 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2416
2417 data.one_pct = data.tot_used_blocks / 100;
2418 data.cur_pct = 0;
2419 data.time_started = time(NULL);
2420 data.remaining_time = -1;
2421
2422 data.buffer = malloc(f2fs_info->block_size);
2423 if (!data.buffer) {
2424 SLOGE("Failed to allocate crypto buffer");
2425 goto errout;
2426 }
2427
2428 data.count = 0;
2429
2430 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2431 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2432
2433 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002434 SLOGE("Error in running over f2fs blocks");
2435 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002436 goto errout;
2437 }
2438
2439 *size_already_done += size;
2440 rc = 0;
2441
2442errout:
2443 if (rc)
2444 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2445
Paul Lawrence3846be12014-09-22 11:33:54 -07002446 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002447 free(f2fs_info);
2448 free(data.buffer);
2449 close(data.realfd);
2450 close(data.cryptofd);
2451
2452 return rc;
2453}
2454
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002455static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2456 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002457 off64_t tot_size,
2458 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002459{
2460 int realfd, cryptofd;
2461 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002462 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002463 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002464 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002465 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002466
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002467 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002468 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002469 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002470 }
2471
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002472 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002473 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2474 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002475 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002476 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002477 }
2478
2479 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2480 * The size passed in is the number of 512 byte sectors in the filesystem.
2481 * So compute the number of whole 4K blocks we should read/write,
2482 * and the remainder.
2483 */
2484 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2485 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002486 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2487 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002488
2489 SLOGE("Encrypting filesystem in place...");
2490
Paul Lawrence87999172014-02-20 12:21:31 -08002491 i = previously_encrypted_upto + 1 - *size_already_done;
2492
2493 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2494 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2495 goto errout;
2496 }
2497
2498 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2499 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2500 goto errout;
2501 }
2502
2503 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2504 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2505 SLOGE("Error reading initial sectors from real_blkdev %s for "
2506 "inplace encrypt\n", crypto_blkdev);
2507 goto errout;
2508 }
2509 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2510 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2511 "inplace encrypt\n", crypto_blkdev);
2512 goto errout;
2513 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002514 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002515 }
2516 }
2517
Ken Sumrall29d8da82011-05-18 17:20:07 -07002518 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002519 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002520 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002521 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002522 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002523 if (new_pct > cur_pct) {
2524 char buf[8];
2525
2526 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002527 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002528 property_set("vold.encrypt_progress", buf);
2529 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002530 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002531 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002532 goto errout;
2533 }
2534 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002535 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2536 goto errout;
2537 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002538 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002539 CRYPT_SECTORS_PER_BUFSIZE,
2540 i * CRYPT_SECTORS_PER_BUFSIZE);
2541 }
2542
Paul Lawrence73d7a022014-06-09 14:10:09 -07002543 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002544 SLOGE("Stopping encryption due to low battery");
2545 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2546 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002547 goto errout;
2548 }
2549 }
2550
2551 /* Do any remaining sectors */
2552 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002553 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2554 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002555 goto errout;
2556 }
Paul Lawrence87999172014-02-20 12:21:31 -08002557 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2558 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002559 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002560 } else {
2561 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002562 }
2563 }
2564
Ken Sumrall29d8da82011-05-18 17:20:07 -07002565 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002566 rc = 0;
2567
2568errout:
2569 close(realfd);
2570 close(cryptofd);
2571
2572 return rc;
2573}
2574
JP Abgrall7fc1de82014-10-10 18:43:41 -07002575/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002576static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2577 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002578 off64_t tot_size,
2579 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002580{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002581 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002582 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002583 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002584 }
2585
2586 if (*size_already_done + size < previously_encrypted_upto) {
2587 *size_already_done += size;
2588 return 0;
2589 }
2590
Daniel Rosenberge82df162014-08-15 22:19:23 +00002591 /* TODO: identify filesystem type.
2592 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2593 * then we will drop down to cryptfs_enable_inplace_f2fs.
2594 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002595 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002596 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002597 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002598 return 0;
2599 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002600 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002601
JP Abgrall7fc1de82014-10-10 18:43:41 -07002602 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002603 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002604 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002605 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002606 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002607 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002608
JP Abgrall7fc1de82014-10-10 18:43:41 -07002609 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002610 size, size_already_done, tot_size,
2611 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002612 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2613
2614 /* Hack for b/17898962, the following is the symptom... */
2615 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2616 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2617 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2618 return ENABLE_INPLACE_ERR_DEV;
2619 }
2620 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002621}
2622
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002623#define CRYPTO_ENABLE_WIPE 1
2624#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002625
2626#define FRAMEWORK_BOOT_WAIT 60
2627
Paul Lawrence87999172014-02-20 12:21:31 -08002628static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2629{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002630 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002631 if (fd == -1) {
2632 SLOGE("Error opening file %s", filename);
2633 return -1;
2634 }
2635
2636 char block[CRYPT_INPLACE_BUFSIZE];
2637 memset(block, 0, sizeof(block));
2638 if (unix_read(fd, block, sizeof(block)) < 0) {
2639 SLOGE("Error reading file %s", filename);
2640 close(fd);
2641 return -1;
2642 }
2643
2644 close(fd);
2645
2646 SHA256_CTX c;
2647 SHA256_Init(&c);
2648 SHA256_Update(&c, block, sizeof(block));
2649 SHA256_Final(buf, &c);
2650
2651 return 0;
2652}
2653
JP Abgrall62c7af32014-06-16 13:01:23 -07002654static int get_fs_type(struct fstab_rec *rec)
2655{
2656 if (!strcmp(rec->fs_type, "ext4")) {
2657 return EXT4_FS;
2658 } else if (!strcmp(rec->fs_type, "f2fs")) {
2659 return F2FS_FS;
2660 } else {
2661 return -1;
2662 }
2663}
2664
Paul Lawrence87999172014-02-20 12:21:31 -08002665static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2666 char *crypto_blkdev, char *real_blkdev,
2667 int previously_encrypted_upto)
2668{
2669 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002670 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002671
Paul Lawrence73d7a022014-06-09 14:10:09 -07002672 if (!is_battery_ok_to_start()) {
2673 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002674 return 0;
2675 }
2676
2677 /* The size of the userdata partition, and add in the vold volumes below */
2678 tot_encryption_size = crypt_ftr->fs_size;
2679
2680 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002681 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2682 int fs_type = get_fs_type(rec);
2683 if (fs_type < 0) {
2684 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2685 return -1;
2686 }
2687 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002688 } else if (how == CRYPTO_ENABLE_INPLACE) {
2689 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2690 crypt_ftr->fs_size, &cur_encryption_done,
2691 tot_encryption_size,
2692 previously_encrypted_upto);
2693
JP Abgrall7fc1de82014-10-10 18:43:41 -07002694 if (rc == ENABLE_INPLACE_ERR_DEV) {
2695 /* Hack for b/17898962 */
2696 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2697 cryptfs_reboot(reboot);
2698 }
2699
Paul Lawrence73d7a022014-06-09 14:10:09 -07002700 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002701 crypt_ftr->encrypted_upto = cur_encryption_done;
2702 }
2703
Paul Lawrence73d7a022014-06-09 14:10:09 -07002704 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002705 /* The inplace routine never actually sets the progress to 100% due
2706 * to the round down nature of integer division, so set it here */
2707 property_set("vold.encrypt_progress", "100");
2708 }
2709 } else {
2710 /* Shouldn't happen */
2711 SLOGE("cryptfs_enable: internal error, unknown option\n");
2712 rc = -1;
2713 }
2714
2715 return rc;
2716}
2717
Paul Lawrence13486032014-02-03 13:28:11 -08002718int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002719 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002720{
2721 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002722 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002723 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002724 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002725 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002726 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002727 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002728 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002729 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002730 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002731 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002732 bool rebootEncryption = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002733
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002734 if (!strcmp(howarg, "wipe")) {
2735 how = CRYPTO_ENABLE_WIPE;
2736 } else if (! strcmp(howarg, "inplace")) {
2737 how = CRYPTO_ENABLE_INPLACE;
2738 } else {
2739 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002740 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002741 }
2742
Paul Lawrence87999172014-02-20 12:21:31 -08002743 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002744 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2745 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2746 /* An encryption was underway and was interrupted */
2747 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2748 crypt_ftr.encrypted_upto = 0;
2749 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002750
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002751 /* At this point, we are in an inconsistent state. Until we successfully
2752 complete encryption, a reboot will leave us broken. So mark the
2753 encryption failed in case that happens.
2754 On successfully completing encryption, remove this flag */
2755 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002756
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002757 put_crypt_ftr_and_key(&crypt_ftr);
2758 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2759 if (!check_ftr_sha(&crypt_ftr)) {
2760 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2761 put_crypt_ftr_and_key(&crypt_ftr);
2762 goto error_unencrypted;
2763 }
2764
2765 /* Doing a reboot-encryption*/
2766 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2767 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2768 rebootEncryption = true;
2769 }
Paul Lawrence87999172014-02-20 12:21:31 -08002770 }
2771
2772 property_get("ro.crypto.state", encrypted_state, "");
2773 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2774 SLOGE("Device is already running encrypted, aborting");
2775 goto error_unencrypted;
2776 }
2777
2778 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2779 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002780 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002781
Ken Sumrall3ed82362011-01-28 23:31:16 -08002782 /* Get the size of the real block device */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002783 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002784 if (fd == -1) {
2785 SLOGE("Cannot open block device %s\n", real_blkdev);
2786 goto error_unencrypted;
2787 }
2788 unsigned long nr_sec;
2789 get_blkdev_size(fd, &nr_sec);
2790 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002791 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2792 goto error_unencrypted;
2793 }
2794 close(fd);
2795
2796 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002797 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002798 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002799 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002800 if (fs_size_sec == 0)
2801 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2802
Paul Lawrence87999172014-02-20 12:21:31 -08002803 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002804
2805 if (fs_size_sec > max_fs_size_sec) {
2806 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2807 goto error_unencrypted;
2808 }
2809 }
2810
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002811 /* Get a wakelock as this may take a while, and we don't want the
2812 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2813 * wants to keep the screen on, it can grab a full wakelock.
2814 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002815 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002816 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2817
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002818 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002819 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002820 */
2821 property_set("vold.decrypt", "trigger_shutdown_framework");
2822 SLOGD("Just asked init to shut down class main\n");
2823
Jeff Sharkey9c484982015-03-31 10:35:33 -07002824 /* Ask vold to unmount all devices that it manages */
2825 if (vold_unmountAll()) {
2826 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002827 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002828
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002829 /* no_ui means we are being called from init, not settings.
2830 Now we always reboot from settings, so !no_ui means reboot
2831 */
2832 bool onlyCreateHeader = false;
2833 if (!no_ui) {
2834 /* Try fallback, which is to reboot and try there */
2835 onlyCreateHeader = true;
2836 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2837 if (breadcrumb == 0) {
2838 SLOGE("Failed to create breadcrumb file");
2839 goto error_shutting_down;
2840 }
2841 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002842 }
2843
2844 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002845 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002846 /* Now that /data is unmounted, we need to mount a tmpfs
2847 * /data, set a property saying we're doing inplace encryption,
2848 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002849 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002850 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002851 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002852 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002853 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002854 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002855
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002856 /* restart the framework. */
2857 /* Create necessary paths on /data */
2858 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002859 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002860 }
2861
Ken Sumrall92736ef2012-10-17 20:57:14 -07002862 /* Ugh, shutting down the framework is not synchronous, so until it
2863 * can be fixed, this horrible hack will wait a moment for it all to
2864 * shut down before proceeding. Without it, some devices cannot
2865 * restart the graphics services.
2866 */
2867 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002868 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002869
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002870 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002871 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002872 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002873 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2874 goto error_shutting_down;
2875 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002876
Paul Lawrence87999172014-02-20 12:21:31 -08002877 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2878 crypt_ftr.fs_size = nr_sec
2879 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2880 } else {
2881 crypt_ftr.fs_size = nr_sec;
2882 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002883 /* At this point, we are in an inconsistent state. Until we successfully
2884 complete encryption, a reboot will leave us broken. So mark the
2885 encryption failed in case that happens.
2886 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002887 if (onlyCreateHeader) {
2888 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2889 } else {
2890 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2891 }
Paul Lawrence87999172014-02-20 12:21:31 -08002892 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002893#ifndef CONFIG_HW_DISK_ENCRYPTION
2894 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
2895#else
2896 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
2897
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08002898 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07002899 if (!rc) {
2900 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
2901 }
2902
2903 rc = set_hw_device_encryption_key(passwd,
2904 (char*) crypt_ftr.crypto_type_name);
2905 if (!rc) {
2906 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
2907 goto error_shutting_down;
2908 }
2909#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002910
Paul Lawrence87999172014-02-20 12:21:31 -08002911 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002912 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2913 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002914 SLOGE("Cannot create encrypted master key\n");
2915 goto error_shutting_down;
2916 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002917
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002918 /* Replace scrypted intermediate key if we are preparing for a reboot */
2919 if (onlyCreateHeader) {
2920 unsigned char fake_master_key[KEY_LEN_BYTES];
2921 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2922 memset(fake_master_key, 0, sizeof(fake_master_key));
2923 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2924 encrypted_fake_master_key, &crypt_ftr);
2925 }
2926
Paul Lawrence87999172014-02-20 12:21:31 -08002927 /* Write the key to the end of the partition */
2928 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002929
Paul Lawrence87999172014-02-20 12:21:31 -08002930 /* If any persistent data has been remembered, save it.
2931 * If none, create a valid empty table and save that.
2932 */
2933 if (!persist_data) {
2934 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2935 if (pdata) {
2936 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2937 persist_data = pdata;
2938 }
2939 }
2940 if (persist_data) {
2941 save_persistent_data();
2942 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002943 }
2944
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002945 if (onlyCreateHeader) {
2946 sleep(2);
2947 cryptfs_reboot(reboot);
2948 }
2949
2950 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002951 /* startup service classes main and late_start */
2952 property_set("vold.decrypt", "trigger_restart_min_framework");
2953 SLOGD("Just triggered restart_min_framework\n");
2954
2955 /* OK, the framework is restarted and will soon be showing a
2956 * progress bar. Time to setup an encrypted mapping, and
2957 * either write a new filesystem, or encrypt in place updating
2958 * the progress bar as we work.
2959 */
2960 }
2961
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002962 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002963 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002964 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002965
Paul Lawrence87999172014-02-20 12:21:31 -08002966 /* If we are continuing, check checksums match */
2967 rc = 0;
2968 if (previously_encrypted_upto) {
2969 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2970 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002971
Paul Lawrence87999172014-02-20 12:21:31 -08002972 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2973 sizeof(hash_first_block)) != 0) {
2974 SLOGE("Checksums do not match - trigger wipe");
2975 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002976 }
2977 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002978
Paul Lawrence87999172014-02-20 12:21:31 -08002979 if (!rc) {
2980 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2981 crypto_blkdev, real_blkdev,
2982 previously_encrypted_upto);
2983 }
2984
2985 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002986 if (!rc && how == CRYPTO_ENABLE_INPLACE
2987 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002988 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2989 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002990 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002991 SLOGE("Error calculating checksum for continuing encryption");
2992 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002993 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002994 }
2995
2996 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002997 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002998
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002999 if (! rc) {
3000 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003001 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003002
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003003 if (how == CRYPTO_ENABLE_INPLACE
3004 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003005 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3006 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003007 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003008 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003009
Paul Lawrence6bfed202014-07-28 12:47:22 -07003010 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003011
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003012 if (how == CRYPTO_ENABLE_WIPE
3013 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003014 char value[PROPERTY_VALUE_MAX];
3015 property_get("ro.crypto.state", value, "");
3016 if (!strcmp(value, "")) {
3017 /* default encryption - continue first boot sequence */
3018 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08003019 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003020 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003021 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
3022 // Bring up cryptkeeper that will check the password and set it
3023 property_set("vold.decrypt", "trigger_shutdown_framework");
3024 sleep(2);
3025 property_set("vold.encrypt_progress", "");
3026 cryptfs_trigger_restart_min_framework();
3027 } else {
3028 cryptfs_check_passwd(DEFAULT_PASSWORD);
3029 cryptfs_restart_internal(1);
3030 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003031 return 0;
3032 } else {
3033 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003034 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003035 }
Paul Lawrence87999172014-02-20 12:21:31 -08003036 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003037 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003038 cryptfs_reboot(shutdown);
3039 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003040 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003041 char value[PROPERTY_VALUE_MAX];
3042
Ken Sumrall319369a2012-06-27 16:30:18 -07003043 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003044 if (!strcmp(value, "1")) {
3045 /* wipe data if encryption failed */
3046 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Yabin Cuiffa2e092016-04-06 17:21:38 -07003047 if (!write_bootloader_message("--wipe_data\n--reason=cryptfs_enable_internal\n")) {
3048 SLOGE("could not write bootloader message\n");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003049 }
Paul Lawrence87999172014-02-20 12:21:31 -08003050 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003051 } else {
3052 /* set property to trigger dialog */
3053 property_set("vold.encrypt_progress", "error_partially_encrypted");
3054 release_wake_lock(lockid);
3055 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003056 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003057 }
3058
Ken Sumrall3ed82362011-01-28 23:31:16 -08003059 /* hrm, the encrypt step claims success, but the reboot failed.
3060 * This should not happen.
3061 * Set the property and return. Hope the framework can deal with it.
3062 */
3063 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003064 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003065 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003066
3067error_unencrypted:
3068 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003069 if (lockid[0]) {
3070 release_wake_lock(lockid);
3071 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003072 return -1;
3073
3074error_shutting_down:
3075 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3076 * but the framework is stopped and not restarted to show the error, so it's up to
3077 * vold to restart the system.
3078 */
3079 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003080 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003081
3082 /* shouldn't get here */
3083 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003084 if (lockid[0]) {
3085 release_wake_lock(lockid);
3086 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003087 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003088}
3089
Paul Lawrence569649f2015-09-09 12:13:00 -07003090int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003091{
Paul Lawrence569649f2015-09-09 12:13:00 -07003092 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003093}
3094
Paul Lawrence569649f2015-09-09 12:13:00 -07003095int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003096{
3097 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07003098 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003099}
3100
3101int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003102{
Paul Crowley38132a12016-02-09 09:50:32 +00003103 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003104 SLOGE("cryptfs_changepw not valid for file encryption");
3105 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003106 }
3107
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003108 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003109 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003110
3111 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003112 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003113 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003114 return -1;
3115 }
3116
Paul Lawrencef4faa572014-01-29 13:31:03 -08003117 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3118 SLOGE("Invalid crypt_type %d", crypt_type);
3119 return -1;
3120 }
3121
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003122 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003123 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003124 SLOGE("Error getting crypt footer and key");
3125 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003126 }
3127
Paul Lawrencef4faa572014-01-29 13:31:03 -08003128 crypt_ftr.crypt_type = crypt_type;
3129
JP Abgrall933216c2015-02-11 13:44:32 -08003130 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003131 : newpw,
3132 crypt_ftr.salt,
3133 saved_master_key,
3134 crypt_ftr.master_key,
3135 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003136 if (rc) {
3137 SLOGE("Encrypt master key failed: %d", rc);
3138 return -1;
3139 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003140 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003141 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003142
Ajay Dudani87701e22014-09-17 21:02:52 -07003143#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003144 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3145 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3146 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3147 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3148 if (!rc)
3149 return -1;
3150 } else {
3151 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3152 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3153 if (!rc)
3154 return -1;
3155 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003156 }
3157#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003158 return 0;
3159}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003160
Rubin Xu85c01f92014-10-13 12:49:54 +01003161static unsigned int persist_get_max_entries(int encrypted) {
3162 struct crypt_mnt_ftr crypt_ftr;
3163 unsigned int dsize;
3164 unsigned int max_persistent_entries;
3165
3166 /* If encrypted, use the values from the crypt_ftr, otherwise
3167 * use the values for the current spec.
3168 */
3169 if (encrypted) {
3170 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3171 return -1;
3172 }
3173 dsize = crypt_ftr.persist_data_size;
3174 } else {
3175 dsize = CRYPT_PERSIST_DATA_SIZE;
3176 }
3177
3178 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3179 sizeof(struct crypt_persist_entry);
3180
3181 return max_persistent_entries;
3182}
3183
3184static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003185{
3186 unsigned int i;
3187
3188 if (persist_data == NULL) {
3189 return -1;
3190 }
3191 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3192 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3193 /* We found it! */
3194 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3195 return 0;
3196 }
3197 }
3198
3199 return -1;
3200}
3201
Rubin Xu85c01f92014-10-13 12:49:54 +01003202static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003203{
3204 unsigned int i;
3205 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003206 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003207
3208 if (persist_data == NULL) {
3209 return -1;
3210 }
3211
Rubin Xu85c01f92014-10-13 12:49:54 +01003212 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003213
3214 num = persist_data->persist_valid_entries;
3215
3216 for (i = 0; i < num; i++) {
3217 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3218 /* We found an existing entry, update it! */
3219 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3220 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3221 return 0;
3222 }
3223 }
3224
3225 /* We didn't find it, add it to the end, if there is room */
3226 if (persist_data->persist_valid_entries < max_persistent_entries) {
3227 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3228 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3229 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3230 persist_data->persist_valid_entries++;
3231 return 0;
3232 }
3233
3234 return -1;
3235}
3236
Rubin Xu85c01f92014-10-13 12:49:54 +01003237/**
3238 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3239 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3240 */
3241static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003242 unsigned int field_len;
3243 unsigned int key_index;
3244 field_len = strlen(field);
3245
3246 if (index == 0) {
3247 // The first key in a multi-entry field is just the filedname itself.
3248 if (!strcmp(key, field)) {
3249 return 1;
3250 }
3251 }
3252 // Match key against "%s_%d" % (field, index)
3253 if (strlen(key) < field_len + 1 + 1) {
3254 // Need at least a '_' and a digit.
3255 return 0;
3256 }
3257 if (strncmp(key, field, field_len)) {
3258 // If the key does not begin with field, it's not a match.
3259 return 0;
3260 }
3261 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3262 return 0;
3263 }
3264 return key_index >= index;
3265}
3266
3267/*
3268 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3269 * remaining entries starting from index will be deleted.
3270 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3271 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3272 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3273 *
3274 */
3275static int persist_del_keys(const char *fieldname, unsigned index)
3276{
3277 unsigned int i;
3278 unsigned int j;
3279 unsigned int num;
3280
3281 if (persist_data == NULL) {
3282 return PERSIST_DEL_KEY_ERROR_OTHER;
3283 }
3284
3285 num = persist_data->persist_valid_entries;
3286
3287 j = 0; // points to the end of non-deleted entries.
3288 // Filter out to-be-deleted entries in place.
3289 for (i = 0; i < num; i++) {
3290 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3291 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3292 j++;
3293 }
3294 }
3295
3296 if (j < num) {
3297 persist_data->persist_valid_entries = j;
3298 // Zeroise the remaining entries
3299 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3300 return PERSIST_DEL_KEY_OK;
3301 } else {
3302 // Did not find an entry matching the given fieldname
3303 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3304 }
3305}
3306
3307static int persist_count_keys(const char *fieldname)
3308{
3309 unsigned int i;
3310 unsigned int count;
3311
3312 if (persist_data == NULL) {
3313 return -1;
3314 }
3315
3316 count = 0;
3317 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3318 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3319 count++;
3320 }
3321 }
3322
3323 return count;
3324}
3325
Ken Sumrall160b4d62013-04-22 12:15:39 -07003326/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003327int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003328{
Paul Crowley38132a12016-02-09 09:50:32 +00003329 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003330 SLOGE("Cannot get field when file encrypted");
3331 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003332 }
3333
Ken Sumrall160b4d62013-04-22 12:15:39 -07003334 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003335 /* CRYPTO_GETFIELD_OK is success,
3336 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3337 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3338 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003339 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003340 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3341 int i;
3342 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003343
3344 if (persist_data == NULL) {
3345 load_persistent_data();
3346 if (persist_data == NULL) {
3347 SLOGE("Getfield error, cannot load persistent data");
3348 goto out;
3349 }
3350 }
3351
Rubin Xu85c01f92014-10-13 12:49:54 +01003352 // Read value from persistent entries. If the original value is split into multiple entries,
3353 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003354 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003355 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3356 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3357 // value too small
3358 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3359 goto out;
3360 }
3361 rc = CRYPTO_GETFIELD_OK;
3362
3363 for (i = 1; /* break explicitly */; i++) {
3364 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3365 (int) sizeof(temp_field)) {
3366 // If the fieldname is very long, we stop as soon as it begins to overflow the
3367 // maximum field length. At this point we have in fact fully read out the original
3368 // value because cryptfs_setfield would not allow fields with longer names to be
3369 // written in the first place.
3370 break;
3371 }
3372 if (!persist_get_key(temp_field, temp_value)) {
3373 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3374 // value too small.
3375 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3376 goto out;
3377 }
3378 } else {
3379 // Exhaust all entries.
3380 break;
3381 }
3382 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003383 } else {
3384 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003385 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003386 }
3387
3388out:
3389 return rc;
3390}
3391
3392/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003393int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003394{
Paul Crowley38132a12016-02-09 09:50:32 +00003395 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003396 SLOGE("Cannot set field when file encrypted");
3397 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003398 }
3399
Ken Sumrall160b4d62013-04-22 12:15:39 -07003400 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003401 /* 0 is success, negative values are error */
3402 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003403 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003404 unsigned int field_id;
3405 char temp_field[PROPERTY_KEY_MAX];
3406 unsigned int num_entries;
3407 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003408
3409 if (persist_data == NULL) {
3410 load_persistent_data();
3411 if (persist_data == NULL) {
3412 SLOGE("Setfield error, cannot load persistent data");
3413 goto out;
3414 }
3415 }
3416
3417 property_get("ro.crypto.state", encrypted_state, "");
3418 if (!strcmp(encrypted_state, "encrypted") ) {
3419 encrypted = 1;
3420 }
3421
Rubin Xu85c01f92014-10-13 12:49:54 +01003422 // Compute the number of entries required to store value, each entry can store up to
3423 // (PROPERTY_VALUE_MAX - 1) chars
3424 if (strlen(value) == 0) {
3425 // Empty value also needs one entry to store.
3426 num_entries = 1;
3427 } else {
3428 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3429 }
3430
3431 max_keylen = strlen(fieldname);
3432 if (num_entries > 1) {
3433 // Need an extra "_%d" suffix.
3434 max_keylen += 1 + log10(num_entries);
3435 }
3436 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3437 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003438 goto out;
3439 }
3440
Rubin Xu85c01f92014-10-13 12:49:54 +01003441 // Make sure we have enough space to write the new value
3442 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3443 persist_get_max_entries(encrypted)) {
3444 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3445 goto out;
3446 }
3447
3448 // Now that we know persist_data has enough space for value, let's delete the old field first
3449 // to make up space.
3450 persist_del_keys(fieldname, 0);
3451
3452 if (persist_set_key(fieldname, value, encrypted)) {
3453 // fail to set key, should not happen as we have already checked the available space
3454 SLOGE("persist_set_key() error during setfield()");
3455 goto out;
3456 }
3457
3458 for (field_id = 1; field_id < num_entries; field_id++) {
3459 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3460
3461 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3462 // fail to set key, should not happen as we have already checked the available space.
3463 SLOGE("persist_set_key() error during setfield()");
3464 goto out;
3465 }
3466 }
3467
Ken Sumrall160b4d62013-04-22 12:15:39 -07003468 /* If we are running encrypted, save the persistent data now */
3469 if (encrypted) {
3470 if (save_persistent_data()) {
3471 SLOGE("Setfield error, cannot save persistent data");
3472 goto out;
3473 }
3474 }
3475
Rubin Xu85c01f92014-10-13 12:49:54 +01003476 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003477
3478out:
3479 return rc;
3480}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003481
3482/* Checks userdata. Attempt to mount the volume if default-
3483 * encrypted.
3484 * On success trigger next init phase and return 0.
3485 * Currently do not handle failure - see TODO below.
3486 */
3487int cryptfs_mount_default_encrypted(void)
3488{
Paul Lawrence84274cc2016-04-15 15:41:33 -07003489 int crypt_type = cryptfs_get_password_type();
3490 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3491 SLOGE("Bad crypt type - error");
3492 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3493 SLOGD("Password is not default - "
3494 "starting min framework to prompt");
3495 property_set("vold.decrypt", "trigger_restart_min_framework");
3496 return 0;
3497 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3498 SLOGD("Password is default - restarting filesystem");
3499 cryptfs_restart_internal(0);
3500 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003501 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003502 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003503 }
3504
Paul Lawrence6bfed202014-07-28 12:47:22 -07003505 /** Corrupt. Allow us to boot into framework, which will detect bad
3506 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003507 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003508 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003509 return 0;
3510}
3511
3512/* Returns type of the password, default, pattern, pin or password.
3513 */
3514int cryptfs_get_password_type(void)
3515{
Paul Crowley38132a12016-02-09 09:50:32 +00003516 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003517 SLOGE("cryptfs_get_password_type not valid for file encryption");
3518 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003519 }
3520
Paul Lawrencef4faa572014-01-29 13:31:03 -08003521 struct crypt_mnt_ftr crypt_ftr;
3522
3523 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3524 SLOGE("Error getting crypt footer and key\n");
3525 return -1;
3526 }
3527
Paul Lawrence6bfed202014-07-28 12:47:22 -07003528 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3529 return -1;
3530 }
3531
Paul Lawrencef4faa572014-01-29 13:31:03 -08003532 return crypt_ftr.crypt_type;
3533}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003534
Paul Lawrence05335c32015-03-05 09:46:23 -08003535const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003536{
Paul Crowley38132a12016-02-09 09:50:32 +00003537 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003538 SLOGE("cryptfs_get_password not valid for file encryption");
3539 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003540 }
3541
Paul Lawrence399317e2014-03-10 13:20:50 -07003542 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003543 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003544 if (now.tv_sec < password_expiry_time) {
3545 return password;
3546 } else {
3547 cryptfs_clear_password();
3548 return 0;
3549 }
3550}
3551
3552void cryptfs_clear_password()
3553{
3554 if (password) {
3555 size_t len = strlen(password);
3556 memset(password, 0, len);
3557 free(password);
3558 password = 0;
3559 password_expiry_time = 0;
3560 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003561}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003562
3563int cryptfs_enable_file()
3564{
Paul Crowley38132a12016-02-09 09:50:32 +00003565 return e4crypt_initialize_global_de();
Paul Lawrence731a7a22015-04-28 22:14:15 +00003566}
3567
Paul Lawrence0c247462015-10-29 10:30:57 -07003568int cryptfs_isConvertibleToFBE()
3569{
3570 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3571 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
3572}
3573
Paul Lawrence731a7a22015-04-28 22:14:15 +00003574int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3575{
3576 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3577 SLOGE("Failed to initialize crypt_ftr");
3578 return -1;
3579 }
3580
3581 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3582 crypt_ftr->salt, crypt_ftr)) {
3583 SLOGE("Cannot create encrypted master key\n");
3584 return -1;
3585 }
3586
3587 //crypt_ftr->keysize = key_length / 8;
3588 return 0;
3589}
3590
3591int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3592 unsigned char* master_key)
3593{
3594 int rc;
3595
Paul Lawrence731a7a22015-04-28 22:14:15 +00003596 unsigned char* intermediate_key = 0;
3597 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003598
3599 if (password == 0 || *password == 0) {
3600 password = DEFAULT_PASSWORD;
3601 }
3602
Paul Lawrence731a7a22015-04-28 22:14:15 +00003603 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3604 &intermediate_key_size);
3605
Paul Lawrence300dae72016-03-11 11:02:52 -08003606 if (rc) {
3607 SLOGE("Can't calculate intermediate key");
3608 return rc;
3609 }
3610
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003611 int N = 1 << ftr->N_factor;
3612 int r = 1 << ftr->r_factor;
3613 int p = 1 << ftr->p_factor;
3614
3615 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3616
3617 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3618 ftr->salt, sizeof(ftr->salt), N, r, p,
3619 scrypted_intermediate_key,
3620 sizeof(scrypted_intermediate_key));
3621
3622 free(intermediate_key);
3623
3624 if (rc) {
Paul Lawrence300dae72016-03-11 11:02:52 -08003625 SLOGE("Can't scrypt intermediate key");
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003626 return rc;
3627 }
3628
3629 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3630 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00003631}
3632
3633int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3634 const unsigned char* master_key)
3635{
3636 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3637 ftr);
3638}
Paul Lawrence6e410592016-05-24 14:20:38 -07003639
3640const char* cryptfs_get_file_encryption_mode()
3641{
3642 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3643 return fs_mgr_get_file_encryption_mode(rec);
3644}