blob: f500dfea974581cef4725dc2312afd0fca9bd172 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070041#include <ext4_utils/ext4.h>
42#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070058#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000059#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000060#include "f2fs_sparseblock.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080061#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000062#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080063#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070064#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080065extern "C" {
66#include <crypto_scrypt.h>
67}
Mark Salyzyn3e971272014-01-21 13:27:04 -080068
Mark Salyzyn5eecc442014-02-12 14:16:14 -080069#define UNUSED __attribute__((unused))
70
Ken Sumrall8f869aa2010-12-03 03:47:09 -080071#define DM_CRYPT_BUF_SIZE 4096
72
Jason parks70a4b3f2011-01-28 10:10:47 -060073#define HASH_COUNT 2000
74#define KEY_LEN_BYTES 16
75#define IV_LEN_BYTES 16
76
Ken Sumrall29d8da82011-05-18 17:20:07 -070077#define KEY_IN_FOOTER "footer"
78
Paul Lawrence3bd36d52015-06-09 13:37:44 -070079#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080080
Paul Lawrence3d99eba2015-11-20 07:07:19 -080081#define CRYPTO_BLOCK_DEVICE "userdata"
82
83#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
84
Ken Sumrall29d8da82011-05-18 17:20:07 -070085#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070086#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070087
Ken Sumralle919efe2012-09-29 17:07:41 -070088#define TABLE_LOAD_RETRIES 10
89
Shawn Willden47ba10d2014-09-03 17:07:06 -060090#define RSA_KEY_SIZE 2048
91#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
92#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060093#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070094
Paul Lawrence8e3f4512014-09-08 10:11:17 -070095#define RETRY_MOUNT_ATTEMPTS 10
96#define RETRY_MOUNT_DELAY_SECONDS 1
97
Jason parks70a4b3f2011-01-28 10:10:47 -060098static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070099static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600100static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700101static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800102
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700103/* Should we use keymaster? */
104static int keymaster_check_compatibility()
105{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000106 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700107}
108
109/* Create a new keymaster key and store it in this footer */
110static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
111{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800112 if (ftr->keymaster_blob_size) {
113 SLOGI("Already have key");
114 return 0;
115 }
116
Janis Danisevskis015ec302017-01-31 11:31:08 +0000117 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
118 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
119 &ftr->keymaster_blob_size);
120 if (rc) {
121 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
122 SLOGE("Keymaster key blob to large)");
123 ftr->keymaster_blob_size = 0;
124 }
125 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700126 return -1;
127 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000128 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700129}
130
Shawn Willdene17a9c42014-09-08 13:04:08 -0600131/* This signs the given object using the keymaster key. */
132static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600133 const unsigned char *object,
134 const size_t object_size,
135 unsigned char **signature,
136 size_t *signature_size)
137{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600138 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600139 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600140 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600141
Shawn Willdene17a9c42014-09-08 13:04:08 -0600142 // To sign a message with RSA, the message must satisfy two
143 // constraints:
144 //
145 // 1. The message, when interpreted as a big-endian numeric value, must
146 // be strictly less than the public modulus of the RSA key. Note
147 // that because the most significant bit of the public modulus is
148 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
149 // key), an n-bit message with most significant bit 0 always
150 // satisfies this requirement.
151 //
152 // 2. The message must have the same length in bits as the public
153 // modulus of the RSA key. This requirement isn't mathematically
154 // necessary, but is necessary to ensure consistency in
155 // implementations.
156 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600157 case KDF_SCRYPT_KEYMASTER:
158 // This ensures the most significant byte of the signed message
159 // is zero. We could have zero-padded to the left instead, but
160 // this approach is slightly more robust against changes in
161 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600162 // so) because we really should be using a proper deterministic
163 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800164 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600165 SLOGI("Signing safely-padded object");
166 break;
167 default:
168 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000169 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600170 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000171 return keymaster_sign_object_for_cryptfs_scrypt(ftr->keymaster_blob, ftr->keymaster_blob_size,
172 KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign, to_sign_size, signature, signature_size);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600173}
174
Paul Lawrence399317e2014-03-10 13:20:50 -0700175/* Store password when userdata is successfully decrypted and mounted.
176 * Cleared by cryptfs_clear_password
177 *
178 * To avoid a double prompt at boot, we need to store the CryptKeeper
179 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
180 * Since the entire framework is torn down and rebuilt after encryption,
181 * we have to use a daemon or similar to store the password. Since vold
182 * is secured against IPC except from system processes, it seems a reasonable
183 * place to store this.
184 *
185 * password should be cleared once it has been used.
186 *
187 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800188 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700189static char* password = 0;
190static int password_expiry_time = 0;
191static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800192
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800193extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800194
Josh Gaofec44372017-08-28 13:22:55 -0700195enum class RebootType {reboot, recovery, shutdown};
196static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700197{
Josh Gaofec44372017-08-28 13:22:55 -0700198 switch (rt) {
199 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800200 property_set(ANDROID_RB_PROPERTY, "reboot");
201 break;
202
Josh Gaofec44372017-08-28 13:22:55 -0700203 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800204 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
205 break;
206
Josh Gaofec44372017-08-28 13:22:55 -0700207 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800208 property_set(ANDROID_RB_PROPERTY, "shutdown");
209 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700210 }
Paul Lawrence87999172014-02-20 12:21:31 -0800211
Ken Sumralladfba362013-06-04 16:37:52 -0700212 sleep(20);
213
214 /* Shouldn't get here, reboot should happen before sleep times out */
215 return;
216}
217
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800218static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
219{
220 memset(io, 0, dataSize);
221 io->data_size = dataSize;
222 io->data_start = sizeof(struct dm_ioctl);
223 io->version[0] = 4;
224 io->version[1] = 0;
225 io->version[2] = 0;
226 io->flags = flags;
227 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100228 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800229 }
230}
231
Kenny Rootc4c70f12013-06-14 12:11:38 -0700232/**
233 * Gets the default device scrypt parameters for key derivation time tuning.
234 * The parameters should lead to about one second derivation time for the
235 * given device.
236 */
237static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700238 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000239 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700240
Paul Crowley63c18d32016-02-10 14:02:47 +0000241 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
242 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
243 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
244 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700245 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000246 ftr->N_factor = Nf;
247 ftr->r_factor = rf;
248 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700249}
250
Ken Sumrall3ed82362011-01-28 23:31:16 -0800251static unsigned int get_fs_size(char *dev)
252{
253 int fd, block_size;
254 struct ext4_super_block sb;
255 off64_t len;
256
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700257 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800258 SLOGE("Cannot open device to get filesystem size ");
259 return 0;
260 }
261
262 if (lseek64(fd, 1024, SEEK_SET) < 0) {
263 SLOGE("Cannot seek to superblock");
264 return 0;
265 }
266
267 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
268 SLOGE("Cannot read superblock");
269 return 0;
270 }
271
272 close(fd);
273
Daniel Rosenberge82df162014-08-15 22:19:23 +0000274 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
275 SLOGE("Not a valid ext4 superblock");
276 return 0;
277 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800278 block_size = 1024 << sb.s_log_block_size;
279 /* compute length in bytes */
280 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
281
282 /* return length in sectors */
283 return (unsigned int) (len / 512);
284}
285
Ken Sumrall160b4d62013-04-22 12:15:39 -0700286static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
287{
288 static int cached_data = 0;
289 static off64_t cached_off = 0;
290 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
291 int fd;
292 char key_loc[PROPERTY_VALUE_MAX];
293 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700294 int rc = -1;
295
296 if (!cached_data) {
297 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
298
299 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700300 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700301 SLOGE("Cannot open real block device %s\n", real_blkdev);
302 return -1;
303 }
304
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900305 unsigned long nr_sec = 0;
306 get_blkdev_size(fd, &nr_sec);
307 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700308 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
309 * encryption info footer and key, and plenty of bytes to spare for future
310 * growth.
311 */
312 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
313 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
314 cached_data = 1;
315 } else {
316 SLOGE("Cannot get size of block device %s\n", real_blkdev);
317 }
318 close(fd);
319 } else {
320 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
321 cached_off = 0;
322 cached_data = 1;
323 }
324 }
325
326 if (cached_data) {
327 if (metadata_fname) {
328 *metadata_fname = cached_metadata_fname;
329 }
330 if (off) {
331 *off = cached_off;
332 }
333 rc = 0;
334 }
335
336 return rc;
337}
338
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800339/* Set sha256 checksum in structure */
340static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
341{
342 SHA256_CTX c;
343 SHA256_Init(&c);
344 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
345 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
346 SHA256_Final(crypt_ftr->sha256, &c);
347}
348
Ken Sumralle8744072011-01-18 22:01:55 -0800349/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800350 * update the failed mount count but not change the key.
351 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700352static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800353{
354 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800355 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700356 /* starting_off is set to the SEEK_SET offset
357 * where the crypto structure starts
358 */
359 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800360 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700361 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700362 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800363
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800364 set_ftr_sha(crypt_ftr);
365
Ken Sumrall160b4d62013-04-22 12:15:39 -0700366 if (get_crypt_ftr_info(&fname, &starting_off)) {
367 SLOGE("Unable to get crypt_ftr_info\n");
368 return -1;
369 }
370 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700371 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700372 return -1;
373 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700374 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700375 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700376 return -1;
377 }
378
379 /* Seek to the start of the crypt footer */
380 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
381 SLOGE("Cannot seek to real block device footer\n");
382 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800383 }
384
385 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
386 SLOGE("Cannot write real block device footer\n");
387 goto errout;
388 }
389
Ken Sumrall3be890f2011-09-14 16:53:46 -0700390 fstat(fd, &statbuf);
391 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700392 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700393 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800394 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800395 goto errout;
396 }
397 }
398
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800399 /* Success! */
400 rc = 0;
401
402errout:
403 close(fd);
404 return rc;
405
406}
407
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800408static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
409{
410 struct crypt_mnt_ftr copy;
411 memcpy(&copy, crypt_ftr, sizeof(copy));
412 set_ftr_sha(&copy);
413 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
414}
415
Ken Sumrall160b4d62013-04-22 12:15:39 -0700416static inline int unix_read(int fd, void* buff, int len)
417{
418 return TEMP_FAILURE_RETRY(read(fd, buff, len));
419}
420
421static inline int unix_write(int fd, const void* buff, int len)
422{
423 return TEMP_FAILURE_RETRY(write(fd, buff, len));
424}
425
426static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
427{
428 memset(pdata, 0, len);
429 pdata->persist_magic = PERSIST_DATA_MAGIC;
430 pdata->persist_valid_entries = 0;
431}
432
433/* A routine to update the passed in crypt_ftr to the lastest version.
434 * fd is open read/write on the device that holds the crypto footer and persistent
435 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
436 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
437 */
438static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
439{
Kenny Root7434b312013-06-14 11:29:53 -0700440 int orig_major = crypt_ftr->major_version;
441 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700442
Kenny Root7434b312013-06-14 11:29:53 -0700443 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
444 struct crypt_persist_data *pdata;
445 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700446
Kenny Rootc4c70f12013-06-14 12:11:38 -0700447 SLOGW("upgrading crypto footer to 1.1");
448
Wei Wang4375f1b2017-02-24 17:43:01 -0800449 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700450 if (pdata == NULL) {
451 SLOGE("Cannot allocate persisent data\n");
452 return;
453 }
454 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
455
456 /* Need to initialize the persistent data area */
457 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
458 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100459 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700460 return;
461 }
462 /* Write all zeros to the first copy, making it invalid */
463 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
464
465 /* Write a valid but empty structure to the second copy */
466 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
467 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
468
469 /* Update the footer */
470 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
471 crypt_ftr->persist_data_offset[0] = pdata_offset;
472 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
473 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100474 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700475 }
476
Paul Lawrencef4faa572014-01-29 13:31:03 -0800477 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700478 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800479 /* But keep the old kdf_type.
480 * It will get updated later to KDF_SCRYPT after the password has been verified.
481 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700482 crypt_ftr->kdf_type = KDF_PBKDF2;
483 get_device_scrypt_params(crypt_ftr);
484 crypt_ftr->minor_version = 2;
485 }
486
Paul Lawrencef4faa572014-01-29 13:31:03 -0800487 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
488 SLOGW("upgrading crypto footer to 1.3");
489 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
490 crypt_ftr->minor_version = 3;
491 }
492
Kenny Root7434b312013-06-14 11:29:53 -0700493 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
494 if (lseek64(fd, offset, SEEK_SET) == -1) {
495 SLOGE("Cannot seek to crypt footer\n");
496 return;
497 }
498 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700499 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700500}
501
502
503static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800504{
505 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800506 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700507 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800508 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700509 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700510 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800511
Ken Sumrall160b4d62013-04-22 12:15:39 -0700512 if (get_crypt_ftr_info(&fname, &starting_off)) {
513 SLOGE("Unable to get crypt_ftr_info\n");
514 return -1;
515 }
516 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700517 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700518 return -1;
519 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700520 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700521 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700522 return -1;
523 }
524
525 /* Make sure it's 16 Kbytes in length */
526 fstat(fd, &statbuf);
527 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
528 SLOGE("footer file %s is not the expected size!\n", fname);
529 goto errout;
530 }
531
532 /* Seek to the start of the crypt footer */
533 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
534 SLOGE("Cannot seek to real block device footer\n");
535 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800536 }
537
538 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
539 SLOGE("Cannot read real block device footer\n");
540 goto errout;
541 }
542
543 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700544 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800545 goto errout;
546 }
547
Kenny Rootc96a5f82013-06-14 12:08:28 -0700548 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
549 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
550 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800551 goto errout;
552 }
553
Kenny Rootc96a5f82013-06-14 12:08:28 -0700554 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
555 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
556 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800557 }
558
Ken Sumrall160b4d62013-04-22 12:15:39 -0700559 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
560 * copy on disk before returning.
561 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700562 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700563 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800564 }
565
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800566 /* Success! */
567 rc = 0;
568
569errout:
570 close(fd);
571 return rc;
572}
573
Ken Sumrall160b4d62013-04-22 12:15:39 -0700574static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
575{
576 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
577 crypt_ftr->persist_data_offset[1]) {
578 SLOGE("Crypt_ftr persist data regions overlap");
579 return -1;
580 }
581
582 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
583 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
584 return -1;
585 }
586
587 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
588 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
589 CRYPT_FOOTER_OFFSET) {
590 SLOGE("Persistent data extends past crypto footer");
591 return -1;
592 }
593
594 return 0;
595}
596
597static int load_persistent_data(void)
598{
599 struct crypt_mnt_ftr crypt_ftr;
600 struct crypt_persist_data *pdata = NULL;
601 char encrypted_state[PROPERTY_VALUE_MAX];
602 char *fname;
603 int found = 0;
604 int fd;
605 int ret;
606 int i;
607
608 if (persist_data) {
609 /* Nothing to do, we've already loaded or initialized it */
610 return 0;
611 }
612
613
614 /* If not encrypted, just allocate an empty table and initialize it */
615 property_get("ro.crypto.state", encrypted_state, "");
616 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800617 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700618 if (pdata) {
619 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
620 persist_data = pdata;
621 return 0;
622 }
623 return -1;
624 }
625
626 if(get_crypt_ftr_and_key(&crypt_ftr)) {
627 return -1;
628 }
629
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700630 if ((crypt_ftr.major_version < 1)
631 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700632 SLOGE("Crypt_ftr version doesn't support persistent data");
633 return -1;
634 }
635
636 if (get_crypt_ftr_info(&fname, NULL)) {
637 return -1;
638 }
639
640 ret = validate_persistent_data_storage(&crypt_ftr);
641 if (ret) {
642 return -1;
643 }
644
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700645 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700646 if (fd < 0) {
647 SLOGE("Cannot open %s metadata file", fname);
648 return -1;
649 }
650
Wei Wang4375f1b2017-02-24 17:43:01 -0800651 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800652 if (pdata == NULL) {
653 SLOGE("Cannot allocate memory for persistent data");
654 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700655 }
656
657 for (i = 0; i < 2; i++) {
658 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
659 SLOGE("Cannot seek to read persistent data on %s", fname);
660 goto err2;
661 }
662 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
663 SLOGE("Error reading persistent data on iteration %d", i);
664 goto err2;
665 }
666 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
667 found = 1;
668 break;
669 }
670 }
671
672 if (!found) {
673 SLOGI("Could not find valid persistent data, creating");
674 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
675 }
676
677 /* Success */
678 persist_data = pdata;
679 close(fd);
680 return 0;
681
682err2:
683 free(pdata);
684
685err:
686 close(fd);
687 return -1;
688}
689
690static int save_persistent_data(void)
691{
692 struct crypt_mnt_ftr crypt_ftr;
693 struct crypt_persist_data *pdata;
694 char *fname;
695 off64_t write_offset;
696 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700697 int fd;
698 int ret;
699
700 if (persist_data == NULL) {
701 SLOGE("No persistent data to save");
702 return -1;
703 }
704
705 if(get_crypt_ftr_and_key(&crypt_ftr)) {
706 return -1;
707 }
708
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700709 if ((crypt_ftr.major_version < 1)
710 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700711 SLOGE("Crypt_ftr version doesn't support persistent data");
712 return -1;
713 }
714
715 ret = validate_persistent_data_storage(&crypt_ftr);
716 if (ret) {
717 return -1;
718 }
719
720 if (get_crypt_ftr_info(&fname, NULL)) {
721 return -1;
722 }
723
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700724 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700725 if (fd < 0) {
726 SLOGE("Cannot open %s metadata file", fname);
727 return -1;
728 }
729
Wei Wang4375f1b2017-02-24 17:43:01 -0800730 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700731 if (pdata == NULL) {
732 SLOGE("Cannot allocate persistant data");
733 goto err;
734 }
735
736 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
737 SLOGE("Cannot seek to read persistent data on %s", fname);
738 goto err2;
739 }
740
741 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
742 SLOGE("Error reading persistent data before save");
743 goto err2;
744 }
745
746 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
747 /* The first copy is the curent valid copy, so write to
748 * the second copy and erase this one */
749 write_offset = crypt_ftr.persist_data_offset[1];
750 erase_offset = crypt_ftr.persist_data_offset[0];
751 } else {
752 /* The second copy must be the valid copy, so write to
753 * the first copy, and erase the second */
754 write_offset = crypt_ftr.persist_data_offset[0];
755 erase_offset = crypt_ftr.persist_data_offset[1];
756 }
757
758 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100759 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700760 SLOGE("Cannot seek to write persistent data");
761 goto err2;
762 }
763 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
764 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100765 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700766 SLOGE("Cannot seek to erase previous persistent data");
767 goto err2;
768 }
769 fsync(fd);
770 memset(pdata, 0, crypt_ftr.persist_data_size);
771 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
772 (int) crypt_ftr.persist_data_size) {
773 SLOGE("Cannot write to erase previous persistent data");
774 goto err2;
775 }
776 fsync(fd);
777 } else {
778 SLOGE("Cannot write to save persistent data");
779 goto err2;
780 }
781
782 /* Success */
783 free(pdata);
784 close(fd);
785 return 0;
786
787err2:
788 free(pdata);
789err:
790 close(fd);
791 return -1;
792}
793
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800794/* Convert a binary key of specified length into an ascii hex string equivalent,
795 * without the leading 0x and with null termination
796 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700797static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700798 unsigned int keysize, char *master_key_ascii) {
799 unsigned int i, a;
800 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800801
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700802 for (i=0, a=0; i<keysize; i++, a+=2) {
803 /* For each byte, write out two ascii hex digits */
804 nibble = (master_key[i] >> 4) & 0xf;
805 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800806
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700807 nibble = master_key[i] & 0xf;
808 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
809 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800810
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700811 /* Add the null termination */
812 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800813
814}
815
Jeff Sharkey9c484982015-03-31 10:35:33 -0700816static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
817 const unsigned char *master_key, const char *real_blk_name,
818 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800819 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800820 struct dm_ioctl *io;
821 struct dm_target_spec *tgt;
822 char *crypt_params;
823 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800824 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800825 int i;
826
827 io = (struct dm_ioctl *) buffer;
828
829 /* Load the mapping table for this device */
830 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
831
832 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
833 io->target_count = 1;
834 tgt->status = 0;
835 tgt->sector_start = 0;
836 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700837 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800838
839 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
840 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800841
842 buff_offset = crypt_params - buffer;
843 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
844 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
845 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800846 crypt_params += strlen(crypt_params) + 1;
847 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
848 tgt->next = crypt_params - buffer;
849
850 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
851 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
852 break;
853 }
854 usleep(500000);
855 }
856
857 if (i == TABLE_LOAD_RETRIES) {
858 /* We failed to load the table, return an error */
859 return -1;
860 } else {
861 return i + 1;
862 }
863}
864
865
866static int get_dm_crypt_version(int fd, const char *name, int *version)
867{
868 char buffer[DM_CRYPT_BUF_SIZE];
869 struct dm_ioctl *io;
870 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800871
872 io = (struct dm_ioctl *) buffer;
873
874 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
875
876 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
877 return -1;
878 }
879
880 /* Iterate over the returned versions, looking for name of "crypt".
881 * When found, get and return the version.
882 */
883 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
884 while (v->next) {
885 if (! strcmp(v->name, "crypt")) {
886 /* We found the crypt driver, return the version, and get out */
887 version[0] = v->version[0];
888 version[1] = v->version[1];
889 version[2] = v->version[2];
890 return 0;
891 }
892 v = (struct dm_target_versions *)(((char *)v) + v->next);
893 }
894
895 return -1;
896}
897
Jeff Sharkey9c484982015-03-31 10:35:33 -0700898static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
899 const unsigned char *master_key, const char *real_blk_name,
900 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800901 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800902 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800903 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -0700904 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800905 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800906 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800907 int version[3];
Wei Wang4375f1b2017-02-24 17:43:01 -0800908 const char *extra_params;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800909 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800910
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700911 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800912 SLOGE("Cannot open device-mapper\n");
913 goto errout;
914 }
915
916 io = (struct dm_ioctl *) buffer;
917
918 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800919 err = ioctl(fd, DM_DEV_CREATE, io);
920 if (err) {
921 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800922 goto errout;
923 }
924
925 /* Get the device status, in particular, the name of it's device file */
926 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
927 if (ioctl(fd, DM_DEV_STATUS, io)) {
928 SLOGE("Cannot retrieve dm-crypt device status\n");
929 goto errout;
930 }
931 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
932 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
933
Ken Sumralldb5e0262013-02-05 17:39:48 -0800934 extra_params = "";
935 if (! get_dm_crypt_version(fd, name, version)) {
936 /* Support for allow_discards was added in version 1.11.0 */
937 if ((version[0] >= 2) ||
938 ((version[0] == 1) && (version[1] >= 11))) {
939 extra_params = "1 allow_discards";
940 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
941 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700942 }
943
Ken Sumralldb5e0262013-02-05 17:39:48 -0800944 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
945 fd, extra_params);
946 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800947 SLOGE("Cannot load dm-crypt mapping table.\n");
948 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800949 } else if (load_count > 1) {
950 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800951 }
952
953 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800954 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800955
956 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
957 SLOGE("Cannot resume the dm-crypt device\n");
958 goto errout;
959 }
960
961 /* We made it here with no errors. Woot! */
962 retval = 0;
963
964errout:
965 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
966
967 return retval;
968}
969
Wei Wang4375f1b2017-02-24 17:43:01 -0800970static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800971{
972 int fd;
973 char buffer[DM_CRYPT_BUF_SIZE];
974 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800975 int retval = -1;
976
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700977 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800978 SLOGE("Cannot open device-mapper\n");
979 goto errout;
980 }
981
982 io = (struct dm_ioctl *) buffer;
983
984 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
985 if (ioctl(fd, DM_DEV_REMOVE, io)) {
986 SLOGE("Cannot remove dm-crypt device\n");
987 goto errout;
988 }
989
990 /* We made it here with no errors. Woot! */
991 retval = 0;
992
993errout:
994 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
995
996 return retval;
997
998}
999
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001000static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001001 unsigned char *ikey, void *params UNUSED)
1002{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001003 SLOGI("Using pbkdf2 for cryptfs KDF");
1004
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001005 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001006 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1007 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1008 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001009}
1010
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001011static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001012 unsigned char *ikey, void *params)
1013{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001014 SLOGI("Using scrypt for cryptfs KDF");
1015
Kenny Rootc4c70f12013-06-14 12:11:38 -07001016 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1017
1018 int N = 1 << ftr->N_factor;
1019 int r = 1 << ftr->r_factor;
1020 int p = 1 << ftr->p_factor;
1021
1022 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001023 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001024 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1025 salt, SALT_LEN, N, r, p, ikey,
1026 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001027
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001028 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001029}
1030
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001031static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1032 unsigned char *ikey, void *params)
1033{
1034 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1035
1036 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001037 size_t signature_size;
1038 unsigned char* signature;
1039 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1040
1041 int N = 1 << ftr->N_factor;
1042 int r = 1 << ftr->r_factor;
1043 int p = 1 << ftr->p_factor;
1044
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001045 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1046 salt, SALT_LEN, N, r, p, ikey,
1047 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001048
1049 if (rc) {
1050 SLOGE("scrypt failed");
1051 return -1;
1052 }
1053
Shawn Willdene17a9c42014-09-08 13:04:08 -06001054 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1055 &signature, &signature_size)) {
1056 SLOGE("Signing failed");
1057 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001058 }
1059
1060 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1061 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1062 free(signature);
1063
1064 if (rc) {
1065 SLOGE("scrypt failed");
1066 return -1;
1067 }
1068
1069 return 0;
1070}
1071
1072static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1073 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001074 unsigned char *encrypted_master_key,
1075 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001076{
1077 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1078 EVP_CIPHER_CTX e_ctx;
1079 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001080 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001081
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001082 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001083 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001084
1085 switch (crypt_ftr->kdf_type) {
1086 case KDF_SCRYPT_KEYMASTER:
1087 if (keymaster_create_key(crypt_ftr)) {
1088 SLOGE("keymaster_create_key failed");
1089 return -1;
1090 }
1091
1092 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1093 SLOGE("scrypt failed");
1094 return -1;
1095 }
1096 break;
1097
1098 case KDF_SCRYPT:
1099 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1100 SLOGE("scrypt failed");
1101 return -1;
1102 }
1103 break;
1104
1105 default:
1106 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001107 return -1;
1108 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001109
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001110 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001111 EVP_CIPHER_CTX_init(&e_ctx);
1112 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001113 SLOGE("EVP_EncryptInit failed\n");
1114 return -1;
1115 }
1116 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001117
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001118 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001119 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001120 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121 SLOGE("EVP_EncryptUpdate failed\n");
1122 return -1;
1123 }
Adam Langley889c4f12014-09-03 14:23:13 -07001124 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125 SLOGE("EVP_EncryptFinal failed\n");
1126 return -1;
1127 }
1128
1129 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1130 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1131 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001132 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001133
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001134 /* Store the scrypt of the intermediate key, so we can validate if it's a
1135 password error or mount error when things go wrong.
1136 Note there's no need to check for errors, since if this is incorrect, we
1137 simply won't wipe userdata, which is the correct default behavior
1138 */
1139 int N = 1 << crypt_ftr->N_factor;
1140 int r = 1 << crypt_ftr->r_factor;
1141 int p = 1 << crypt_ftr->p_factor;
1142
1143 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1144 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1145 crypt_ftr->scrypted_intermediate_key,
1146 sizeof(crypt_ftr->scrypted_intermediate_key));
1147
1148 if (rc) {
1149 SLOGE("encrypt_master_key: crypto_scrypt failed");
1150 }
1151
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001152 EVP_CIPHER_CTX_cleanup(&e_ctx);
1153
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001154 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001155}
1156
Paul Lawrence731a7a22015-04-28 22:14:15 +00001157static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001158 unsigned char *encrypted_master_key,
1159 unsigned char *decrypted_master_key,
1160 kdf_func kdf, void *kdf_params,
1161 unsigned char** intermediate_key,
1162 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001163{
1164 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 -08001165 EVP_CIPHER_CTX d_ctx;
1166 int decrypted_len, final_len;
1167
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001168 /* Turn the password into an intermediate key and IV that can decrypt the
1169 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001170 if (kdf(passwd, salt, ikey, kdf_params)) {
1171 SLOGE("kdf failed");
1172 return -1;
1173 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001174
1175 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001176 EVP_CIPHER_CTX_init(&d_ctx);
1177 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001178 return -1;
1179 }
1180 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1181 /* Decrypt the master key */
1182 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1183 encrypted_master_key, KEY_LEN_BYTES)) {
1184 return -1;
1185 }
Adam Langley889c4f12014-09-03 14:23:13 -07001186 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001187 return -1;
1188 }
1189
1190 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1191 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001192 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001193
1194 /* Copy intermediate key if needed by params */
1195 if (intermediate_key && intermediate_key_size) {
1196 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001197 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001198 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1199 *intermediate_key_size = KEY_LEN_BYTES;
1200 }
1201 }
1202
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001203 EVP_CIPHER_CTX_cleanup(&d_ctx);
1204
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001205 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001206}
1207
Kenny Rootc4c70f12013-06-14 12:11:38 -07001208static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001209{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001210 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001211 *kdf = scrypt_keymaster;
1212 *kdf_params = ftr;
1213 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001214 *kdf = scrypt;
1215 *kdf_params = ftr;
1216 } else {
1217 *kdf = pbkdf2;
1218 *kdf_params = NULL;
1219 }
1220}
1221
Paul Lawrence731a7a22015-04-28 22:14:15 +00001222static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001223 struct crypt_mnt_ftr *crypt_ftr,
1224 unsigned char** intermediate_key,
1225 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001226{
1227 kdf_func kdf;
1228 void *kdf_params;
1229 int ret;
1230
1231 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001232 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1233 decrypted_master_key, kdf, kdf_params,
1234 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001235 if (ret != 0) {
1236 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001237 }
1238
1239 return ret;
1240}
1241
Wei Wang4375f1b2017-02-24 17:43:01 -08001242static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001243 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001244 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001245 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001246
1247 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001248 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001249 read(fd, key_buf, sizeof(key_buf));
1250 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001251 close(fd);
1252
1253 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001254 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001255}
1256
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001257int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001258{
Greg Hackmann955653e2014-09-24 14:55:20 -07001259 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001260#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001261
1262 /* Now umount the tmpfs filesystem */
1263 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001264 if (umount(mountpoint) == 0) {
1265 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001266 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001267
1268 if (errno == EINVAL) {
1269 /* EINVAL is returned if the directory is not a mountpoint,
1270 * i.e. there is no filesystem mounted there. So just get out.
1271 */
1272 break;
1273 }
1274
1275 err = errno;
1276
1277 /* If allowed, be increasingly aggressive before the last two retries */
1278 if (kill) {
1279 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1280 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001281 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001282 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1283 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001284 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001285 }
1286 }
1287
1288 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001289 }
1290
1291 if (i < WAIT_UNMOUNT_COUNT) {
1292 SLOGD("unmounting %s succeeded\n", mountpoint);
1293 rc = 0;
1294 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001295 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001296 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001297 rc = -1;
1298 }
1299
1300 return rc;
1301}
1302
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001303static int prep_data_fs(void)
1304{
1305 int i;
1306
Jeff Sharkey47695b22016-02-01 17:02:29 -07001307 // NOTE: post_fs_data results in init calling back around to vold, so all
1308 // callers to this method must be async
1309
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001310 /* Do the prep of the /data filesystem */
1311 property_set("vold.post_fs_data_done", "0");
1312 property_set("vold.decrypt", "trigger_post_fs_data");
1313 SLOGD("Just triggered post_fs_data\n");
1314
Ken Sumrallc5872692013-05-14 15:26:31 -07001315 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang4375f1b2017-02-24 17:43:01 -08001316 if (!android::base::WaitForProperty("vold.post_fs_data_done",
1317 "1",
1318 std::chrono::seconds(50))) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001319 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001320 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001321 return -1;
1322 } else {
1323 SLOGD("post_fs_data done\n");
1324 return 0;
1325 }
1326}
1327
Paul Lawrence74f29f12014-08-28 15:54:10 -07001328static void cryptfs_set_corrupt()
1329{
1330 // Mark the footer as bad
1331 struct crypt_mnt_ftr crypt_ftr;
1332 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1333 SLOGE("Failed to get crypto footer - panic");
1334 return;
1335 }
1336
1337 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1338 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1339 SLOGE("Failed to set crypto footer - panic");
1340 return;
1341 }
1342}
1343
1344static void cryptfs_trigger_restart_min_framework()
1345{
1346 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1347 SLOGE("Failed to mount tmpfs on data - panic");
1348 return;
1349 }
1350
1351 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1352 SLOGE("Failed to trigger post fs data - panic");
1353 return;
1354 }
1355
1356 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1357 SLOGE("Failed to trigger restart min framework - panic");
1358 return;
1359 }
1360}
1361
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001362/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001363static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001364{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001365 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001366 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001367 static int restart_successful = 0;
1368
1369 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001370 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001371 SLOGE("Encrypted filesystem not validated, aborting");
1372 return -1;
1373 }
1374
1375 if (restart_successful) {
1376 SLOGE("System already restarted with encrypted disk, aborting");
1377 return -1;
1378 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001379
Paul Lawrencef4faa572014-01-29 13:31:03 -08001380 if (restart_main) {
1381 /* Here is where we shut down the framework. The init scripts
1382 * start all services in one of three classes: core, main or late_start.
1383 * On boot, we start core and main. Now, we stop main, but not core,
1384 * as core includes vold and a few other really important things that
1385 * we need to keep running. Once main has stopped, we should be able
1386 * to umount the tmpfs /data, then mount the encrypted /data.
1387 * We then restart the class main, and also the class late_start.
1388 * At the moment, I've only put a few things in late_start that I know
1389 * are not needed to bring up the framework, and that also cause problems
1390 * with unmounting the tmpfs /data, but I hope to add add more services
1391 * to the late_start class as we optimize this to decrease the delay
1392 * till the user is asked for the password to the filesystem.
1393 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001394
Paul Lawrencef4faa572014-01-29 13:31:03 -08001395 /* The init files are setup to stop the class main when vold.decrypt is
1396 * set to trigger_reset_main.
1397 */
1398 property_set("vold.decrypt", "trigger_reset_main");
1399 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001400
Paul Lawrencef4faa572014-01-29 13:31:03 -08001401 /* Ugh, shutting down the framework is not synchronous, so until it
1402 * can be fixed, this horrible hack will wait a moment for it all to
1403 * shut down before proceeding. Without it, some devices cannot
1404 * restart the graphics services.
1405 */
1406 sleep(2);
1407 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001408
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001409 /* Now that the framework is shutdown, we should be able to umount()
1410 * the tmpfs filesystem, and mount the real one.
1411 */
1412
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001413 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1414 if (strlen(crypto_blkdev) == 0) {
1415 SLOGE("fs_crypto_blkdev not set\n");
1416 return -1;
1417 }
1418
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001419 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001420 /* If ro.crypto.readonly is set to 1, mount the decrypted
1421 * filesystem readonly. This is used when /data is mounted by
1422 * recovery mode.
1423 */
1424 char ro_prop[PROPERTY_VALUE_MAX];
1425 property_get("ro.crypto.readonly", ro_prop, "");
1426 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1427 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1428 rec->flags |= MS_RDONLY;
1429 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001430
Ken Sumralle5032c42012-04-01 23:58:44 -07001431 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001432 int retries = RETRY_MOUNT_ATTEMPTS;
1433 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001434
1435 /*
1436 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1437 * partitions in the fsck domain.
1438 */
1439 if (setexeccon(secontextFsck())){
1440 SLOGE("Failed to setexeccon");
1441 return -1;
1442 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001443 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1444 crypto_blkdev, 0))
1445 != 0) {
1446 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1447 /* TODO: invoke something similar to
1448 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1449 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1450 SLOGI("Failed to mount %s because it is busy - waiting",
1451 crypto_blkdev);
1452 if (--retries) {
1453 sleep(RETRY_MOUNT_DELAY_SECONDS);
1454 } else {
1455 /* Let's hope that a reboot clears away whatever is keeping
1456 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001457 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001458 }
1459 } else {
1460 SLOGE("Failed to mount decrypted data");
1461 cryptfs_set_corrupt();
1462 cryptfs_trigger_restart_min_framework();
1463 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001464 if (setexeccon(NULL)) {
1465 SLOGE("Failed to setexeccon");
1466 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001467 return -1;
1468 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001469 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001470 if (setexeccon(NULL)) {
1471 SLOGE("Failed to setexeccon");
1472 return -1;
1473 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001474
Ken Sumralle5032c42012-04-01 23:58:44 -07001475 /* Create necessary paths on /data */
1476 if (prep_data_fs()) {
1477 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001478 }
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001479 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001480
1481 /* startup service classes main and late_start */
1482 property_set("vold.decrypt", "trigger_restart_framework");
1483 SLOGD("Just triggered restart_framework\n");
1484
1485 /* Give it a few moments to get started */
1486 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001487 }
1488
Ken Sumrall0cc16632011-01-18 20:32:26 -08001489 if (rc == 0) {
1490 restart_successful = 1;
1491 }
1492
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001493 return rc;
1494}
1495
Paul Lawrencef4faa572014-01-29 13:31:03 -08001496int cryptfs_restart(void)
1497{
Paul Lawrence05335c32015-03-05 09:46:23 -08001498 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001499 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001500 SLOGE("cryptfs_restart not valid for file encryption:");
1501 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001502 }
1503
Paul Lawrencef4faa572014-01-29 13:31:03 -08001504 /* Call internal implementation forcing a restart of main service group */
1505 return cryptfs_restart_internal(1);
1506}
1507
Wei Wang4375f1b2017-02-24 17:43:01 -08001508static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001509{
1510 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001511 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001512 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001513
1514 property_get("ro.crypto.state", encrypted_state, "");
1515 if (strcmp(encrypted_state, "encrypted") ) {
1516 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001517 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001518 }
1519
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001520 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001521 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001522 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001523 }
1524
Ken Sumrall160b4d62013-04-22 12:15:39 -07001525 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001526 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001527
Ken Sumralle1a45852011-12-14 21:24:27 -08001528 /*
1529 * Only report this error if key_loc is a file and it exists.
1530 * If the device was never encrypted, and /data is not mountable for
1531 * some reason, returning 1 should prevent the UI from presenting the
1532 * a "enter password" screen, or worse, a "press button to wipe the
1533 * device" screen.
1534 */
1535 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1536 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001537 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001538 } else {
1539 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001540 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001541 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001542 }
1543
Paul Lawrence74f29f12014-08-28 15:54:10 -07001544 // Test for possible error flags
1545 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1546 SLOGE("Encryption process is partway completed\n");
1547 return CRYPTO_COMPLETE_PARTIAL;
1548 }
1549
1550 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1551 SLOGE("Encryption process was interrupted but cannot continue\n");
1552 return CRYPTO_COMPLETE_INCONSISTENT;
1553 }
1554
1555 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1556 SLOGE("Encryption is successful but data is corrupt\n");
1557 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001558 }
1559
1560 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001561 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001562}
1563
Paul Lawrencef4faa572014-01-29 13:31:03 -08001564static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001565 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001566{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001567 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001568 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569 char crypto_blkdev[MAXPATHLEN];
1570 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001572 unsigned int orig_failed_decrypt_count;
1573 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001574 int use_keymaster = 0;
1575 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001576 unsigned char* intermediate_key = 0;
1577 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001578 int N = 1 << crypt_ftr->N_factor;
1579 int r = 1 << crypt_ftr->r_factor;
1580 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001581
Paul Lawrencef4faa572014-01-29 13:31:03 -08001582 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1583 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001584
Paul Lawrencef4faa572014-01-29 13:31:03 -08001585 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001586 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1587 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001588 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001589 rc = -1;
1590 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001591 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001592 }
1593
Paul Lawrencef4faa572014-01-29 13:31:03 -08001594 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1595
Paul Lawrence74f29f12014-08-28 15:54:10 -07001596 // Create crypto block device - all (non fatal) code paths
1597 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001598 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1599 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001600 SLOGE("Error creating decrypted block device\n");
1601 rc = -1;
1602 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001603 }
1604
Paul Lawrence74f29f12014-08-28 15:54:10 -07001605 /* Work out if the problem is the password or the data */
1606 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1607 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001608
Paul Lawrence74f29f12014-08-28 15:54:10 -07001609 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1610 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1611 N, r, p, scrypted_intermediate_key,
1612 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001613
Paul Lawrence74f29f12014-08-28 15:54:10 -07001614 // Does the key match the crypto footer?
1615 if (rc == 0 && memcmp(scrypted_intermediate_key,
1616 crypt_ftr->scrypted_intermediate_key,
1617 sizeof(scrypted_intermediate_key)) == 0) {
1618 SLOGI("Password matches");
1619 rc = 0;
1620 } else {
1621 /* Try mounting the file system anyway, just in case the problem's with
1622 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001623 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1624 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001625 mkdir(tmp_mount_point, 0755);
1626 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1627 SLOGE("Error temp mounting decrypted block device\n");
1628 delete_crypto_blk_dev(label);
1629
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001630 rc = ++crypt_ftr->failed_decrypt_count;
1631 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001632 } else {
1633 /* Success! */
1634 SLOGI("Password did not match but decrypted drive mounted - continue");
1635 umount(tmp_mount_point);
1636 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001637 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001638 }
1639
1640 if (rc == 0) {
1641 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001642 if (orig_failed_decrypt_count != 0) {
1643 put_crypt_ftr_and_key(crypt_ftr);
1644 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001645
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001646 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001647 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001648 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001649
1650 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001651 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001652 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001653 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001654 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001655 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001656 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001657
Paul Lawrence74f29f12014-08-28 15:54:10 -07001658 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001659 use_keymaster = keymaster_check_compatibility();
1660 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001661 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001662 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1663 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1664 upgrade = 1;
1665 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001666 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001667 upgrade = 1;
1668 }
1669
1670 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001671 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1672 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001673 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001674 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001675 }
1676 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001677
1678 // Do not fail even if upgrade failed - machine is bootable
1679 // Note that if this code is ever hit, there is a *serious* problem
1680 // since KDFs should never fail. You *must* fix the kdf before
1681 // proceeding!
1682 if (rc) {
1683 SLOGW("Upgrade failed with error %d,"
1684 " but continuing with previous state",
1685 rc);
1686 rc = 0;
1687 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001688 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001689 }
1690
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001691 errout:
1692 if (intermediate_key) {
1693 memset(intermediate_key, 0, intermediate_key_size);
1694 free(intermediate_key);
1695 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001696 return rc;
1697}
1698
Ken Sumrall29d8da82011-05-18 17:20:07 -07001699/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001700 * Called by vold when it's asked to mount an encrypted external
1701 * storage volume. The incoming partition has no crypto header/footer,
1702 * as any metadata is been stored in a separate, small partition.
1703 *
1704 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001705 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001706int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1707 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001708 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001709 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001710 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001711 return -1;
1712 }
1713
1714 unsigned long nr_sec = 0;
1715 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001716 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001717
Ken Sumrall29d8da82011-05-18 17:20:07 -07001718 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001719 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001720 return -1;
1721 }
1722
Jeff Sharkey9c484982015-03-31 10:35:33 -07001723 struct crypt_mnt_ftr ext_crypt_ftr;
1724 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1725 ext_crypt_ftr.fs_size = nr_sec;
1726 ext_crypt_ftr.keysize = keysize;
1727 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001728
Jeff Sharkey9c484982015-03-31 10:35:33 -07001729 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1730 out_crypto_blkdev, label);
1731}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001732
Jeff Sharkey9c484982015-03-31 10:35:33 -07001733/*
1734 * Called by vold when it's asked to unmount an encrypted external
1735 * storage volume.
1736 */
1737int cryptfs_revert_ext_volume(const char* label) {
1738 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001739}
1740
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001741int cryptfs_crypto_complete(void)
1742{
1743 return do_crypto_complete("/data");
1744}
1745
Paul Lawrencef4faa572014-01-29 13:31:03 -08001746int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1747{
1748 char encrypted_state[PROPERTY_VALUE_MAX];
1749 property_get("ro.crypto.state", encrypted_state, "");
1750 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1751 SLOGE("encrypted fs already validated or not running with encryption,"
1752 " aborting");
1753 return -1;
1754 }
1755
1756 if (get_crypt_ftr_and_key(crypt_ftr)) {
1757 SLOGE("Error getting crypt footer and key");
1758 return -1;
1759 }
1760
1761 return 0;
1762}
1763
Wei Wang4375f1b2017-02-24 17:43:01 -08001764int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001765{
Paul Lawrence05335c32015-03-05 09:46:23 -08001766 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001767 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001768 SLOGE("cryptfs_check_passwd not valid for file encryption");
1769 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001770 }
1771
Paul Lawrencef4faa572014-01-29 13:31:03 -08001772 struct crypt_mnt_ftr crypt_ftr;
1773 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001774
Paul Lawrencef4faa572014-01-29 13:31:03 -08001775 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001776 if (rc) {
1777 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001778 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001779 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001780
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001781 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001782 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1783 if (rc) {
1784 SLOGE("Password did not match");
1785 return rc;
1786 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001787
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001788 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1789 // Here we have a default actual password but a real password
1790 // we must test against the scrypted value
1791 // First, we must delete the crypto block device that
1792 // test_mount_encrypted_fs leaves behind as a side effect
1793 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1794 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1795 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1796 if (rc) {
1797 SLOGE("Default password did not match on reboot encryption");
1798 return rc;
1799 }
1800
1801 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1802 put_crypt_ftr_and_key(&crypt_ftr);
1803 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1804 if (rc) {
1805 SLOGE("Could not change password on reboot encryption");
1806 return rc;
1807 }
1808 }
1809
1810 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001811 cryptfs_clear_password();
1812 password = strdup(passwd);
1813 struct timespec now;
1814 clock_gettime(CLOCK_BOOTTIME, &now);
1815 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001816 }
1817
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001818 return rc;
1819}
1820
Ken Sumrall3ad90722011-10-04 20:38:29 -07001821int cryptfs_verify_passwd(char *passwd)
1822{
1823 struct crypt_mnt_ftr crypt_ftr;
1824 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001825 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001826 char encrypted_state[PROPERTY_VALUE_MAX];
1827 int rc;
1828
1829 property_get("ro.crypto.state", encrypted_state, "");
1830 if (strcmp(encrypted_state, "encrypted") ) {
1831 SLOGE("device not encrypted, aborting");
1832 return -2;
1833 }
1834
1835 if (!master_key_saved) {
1836 SLOGE("encrypted fs not yet mounted, aborting");
1837 return -1;
1838 }
1839
1840 if (!saved_mount_point) {
1841 SLOGE("encrypted fs failed to save mount point, aborting");
1842 return -1;
1843 }
1844
Ken Sumrall160b4d62013-04-22 12:15:39 -07001845 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001846 SLOGE("Error getting crypt footer and key\n");
1847 return -1;
1848 }
1849
1850 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1851 /* If the device has no password, then just say the password is valid */
1852 rc = 0;
1853 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001854 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001855 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1856 /* They match, the password is correct */
1857 rc = 0;
1858 } else {
1859 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1860 sleep(1);
1861 rc = 1;
1862 }
1863 }
1864
1865 return rc;
1866}
1867
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001868/* Initialize a crypt_mnt_ftr structure. The keysize is
1869 * defaulted to 16 bytes, and the filesystem size to 0.
1870 * Presumably, at a minimum, the caller will update the
1871 * filesystem size and crypto_type_name after calling this function.
1872 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001873static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001874{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001875 off64_t off;
1876
1877 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001878 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001879 ftr->major_version = CURRENT_MAJOR_VERSION;
1880 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001881 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001882 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001883
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001884 switch (keymaster_check_compatibility()) {
1885 case 1:
1886 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1887 break;
1888
1889 case 0:
1890 ftr->kdf_type = KDF_SCRYPT;
1891 break;
1892
1893 default:
1894 SLOGE("keymaster_check_compatibility failed");
1895 return -1;
1896 }
1897
Kenny Rootc4c70f12013-06-14 12:11:38 -07001898 get_device_scrypt_params(ftr);
1899
Ken Sumrall160b4d62013-04-22 12:15:39 -07001900 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1901 if (get_crypt_ftr_info(NULL, &off) == 0) {
1902 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1903 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1904 ftr->persist_data_size;
1905 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001906
1907 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001908}
1909
Ken Sumrall29d8da82011-05-18 17:20:07 -07001910static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001911{
Ken Sumralle550f782013-08-20 13:48:23 -07001912 const char *args[10];
1913 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1914 int num_args;
1915 int status;
1916 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001917 int rc = -1;
1918
Ken Sumrall29d8da82011-05-18 17:20:07 -07001919 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001920#ifdef TARGET_USES_MKE2FS
1921 args[0] = "/system/bin/mke2fs";
1922 args[1] = "-M";
1923 args[2] = "/data";
1924 args[3] = "-b";
1925 args[4] = "4096";
1926 args[5] = "-t";
1927 args[6] = "ext4";
1928 args[7] = crypto_blkdev;
1929 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1930 args[8] = size_str;
1931 num_args = 9;
1932#else
Ken Sumralle550f782013-08-20 13:48:23 -07001933 args[0] = "/system/bin/make_ext4fs";
1934 args[1] = "-a";
1935 args[2] = "/data";
1936 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07001937 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07001938 args[4] = size_str;
1939 args[5] = crypto_blkdev;
1940 num_args = 6;
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001941#endif
Ken Sumralle550f782013-08-20 13:48:23 -07001942 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1943 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001944 } else if (type == F2FS_FS) {
1945 args[0] = "/system/bin/mkfs.f2fs";
1946 args[1] = "-t";
1947 args[2] = "-d1";
1948 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001949 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07001950 args[4] = size_str;
1951 num_args = 5;
1952 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
1953 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001954 } else {
1955 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1956 return -1;
1957 }
1958
Ken Sumralle550f782013-08-20 13:48:23 -07001959 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1960
1961 if (tmp != 0) {
1962 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001963 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001964 if (WIFEXITED(status)) {
1965 if (WEXITSTATUS(status)) {
1966 SLOGE("Error creating filesystem on %s, exit status %d ",
1967 crypto_blkdev, WEXITSTATUS(status));
1968 } else {
1969 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1970 rc = 0;
1971 }
1972 } else {
1973 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1974 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001975 }
1976
1977 return rc;
1978}
1979
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001980#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08001981#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
1982#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001983
1984/* aligned 32K writes tends to make flash happy.
1985 * SD card association recommends it.
1986 */
1987#define BLOCKS_AT_A_TIME 8
1988
1989struct encryptGroupsData
1990{
1991 int realfd;
1992 int cryptofd;
1993 off64_t numblocks;
1994 off64_t one_pct, cur_pct, new_pct;
1995 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001996 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001997 char* real_blkdev, * crypto_blkdev;
1998 int count;
1999 off64_t offset;
2000 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002001 off64_t last_written_sector;
2002 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002003 time_t time_started;
2004 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002005};
2006
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002007static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002008{
2009 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002010
2011 if (is_used) {
2012 data->used_blocks_already_done++;
2013 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002014 if (data->tot_used_blocks) {
2015 data->new_pct = data->used_blocks_already_done / data->one_pct;
2016 } else {
2017 data->new_pct = data->blocks_already_done / data->one_pct;
2018 }
2019
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002020 if (data->new_pct > data->cur_pct) {
2021 char buf[8];
2022 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002023 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002024 property_set("vold.encrypt_progress", buf);
2025 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002026
2027 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002028 struct timespec time_now;
2029 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2030 SLOGW("Error getting time");
2031 } else {
2032 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2033 off64_t remaining_blocks = data->tot_used_blocks
2034 - data->used_blocks_already_done;
2035 int remaining_time = (int)(elapsed_time * remaining_blocks
2036 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002037
Paul Lawrence9c58a872014-09-30 09:12:51 -07002038 // Change time only if not yet set, lower, or a lot higher for
2039 // best user experience
2040 if (data->remaining_time == -1
2041 || remaining_time < data->remaining_time
2042 || remaining_time > data->remaining_time + 60) {
2043 char buf[8];
2044 snprintf(buf, sizeof(buf), "%d", remaining_time);
2045 property_set("vold.encrypt_time_remaining", buf);
2046 data->remaining_time = remaining_time;
2047 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002048 }
2049 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002050}
2051
Paul Lawrence3846be12014-09-22 11:33:54 -07002052static void log_progress(struct encryptGroupsData const* data, bool completed)
2053{
2054 // Precondition - if completed data = 0 else data != 0
2055
2056 // Track progress so we can skip logging blocks
2057 static off64_t offset = -1;
2058
2059 // Need to close existing 'Encrypting from' log?
2060 if (completed || (offset != -1 && data->offset != offset)) {
2061 SLOGI("Encrypted to sector %" PRId64,
2062 offset / info.block_size * CRYPT_SECTOR_SIZE);
2063 offset = -1;
2064 }
2065
2066 // Need to start new 'Encrypting from' log?
2067 if (!completed && offset != data->offset) {
2068 SLOGI("Encrypting from sector %" PRId64,
2069 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2070 }
2071
2072 // Update offset
2073 if (!completed) {
2074 offset = data->offset + (off64_t)data->count * info.block_size;
2075 }
2076}
2077
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002078static int flush_outstanding_data(struct encryptGroupsData* data)
2079{
2080 if (data->count == 0) {
2081 return 0;
2082 }
2083
Elliott Hughes231bdba2014-06-25 18:36:19 -07002084 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002085
2086 if (pread64(data->realfd, data->buffer,
2087 info.block_size * data->count, data->offset)
2088 <= 0) {
2089 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2090 data->real_blkdev);
2091 return -1;
2092 }
2093
2094 if (pwrite64(data->cryptofd, data->buffer,
2095 info.block_size * data->count, data->offset)
2096 <= 0) {
2097 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2098 data->crypto_blkdev);
2099 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002100 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002101 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002102 }
2103
2104 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002105 data->last_written_sector = (data->offset + data->count)
2106 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002107 return 0;
2108}
2109
2110static int encrypt_groups(struct encryptGroupsData* data)
2111{
2112 unsigned int i;
2113 u8 *block_bitmap = 0;
2114 unsigned int block;
2115 off64_t ret;
2116 int rc = -1;
2117
Wei Wang4375f1b2017-02-24 17:43:01 -08002118 data->buffer = (char *)malloc(info.block_size * BLOCKS_AT_A_TIME);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002119 if (!data->buffer) {
2120 SLOGE("Failed to allocate crypto buffer");
2121 goto errout;
2122 }
2123
Wei Wang4375f1b2017-02-24 17:43:01 -08002124 block_bitmap = (u8 *)malloc(info.block_size);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002125 if (!block_bitmap) {
2126 SLOGE("failed to allocate block bitmap");
2127 goto errout;
2128 }
2129
2130 for (i = 0; i < aux_info.groups; ++i) {
2131 SLOGI("Encrypting group %d", i);
2132
2133 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
Wei Wang4375f1b2017-02-24 17:43:01 -08002134 u32 block_count = std::min(info.blocks_per_group,
2135 (u32)(aux_info.len_blocks - first_block));
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002136
2137 off64_t offset = (u64)info.block_size
2138 * aux_info.bg_desc[i].bg_block_bitmap;
2139
2140 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2141 if (ret != (int)info.block_size) {
2142 SLOGE("failed to read all of block group bitmap %d", i);
2143 goto errout;
2144 }
2145
2146 offset = (u64)info.block_size * first_block;
2147
2148 data->count = 0;
2149
2150 for (block = 0; block < block_count; block++) {
liminghaoaa08e582016-01-06 10:30:49 +08002151 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
2152 0 : bitmap_get_bit(block_bitmap, block);
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002153 update_progress(data, used);
2154 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002155 if (data->count == 0) {
2156 data->offset = offset;
2157 }
2158 data->count++;
2159 } else {
2160 if (flush_outstanding_data(data)) {
2161 goto errout;
2162 }
2163 }
2164
2165 offset += info.block_size;
2166
2167 /* Write data if we are aligned or buffer size reached */
2168 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2169 || data->count == BLOCKS_AT_A_TIME) {
2170 if (flush_outstanding_data(data)) {
2171 goto errout;
2172 }
2173 }
2174 }
2175 if (flush_outstanding_data(data)) {
2176 goto errout;
2177 }
2178 }
2179
Paul Lawrence87999172014-02-20 12:21:31 -08002180 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002181 rc = 0;
2182
2183errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002184 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002185 free(data->buffer);
2186 free(block_bitmap);
2187 return rc;
2188}
2189
2190static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2191 char *real_blkdev,
2192 off64_t size,
2193 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002194 off64_t tot_size,
2195 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002196{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002197 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002198 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002199 int rc; // Can't initialize without causing warning -Wclobbered
Wei Wang4375f1b2017-02-24 17:43:01 -08002200 struct timespec time_started = {0};
2201 int retries = RETRY_MOUNT_ATTEMPTS;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002202
Paul Lawrence87999172014-02-20 12:21:31 -08002203 if (previously_encrypted_upto > *size_already_done) {
2204 SLOGD("Not fast encrypting since resuming part way through");
2205 return -1;
2206 }
2207
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002208 memset(&data, 0, sizeof(data));
2209 data.real_blkdev = real_blkdev;
2210 data.crypto_blkdev = crypto_blkdev;
2211
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002212 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002213 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2214 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002215 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002216 goto errout;
2217 }
2218
David Ng82fd8042015-01-21 13:55:21 -08002219 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
David Ng82fd8042015-01-21 13:55:21 -08002220 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2221 if (--retries) {
2222 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2223 crypto_blkdev, errno, strerror(errno));
2224 sleep(RETRY_MOUNT_DELAY_SECONDS);
2225 } else {
2226 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2227 crypto_blkdev, errno, strerror(errno));
2228 rc = ENABLE_INPLACE_ERR_DEV;
2229 goto errout;
2230 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002231 }
2232
2233 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002234 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002235 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002236 goto errout;
2237 }
2238
2239 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002240 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002241 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002242 goto errout;
2243 }
2244
2245 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2246 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2247 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2248
JP Abgrall7fc1de82014-10-10 18:43:41 -07002249 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002250
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002251 data.tot_used_blocks = data.numblocks;
2252 for (i = 0; i < aux_info.groups; ++i) {
2253 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2254 }
2255
2256 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002257 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002258
Paul Lawrence9c58a872014-09-30 09:12:51 -07002259 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2260 SLOGW("Error getting time at start");
2261 // Note - continue anyway - we'll run with 0
2262 }
2263 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002264 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002265
2266 rc = encrypt_groups(&data);
2267 if (rc) {
2268 SLOGE("Error encrypting groups");
2269 goto errout;
2270 }
2271
Paul Lawrence87999172014-02-20 12:21:31 -08002272 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002273 rc = 0;
2274
2275errout:
2276 close(data.realfd);
2277 close(data.cryptofd);
2278
2279 return rc;
2280}
2281
Paul Lawrence3846be12014-09-22 11:33:54 -07002282static void log_progress_f2fs(u64 block, bool completed)
2283{
2284 // Precondition - if completed data = 0 else data != 0
2285
2286 // Track progress so we can skip logging blocks
2287 static u64 last_block = (u64)-1;
2288
2289 // Need to close existing 'Encrypting from' log?
2290 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2291 SLOGI("Encrypted to block %" PRId64, last_block);
2292 last_block = -1;
2293 }
2294
2295 // Need to start new 'Encrypting from' log?
2296 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2297 SLOGI("Encrypting from block %" PRId64, block);
2298 }
2299
2300 // Update offset
2301 if (!completed) {
2302 last_block = block;
2303 }
2304}
2305
Daniel Rosenberge82df162014-08-15 22:19:23 +00002306static int encrypt_one_block_f2fs(u64 pos, void *data)
2307{
2308 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2309
2310 priv_dat->blocks_already_done = pos - 1;
2311 update_progress(priv_dat, 1);
2312
2313 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2314
2315 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002316 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002317 return -1;
2318 }
2319
2320 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002321 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002322 return -1;
2323 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002324 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002325 }
2326
2327 return 0;
2328}
2329
2330static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2331 char *real_blkdev,
2332 off64_t size,
2333 off64_t *size_already_done,
2334 off64_t tot_size,
2335 off64_t previously_encrypted_upto)
2336{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002337 struct encryptGroupsData data;
2338 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002339 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002340 if (previously_encrypted_upto > *size_already_done) {
2341 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002342 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002343 }
2344 memset(&data, 0, sizeof(data));
2345 data.real_blkdev = real_blkdev;
2346 data.crypto_blkdev = crypto_blkdev;
2347 data.realfd = -1;
2348 data.cryptofd = -1;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002349 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002350 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002351 real_blkdev);
2352 goto errout;
2353 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002354 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002355 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002356 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002357 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002358 goto errout;
2359 }
2360
2361 f2fs_info = generate_f2fs_info(data.realfd);
2362 if (!f2fs_info)
2363 goto errout;
2364
2365 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2366 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2367 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2368
2369 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2370
2371 data.one_pct = data.tot_used_blocks / 100;
2372 data.cur_pct = 0;
2373 data.time_started = time(NULL);
2374 data.remaining_time = -1;
2375
Wei Wang4375f1b2017-02-24 17:43:01 -08002376 data.buffer = (char *)malloc(f2fs_info->block_size);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002377 if (!data.buffer) {
2378 SLOGE("Failed to allocate crypto buffer");
2379 goto errout;
2380 }
2381
2382 data.count = 0;
2383
2384 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2385 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2386
2387 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002388 SLOGE("Error in running over f2fs blocks");
2389 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002390 goto errout;
2391 }
2392
2393 *size_already_done += size;
2394 rc = 0;
2395
2396errout:
2397 if (rc)
2398 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2399
Paul Lawrence3846be12014-09-22 11:33:54 -07002400 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002401 free(f2fs_info);
2402 free(data.buffer);
2403 close(data.realfd);
2404 close(data.cryptofd);
2405
2406 return rc;
2407}
2408
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002409static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2410 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002411 off64_t tot_size,
2412 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002413{
2414 int realfd, cryptofd;
2415 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002416 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002417 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002418 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002419 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002420
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002421 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002422 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002423 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002424 }
2425
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002426 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002427 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2428 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002429 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002430 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002431 }
2432
2433 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2434 * The size passed in is the number of 512 byte sectors in the filesystem.
2435 * So compute the number of whole 4K blocks we should read/write,
2436 * and the remainder.
2437 */
2438 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2439 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002440 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2441 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002442
2443 SLOGE("Encrypting filesystem in place...");
2444
Paul Lawrence87999172014-02-20 12:21:31 -08002445 i = previously_encrypted_upto + 1 - *size_already_done;
2446
2447 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2448 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2449 goto errout;
2450 }
2451
2452 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2453 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2454 goto errout;
2455 }
2456
2457 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2458 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2459 SLOGE("Error reading initial sectors from real_blkdev %s for "
2460 "inplace encrypt\n", crypto_blkdev);
2461 goto errout;
2462 }
2463 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2464 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2465 "inplace encrypt\n", crypto_blkdev);
2466 goto errout;
2467 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002468 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002469 }
2470 }
2471
Ken Sumrall29d8da82011-05-18 17:20:07 -07002472 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002473 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002474 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002475 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002476 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002477 if (new_pct > cur_pct) {
2478 char buf[8];
2479
2480 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002481 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002482 property_set("vold.encrypt_progress", buf);
2483 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002484 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002485 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002486 goto errout;
2487 }
2488 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002489 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2490 goto errout;
2491 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002492 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002493 CRYPT_SECTORS_PER_BUFSIZE,
2494 i * CRYPT_SECTORS_PER_BUFSIZE);
2495 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002496 }
2497
2498 /* Do any remaining sectors */
2499 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002500 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2501 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002502 goto errout;
2503 }
Paul Lawrence87999172014-02-20 12:21:31 -08002504 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2505 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002506 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002507 } else {
2508 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002509 }
2510 }
2511
Ken Sumrall29d8da82011-05-18 17:20:07 -07002512 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002513 rc = 0;
2514
2515errout:
2516 close(realfd);
2517 close(cryptofd);
2518
2519 return rc;
2520}
2521
JP Abgrall7fc1de82014-10-10 18:43:41 -07002522/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002523static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2524 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002525 off64_t tot_size,
2526 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002527{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002528 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002529 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002530 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002531 }
2532
2533 if (*size_already_done + size < previously_encrypted_upto) {
2534 *size_already_done += size;
2535 return 0;
2536 }
2537
Daniel Rosenberge82df162014-08-15 22:19:23 +00002538 /* TODO: identify filesystem type.
2539 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2540 * then we will drop down to cryptfs_enable_inplace_f2fs.
2541 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002542 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002543 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002544 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002545 return 0;
2546 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002547 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002548
JP Abgrall7fc1de82014-10-10 18:43:41 -07002549 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002550 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002551 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002552 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002553 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002554 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002555
JP Abgrall7fc1de82014-10-10 18:43:41 -07002556 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002557 size, size_already_done, tot_size,
2558 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002559 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2560
2561 /* Hack for b/17898962, the following is the symptom... */
2562 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2563 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2564 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2565 return ENABLE_INPLACE_ERR_DEV;
2566 }
2567 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002568}
2569
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002570#define CRYPTO_ENABLE_WIPE 1
2571#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002572
2573#define FRAMEWORK_BOOT_WAIT 60
2574
Paul Lawrence87999172014-02-20 12:21:31 -08002575static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2576{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002577 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002578 if (fd == -1) {
2579 SLOGE("Error opening file %s", filename);
2580 return -1;
2581 }
2582
2583 char block[CRYPT_INPLACE_BUFSIZE];
2584 memset(block, 0, sizeof(block));
2585 if (unix_read(fd, block, sizeof(block)) < 0) {
2586 SLOGE("Error reading file %s", filename);
2587 close(fd);
2588 return -1;
2589 }
2590
2591 close(fd);
2592
2593 SHA256_CTX c;
2594 SHA256_Init(&c);
2595 SHA256_Update(&c, block, sizeof(block));
2596 SHA256_Final(buf, &c);
2597
2598 return 0;
2599}
2600
JP Abgrall62c7af32014-06-16 13:01:23 -07002601static int get_fs_type(struct fstab_rec *rec)
2602{
2603 if (!strcmp(rec->fs_type, "ext4")) {
2604 return EXT4_FS;
2605 } else if (!strcmp(rec->fs_type, "f2fs")) {
2606 return F2FS_FS;
2607 } else {
2608 return -1;
2609 }
2610}
2611
Paul Lawrence87999172014-02-20 12:21:31 -08002612static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2613 char *crypto_blkdev, char *real_blkdev,
2614 int previously_encrypted_upto)
2615{
2616 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002617 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002618
Paul Lawrence87999172014-02-20 12:21:31 -08002619 /* The size of the userdata partition, and add in the vold volumes below */
2620 tot_encryption_size = crypt_ftr->fs_size;
2621
2622 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002623 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2624 int fs_type = get_fs_type(rec);
2625 if (fs_type < 0) {
2626 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2627 return -1;
2628 }
2629 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002630 } else if (how == CRYPTO_ENABLE_INPLACE) {
2631 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2632 crypt_ftr->fs_size, &cur_encryption_done,
2633 tot_encryption_size,
2634 previously_encrypted_upto);
2635
JP Abgrall7fc1de82014-10-10 18:43:41 -07002636 if (rc == ENABLE_INPLACE_ERR_DEV) {
2637 /* Hack for b/17898962 */
2638 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
Josh Gaofec44372017-08-28 13:22:55 -07002639 cryptfs_reboot(RebootType::reboot);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002640 }
2641
Paul Lawrence73d7a022014-06-09 14:10:09 -07002642 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002643 crypt_ftr->encrypted_upto = cur_encryption_done;
2644 }
2645
Paul Lawrence73d7a022014-06-09 14:10:09 -07002646 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002647 /* The inplace routine never actually sets the progress to 100% due
2648 * to the round down nature of integer division, so set it here */
2649 property_set("vold.encrypt_progress", "100");
2650 }
2651 } else {
2652 /* Shouldn't happen */
2653 SLOGE("cryptfs_enable: internal error, unknown option\n");
2654 rc = -1;
2655 }
2656
2657 return rc;
2658}
2659
Wei Wang4375f1b2017-02-24 17:43:01 -08002660int cryptfs_enable_internal(char *howarg, int crypt_type, const char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002661 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002662{
2663 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002664 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002665 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002666 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002667 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002668 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002669 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002670 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002671 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002672 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002673 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002674 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002675 bool onlyCreateHeader = false;
2676 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002677
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002678 if (!strcmp(howarg, "wipe")) {
2679 how = CRYPTO_ENABLE_WIPE;
2680 } else if (! strcmp(howarg, "inplace")) {
2681 how = CRYPTO_ENABLE_INPLACE;
2682 } else {
2683 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002684 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002685 }
2686
Paul Lawrence87999172014-02-20 12:21:31 -08002687 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002688 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2689 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2690 /* An encryption was underway and was interrupted */
2691 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2692 crypt_ftr.encrypted_upto = 0;
2693 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002694
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002695 /* At this point, we are in an inconsistent state. Until we successfully
2696 complete encryption, a reboot will leave us broken. So mark the
2697 encryption failed in case that happens.
2698 On successfully completing encryption, remove this flag */
2699 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002700
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002701 put_crypt_ftr_and_key(&crypt_ftr);
2702 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2703 if (!check_ftr_sha(&crypt_ftr)) {
2704 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2705 put_crypt_ftr_and_key(&crypt_ftr);
2706 goto error_unencrypted;
2707 }
2708
2709 /* Doing a reboot-encryption*/
2710 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2711 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2712 rebootEncryption = true;
2713 }
Paul Lawrence87999172014-02-20 12:21:31 -08002714 }
2715
2716 property_get("ro.crypto.state", encrypted_state, "");
2717 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2718 SLOGE("Device is already running encrypted, aborting");
2719 goto error_unencrypted;
2720 }
2721
2722 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2723 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002724 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002725
Ken Sumrall3ed82362011-01-28 23:31:16 -08002726 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002727 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002728 if (fd == -1) {
2729 SLOGE("Cannot open block device %s\n", real_blkdev);
2730 goto error_unencrypted;
2731 }
2732 unsigned long nr_sec;
2733 get_blkdev_size(fd, &nr_sec);
2734 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002735 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2736 goto error_unencrypted;
2737 }
2738 close(fd);
2739
2740 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002741 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002742 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002743 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002744 if (fs_size_sec == 0)
2745 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2746
Paul Lawrence87999172014-02-20 12:21:31 -08002747 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002748
2749 if (fs_size_sec > max_fs_size_sec) {
2750 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2751 goto error_unencrypted;
2752 }
2753 }
2754
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002755 /* Get a wakelock as this may take a while, and we don't want the
2756 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2757 * wants to keep the screen on, it can grab a full wakelock.
2758 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002759 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002760 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2761
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002762 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002763 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002764 */
2765 property_set("vold.decrypt", "trigger_shutdown_framework");
2766 SLOGD("Just asked init to shut down class main\n");
2767
Jeff Sharkey9c484982015-03-31 10:35:33 -07002768 /* Ask vold to unmount all devices that it manages */
2769 if (vold_unmountAll()) {
2770 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002771 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002772
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002773 /* no_ui means we are being called from init, not settings.
2774 Now we always reboot from settings, so !no_ui means reboot
2775 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002776 if (!no_ui) {
2777 /* Try fallback, which is to reboot and try there */
2778 onlyCreateHeader = true;
2779 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2780 if (breadcrumb == 0) {
2781 SLOGE("Failed to create breadcrumb file");
2782 goto error_shutting_down;
2783 }
2784 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002785 }
2786
2787 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002788 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002789 /* Now that /data is unmounted, we need to mount a tmpfs
2790 * /data, set a property saying we're doing inplace encryption,
2791 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002792 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002793 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002794 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002795 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002796 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002797 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002798
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002799 /* restart the framework. */
2800 /* Create necessary paths on /data */
2801 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002802 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002803 }
2804
Ken Sumrall92736ef2012-10-17 20:57:14 -07002805 /* Ugh, shutting down the framework is not synchronous, so until it
2806 * can be fixed, this horrible hack will wait a moment for it all to
2807 * shut down before proceeding. Without it, some devices cannot
2808 * restart the graphics services.
2809 */
2810 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002811 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002812
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002813 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002814 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002815 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002816 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2817 goto error_shutting_down;
2818 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002819
Paul Lawrence87999172014-02-20 12:21:31 -08002820 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2821 crypt_ftr.fs_size = nr_sec
2822 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2823 } else {
2824 crypt_ftr.fs_size = nr_sec;
2825 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002826 /* At this point, we are in an inconsistent state. Until we successfully
2827 complete encryption, a reboot will leave us broken. So mark the
2828 encryption failed in case that happens.
2829 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002830 if (onlyCreateHeader) {
2831 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2832 } else {
2833 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2834 }
Paul Lawrence87999172014-02-20 12:21:31 -08002835 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002836 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002837
Paul Lawrence87999172014-02-20 12:21:31 -08002838 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002839 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2840 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002841 SLOGE("Cannot create encrypted master key\n");
2842 goto error_shutting_down;
2843 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002844
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002845 /* Replace scrypted intermediate key if we are preparing for a reboot */
2846 if (onlyCreateHeader) {
2847 unsigned char fake_master_key[KEY_LEN_BYTES];
2848 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2849 memset(fake_master_key, 0, sizeof(fake_master_key));
2850 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2851 encrypted_fake_master_key, &crypt_ftr);
2852 }
2853
Paul Lawrence87999172014-02-20 12:21:31 -08002854 /* Write the key to the end of the partition */
2855 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002856
Paul Lawrence87999172014-02-20 12:21:31 -08002857 /* If any persistent data has been remembered, save it.
2858 * If none, create a valid empty table and save that.
2859 */
2860 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002861 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002862 if (pdata) {
2863 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2864 persist_data = pdata;
2865 }
2866 }
2867 if (persist_data) {
2868 save_persistent_data();
2869 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002870 }
2871
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002872 if (onlyCreateHeader) {
2873 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002874 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002875 }
2876
2877 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002878 /* startup service classes main and late_start */
2879 property_set("vold.decrypt", "trigger_restart_min_framework");
2880 SLOGD("Just triggered restart_min_framework\n");
2881
2882 /* OK, the framework is restarted and will soon be showing a
2883 * progress bar. Time to setup an encrypted mapping, and
2884 * either write a new filesystem, or encrypt in place updating
2885 * the progress bar as we work.
2886 */
2887 }
2888
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002889 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002890 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002891 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002892
Paul Lawrence87999172014-02-20 12:21:31 -08002893 /* If we are continuing, check checksums match */
2894 rc = 0;
2895 if (previously_encrypted_upto) {
2896 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2897 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002898
Paul Lawrence87999172014-02-20 12:21:31 -08002899 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2900 sizeof(hash_first_block)) != 0) {
2901 SLOGE("Checksums do not match - trigger wipe");
2902 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002903 }
2904 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002905
Paul Lawrence87999172014-02-20 12:21:31 -08002906 if (!rc) {
2907 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2908 crypto_blkdev, real_blkdev,
2909 previously_encrypted_upto);
2910 }
2911
2912 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002913 if (!rc && how == CRYPTO_ENABLE_INPLACE
2914 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002915 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2916 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002917 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002918 SLOGE("Error calculating checksum for continuing encryption");
2919 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002920 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002921 }
2922
2923 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002924 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002925
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002926 if (! rc) {
2927 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002928 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002929
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002930 if (how == CRYPTO_ENABLE_INPLACE
2931 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002932 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2933 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002934 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002935 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002936
Paul Lawrence6bfed202014-07-28 12:47:22 -07002937 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002938
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002939 if (how == CRYPTO_ENABLE_WIPE
2940 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002941 char value[PROPERTY_VALUE_MAX];
2942 property_get("ro.crypto.state", value, "");
2943 if (!strcmp(value, "")) {
2944 /* default encryption - continue first boot sequence */
2945 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08002946 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002947 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002948 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2949 // Bring up cryptkeeper that will check the password and set it
2950 property_set("vold.decrypt", "trigger_shutdown_framework");
2951 sleep(2);
2952 property_set("vold.encrypt_progress", "");
2953 cryptfs_trigger_restart_min_framework();
2954 } else {
2955 cryptfs_check_passwd(DEFAULT_PASSWORD);
2956 cryptfs_restart_internal(1);
2957 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002958 return 0;
2959 } else {
2960 sleep(2); /* Give the UI a chance to show 100% progress */
Josh Gaofec44372017-08-28 13:22:55 -07002961 cryptfs_reboot(RebootType::reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002962 }
Paul Lawrence87999172014-02-20 12:21:31 -08002963 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002964 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002965 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002966 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002967 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002968 char value[PROPERTY_VALUE_MAX];
2969
Ken Sumrall319369a2012-06-27 16:30:18 -07002970 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002971 if (!strcmp(value, "1")) {
2972 /* wipe data if encryption failed */
2973 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002974 std::string err;
2975 const std::vector<std::string> options = {
2976 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2977 };
2978 if (!write_bootloader_message(options, &err)) {
2979 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002980 }
Josh Gaofec44372017-08-28 13:22:55 -07002981 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002982 } else {
2983 /* set property to trigger dialog */
2984 property_set("vold.encrypt_progress", "error_partially_encrypted");
2985 release_wake_lock(lockid);
2986 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002987 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002988 }
2989
Ken Sumrall3ed82362011-01-28 23:31:16 -08002990 /* hrm, the encrypt step claims success, but the reboot failed.
2991 * This should not happen.
2992 * Set the property and return. Hope the framework can deal with it.
2993 */
2994 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002995 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002996 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002997
2998error_unencrypted:
2999 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003000 if (lockid[0]) {
3001 release_wake_lock(lockid);
3002 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003003 return -1;
3004
3005error_shutting_down:
3006 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3007 * but the framework is stopped and not restarted to show the error, so it's up to
3008 * vold to restart the system.
3009 */
3010 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07003011 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003012
3013 /* shouldn't get here */
3014 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003015 if (lockid[0]) {
3016 release_wake_lock(lockid);
3017 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003018 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003019}
3020
Paul Lawrence569649f2015-09-09 12:13:00 -07003021int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003022{
Paul Lawrence569649f2015-09-09 12:13:00 -07003023 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003024}
3025
Paul Lawrence569649f2015-09-09 12:13:00 -07003026int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003027{
3028 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07003029 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003030}
3031
3032int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003033{
Paul Crowley38132a12016-02-09 09:50:32 +00003034 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003035 SLOGE("cryptfs_changepw not valid for file encryption");
3036 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003037 }
3038
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003039 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003040 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003041
3042 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003043 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003044 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003045 return -1;
3046 }
3047
Paul Lawrencef4faa572014-01-29 13:31:03 -08003048 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3049 SLOGE("Invalid crypt_type %d", crypt_type);
3050 return -1;
3051 }
3052
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003053 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003054 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003055 SLOGE("Error getting crypt footer and key");
3056 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003057 }
3058
Paul Lawrencef4faa572014-01-29 13:31:03 -08003059 crypt_ftr.crypt_type = crypt_type;
3060
JP Abgrall933216c2015-02-11 13:44:32 -08003061 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003062 : newpw,
3063 crypt_ftr.salt,
3064 saved_master_key,
3065 crypt_ftr.master_key,
3066 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003067 if (rc) {
3068 SLOGE("Encrypt master key failed: %d", rc);
3069 return -1;
3070 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003071 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003072 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003073
3074 return 0;
3075}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003076
Rubin Xu85c01f92014-10-13 12:49:54 +01003077static unsigned int persist_get_max_entries(int encrypted) {
3078 struct crypt_mnt_ftr crypt_ftr;
3079 unsigned int dsize;
3080 unsigned int max_persistent_entries;
3081
3082 /* If encrypted, use the values from the crypt_ftr, otherwise
3083 * use the values for the current spec.
3084 */
3085 if (encrypted) {
3086 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3087 return -1;
3088 }
3089 dsize = crypt_ftr.persist_data_size;
3090 } else {
3091 dsize = CRYPT_PERSIST_DATA_SIZE;
3092 }
3093
3094 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3095 sizeof(struct crypt_persist_entry);
3096
3097 return max_persistent_entries;
3098}
3099
3100static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003101{
3102 unsigned int i;
3103
3104 if (persist_data == NULL) {
3105 return -1;
3106 }
3107 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3108 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3109 /* We found it! */
3110 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3111 return 0;
3112 }
3113 }
3114
3115 return -1;
3116}
3117
Rubin Xu85c01f92014-10-13 12:49:54 +01003118static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003119{
3120 unsigned int i;
3121 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003122 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003123
3124 if (persist_data == NULL) {
3125 return -1;
3126 }
3127
Rubin Xu85c01f92014-10-13 12:49:54 +01003128 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003129
3130 num = persist_data->persist_valid_entries;
3131
3132 for (i = 0; i < num; i++) {
3133 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3134 /* We found an existing entry, update it! */
3135 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3136 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3137 return 0;
3138 }
3139 }
3140
3141 /* We didn't find it, add it to the end, if there is room */
3142 if (persist_data->persist_valid_entries < max_persistent_entries) {
3143 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3144 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3145 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3146 persist_data->persist_valid_entries++;
3147 return 0;
3148 }
3149
3150 return -1;
3151}
3152
Rubin Xu85c01f92014-10-13 12:49:54 +01003153/**
3154 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3155 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3156 */
3157static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003158 unsigned int field_len;
3159 unsigned int key_index;
3160 field_len = strlen(field);
3161
3162 if (index == 0) {
3163 // The first key in a multi-entry field is just the filedname itself.
3164 if (!strcmp(key, field)) {
3165 return 1;
3166 }
3167 }
3168 // Match key against "%s_%d" % (field, index)
3169 if (strlen(key) < field_len + 1 + 1) {
3170 // Need at least a '_' and a digit.
3171 return 0;
3172 }
3173 if (strncmp(key, field, field_len)) {
3174 // If the key does not begin with field, it's not a match.
3175 return 0;
3176 }
3177 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3178 return 0;
3179 }
3180 return key_index >= index;
3181}
3182
3183/*
3184 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3185 * remaining entries starting from index will be deleted.
3186 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3187 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3188 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3189 *
3190 */
3191static int persist_del_keys(const char *fieldname, unsigned index)
3192{
3193 unsigned int i;
3194 unsigned int j;
3195 unsigned int num;
3196
3197 if (persist_data == NULL) {
3198 return PERSIST_DEL_KEY_ERROR_OTHER;
3199 }
3200
3201 num = persist_data->persist_valid_entries;
3202
3203 j = 0; // points to the end of non-deleted entries.
3204 // Filter out to-be-deleted entries in place.
3205 for (i = 0; i < num; i++) {
3206 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3207 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3208 j++;
3209 }
3210 }
3211
3212 if (j < num) {
3213 persist_data->persist_valid_entries = j;
3214 // Zeroise the remaining entries
3215 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3216 return PERSIST_DEL_KEY_OK;
3217 } else {
3218 // Did not find an entry matching the given fieldname
3219 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3220 }
3221}
3222
3223static int persist_count_keys(const char *fieldname)
3224{
3225 unsigned int i;
3226 unsigned int count;
3227
3228 if (persist_data == NULL) {
3229 return -1;
3230 }
3231
3232 count = 0;
3233 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3234 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3235 count++;
3236 }
3237 }
3238
3239 return count;
3240}
3241
Ken Sumrall160b4d62013-04-22 12:15:39 -07003242/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003243int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003244{
Paul Crowley38132a12016-02-09 09:50:32 +00003245 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003246 SLOGE("Cannot get field when file encrypted");
3247 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003248 }
3249
Ken Sumrall160b4d62013-04-22 12:15:39 -07003250 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003251 /* CRYPTO_GETFIELD_OK is success,
3252 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3253 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3254 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003255 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003256 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3257 int i;
3258 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003259
3260 if (persist_data == NULL) {
3261 load_persistent_data();
3262 if (persist_data == NULL) {
3263 SLOGE("Getfield error, cannot load persistent data");
3264 goto out;
3265 }
3266 }
3267
Rubin Xu85c01f92014-10-13 12:49:54 +01003268 // Read value from persistent entries. If the original value is split into multiple entries,
3269 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003270 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003271 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3272 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3273 // value too small
3274 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3275 goto out;
3276 }
3277 rc = CRYPTO_GETFIELD_OK;
3278
3279 for (i = 1; /* break explicitly */; i++) {
3280 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3281 (int) sizeof(temp_field)) {
3282 // If the fieldname is very long, we stop as soon as it begins to overflow the
3283 // maximum field length. At this point we have in fact fully read out the original
3284 // value because cryptfs_setfield would not allow fields with longer names to be
3285 // written in the first place.
3286 break;
3287 }
3288 if (!persist_get_key(temp_field, temp_value)) {
3289 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3290 // value too small.
3291 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3292 goto out;
3293 }
3294 } else {
3295 // Exhaust all entries.
3296 break;
3297 }
3298 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003299 } else {
3300 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003301 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003302 }
3303
3304out:
3305 return rc;
3306}
3307
3308/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003309int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003310{
Paul Crowley38132a12016-02-09 09:50:32 +00003311 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003312 SLOGE("Cannot set field when file encrypted");
3313 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003314 }
3315
Ken Sumrall160b4d62013-04-22 12:15:39 -07003316 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003317 /* 0 is success, negative values are error */
3318 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003319 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003320 unsigned int field_id;
3321 char temp_field[PROPERTY_KEY_MAX];
3322 unsigned int num_entries;
3323 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003324
3325 if (persist_data == NULL) {
3326 load_persistent_data();
3327 if (persist_data == NULL) {
3328 SLOGE("Setfield error, cannot load persistent data");
3329 goto out;
3330 }
3331 }
3332
3333 property_get("ro.crypto.state", encrypted_state, "");
3334 if (!strcmp(encrypted_state, "encrypted") ) {
3335 encrypted = 1;
3336 }
3337
Rubin Xu85c01f92014-10-13 12:49:54 +01003338 // Compute the number of entries required to store value, each entry can store up to
3339 // (PROPERTY_VALUE_MAX - 1) chars
3340 if (strlen(value) == 0) {
3341 // Empty value also needs one entry to store.
3342 num_entries = 1;
3343 } else {
3344 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3345 }
3346
3347 max_keylen = strlen(fieldname);
3348 if (num_entries > 1) {
3349 // Need an extra "_%d" suffix.
3350 max_keylen += 1 + log10(num_entries);
3351 }
3352 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3353 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003354 goto out;
3355 }
3356
Rubin Xu85c01f92014-10-13 12:49:54 +01003357 // Make sure we have enough space to write the new value
3358 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3359 persist_get_max_entries(encrypted)) {
3360 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3361 goto out;
3362 }
3363
3364 // Now that we know persist_data has enough space for value, let's delete the old field first
3365 // to make up space.
3366 persist_del_keys(fieldname, 0);
3367
3368 if (persist_set_key(fieldname, value, encrypted)) {
3369 // fail to set key, should not happen as we have already checked the available space
3370 SLOGE("persist_set_key() error during setfield()");
3371 goto out;
3372 }
3373
3374 for (field_id = 1; field_id < num_entries; field_id++) {
3375 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3376
3377 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3378 // fail to set key, should not happen as we have already checked the available space.
3379 SLOGE("persist_set_key() error during setfield()");
3380 goto out;
3381 }
3382 }
3383
Ken Sumrall160b4d62013-04-22 12:15:39 -07003384 /* If we are running encrypted, save the persistent data now */
3385 if (encrypted) {
3386 if (save_persistent_data()) {
3387 SLOGE("Setfield error, cannot save persistent data");
3388 goto out;
3389 }
3390 }
3391
Rubin Xu85c01f92014-10-13 12:49:54 +01003392 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003393
3394out:
3395 return rc;
3396}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003397
3398/* Checks userdata. Attempt to mount the volume if default-
3399 * encrypted.
3400 * On success trigger next init phase and return 0.
3401 * Currently do not handle failure - see TODO below.
3402 */
3403int cryptfs_mount_default_encrypted(void)
3404{
Paul Lawrence84274cc2016-04-15 15:41:33 -07003405 int crypt_type = cryptfs_get_password_type();
3406 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3407 SLOGE("Bad crypt type - error");
3408 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3409 SLOGD("Password is not default - "
3410 "starting min framework to prompt");
3411 property_set("vold.decrypt", "trigger_restart_min_framework");
3412 return 0;
3413 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3414 SLOGD("Password is default - restarting filesystem");
3415 cryptfs_restart_internal(0);
3416 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003417 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003418 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003419 }
3420
Paul Lawrence6bfed202014-07-28 12:47:22 -07003421 /** Corrupt. Allow us to boot into framework, which will detect bad
3422 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003423 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003424 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003425 return 0;
3426}
3427
3428/* Returns type of the password, default, pattern, pin or password.
3429 */
3430int cryptfs_get_password_type(void)
3431{
Paul Crowley38132a12016-02-09 09:50:32 +00003432 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003433 SLOGE("cryptfs_get_password_type not valid for file encryption");
3434 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003435 }
3436
Paul Lawrencef4faa572014-01-29 13:31:03 -08003437 struct crypt_mnt_ftr crypt_ftr;
3438
3439 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3440 SLOGE("Error getting crypt footer and key\n");
3441 return -1;
3442 }
3443
Paul Lawrence6bfed202014-07-28 12:47:22 -07003444 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3445 return -1;
3446 }
3447
Paul Lawrencef4faa572014-01-29 13:31:03 -08003448 return crypt_ftr.crypt_type;
3449}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003450
Paul Lawrence05335c32015-03-05 09:46:23 -08003451const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003452{
Paul Crowley38132a12016-02-09 09:50:32 +00003453 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003454 SLOGE("cryptfs_get_password not valid for file encryption");
3455 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003456 }
3457
Paul Lawrence399317e2014-03-10 13:20:50 -07003458 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003459 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003460 if (now.tv_sec < password_expiry_time) {
3461 return password;
3462 } else {
3463 cryptfs_clear_password();
3464 return 0;
3465 }
3466}
3467
3468void cryptfs_clear_password()
3469{
3470 if (password) {
3471 size_t len = strlen(password);
3472 memset(password, 0, len);
3473 free(password);
3474 password = 0;
3475 password_expiry_time = 0;
3476 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003477}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003478
3479int cryptfs_enable_file()
3480{
Paul Crowley38132a12016-02-09 09:50:32 +00003481 return e4crypt_initialize_global_de();
Paul Lawrence731a7a22015-04-28 22:14:15 +00003482}
3483
Paul Lawrence0c247462015-10-29 10:30:57 -07003484int cryptfs_isConvertibleToFBE()
3485{
3486 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3487 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
3488}
3489
Paul Lawrence731a7a22015-04-28 22:14:15 +00003490int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3491{
3492 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3493 SLOGE("Failed to initialize crypt_ftr");
3494 return -1;
3495 }
3496
3497 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3498 crypt_ftr->salt, crypt_ftr)) {
3499 SLOGE("Cannot create encrypted master key\n");
3500 return -1;
3501 }
3502
3503 //crypt_ftr->keysize = key_length / 8;
3504 return 0;
3505}
3506
3507int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3508 unsigned char* master_key)
3509{
3510 int rc;
3511
Paul Lawrence731a7a22015-04-28 22:14:15 +00003512 unsigned char* intermediate_key = 0;
3513 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003514
3515 if (password == 0 || *password == 0) {
3516 password = DEFAULT_PASSWORD;
3517 }
3518
Paul Lawrence731a7a22015-04-28 22:14:15 +00003519 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3520 &intermediate_key_size);
3521
Paul Lawrence300dae72016-03-11 11:02:52 -08003522 if (rc) {
3523 SLOGE("Can't calculate intermediate key");
3524 return rc;
3525 }
3526
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003527 int N = 1 << ftr->N_factor;
3528 int r = 1 << ftr->r_factor;
3529 int p = 1 << ftr->p_factor;
3530
3531 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3532
3533 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3534 ftr->salt, sizeof(ftr->salt), N, r, p,
3535 scrypted_intermediate_key,
3536 sizeof(scrypted_intermediate_key));
3537
3538 free(intermediate_key);
3539
3540 if (rc) {
Paul Lawrence300dae72016-03-11 11:02:52 -08003541 SLOGE("Can't scrypt intermediate key");
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003542 return rc;
3543 }
3544
3545 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3546 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00003547}
3548
3549int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3550 const unsigned char* master_key)
3551{
3552 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3553 ftr);
3554}
Paul Lawrence6e410592016-05-24 14:20:38 -07003555
Eric Biggersb45caaf2017-02-02 14:52:12 -08003556void cryptfs_get_file_encryption_modes(const char **contents_mode_ret,
3557 const char **filenames_mode_ret)
Paul Lawrence6e410592016-05-24 14:20:38 -07003558{
3559 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
Eric Biggersb45caaf2017-02-02 14:52:12 -08003560 fs_mgr_get_file_encryption_modes(rec, contents_mode_ret, filenames_mode_ret);
Paul Lawrence6e410592016-05-24 14:20:38 -07003561}