blob: 6319362716e3421391698def0e5e3373b9fd4983 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070041#include <ext4_utils/ext4.h>
42#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070058#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000059#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000060#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080061#include "CheckBattery.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070062#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080063#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000064#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080065#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070066#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080067extern "C" {
68#include <crypto_scrypt.h>
69}
Mark Salyzyn3e971272014-01-21 13:27:04 -080070
Mark Salyzyn5eecc442014-02-12 14:16:14 -080071#define UNUSED __attribute__((unused))
72
Ken Sumrall8f869aa2010-12-03 03:47:09 -080073#define DM_CRYPT_BUF_SIZE 4096
74
Jason parks70a4b3f2011-01-28 10:10:47 -060075#define HASH_COUNT 2000
76#define KEY_LEN_BYTES 16
77#define IV_LEN_BYTES 16
78
Ken Sumrall29d8da82011-05-18 17:20:07 -070079#define KEY_IN_FOOTER "footer"
80
Paul Lawrence3bd36d52015-06-09 13:37:44 -070081#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080082
Paul Lawrence3d99eba2015-11-20 07:07:19 -080083#define CRYPTO_BLOCK_DEVICE "userdata"
84
85#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
86
Ken Sumrall29d8da82011-05-18 17:20:07 -070087#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070088#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070089
Ken Sumralle919efe2012-09-29 17:07:41 -070090#define TABLE_LOAD_RETRIES 10
91
Shawn Willden47ba10d2014-09-03 17:07:06 -060092#define RSA_KEY_SIZE 2048
93#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
94#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060095#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070096
Paul Lawrence8e3f4512014-09-08 10:11:17 -070097#define RETRY_MOUNT_ATTEMPTS 10
98#define RETRY_MOUNT_DELAY_SECONDS 1
99
Jason parks70a4b3f2011-01-28 10:10:47 -0600100static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700101static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600102static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700103static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800104
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700105/* Should we use keymaster? */
106static int keymaster_check_compatibility()
107{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000108 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700109}
110
111/* Create a new keymaster key and store it in this footer */
112static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
113{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800114 if (ftr->keymaster_blob_size) {
115 SLOGI("Already have key");
116 return 0;
117 }
118
Janis Danisevskis015ec302017-01-31 11:31:08 +0000119 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
120 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
121 &ftr->keymaster_blob_size);
122 if (rc) {
123 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
124 SLOGE("Keymaster key blob to large)");
125 ftr->keymaster_blob_size = 0;
126 }
127 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700128 return -1;
129 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000130 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700131}
132
Shawn Willdene17a9c42014-09-08 13:04:08 -0600133/* This signs the given object using the keymaster key. */
134static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600135 const unsigned char *object,
136 const size_t object_size,
137 unsigned char **signature,
138 size_t *signature_size)
139{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600140 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600141 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600142 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600143
Shawn Willdene17a9c42014-09-08 13:04:08 -0600144 // To sign a message with RSA, the message must satisfy two
145 // constraints:
146 //
147 // 1. The message, when interpreted as a big-endian numeric value, must
148 // be strictly less than the public modulus of the RSA key. Note
149 // that because the most significant bit of the public modulus is
150 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
151 // key), an n-bit message with most significant bit 0 always
152 // satisfies this requirement.
153 //
154 // 2. The message must have the same length in bits as the public
155 // modulus of the RSA key. This requirement isn't mathematically
156 // necessary, but is necessary to ensure consistency in
157 // implementations.
158 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600159 case KDF_SCRYPT_KEYMASTER:
160 // This ensures the most significant byte of the signed message
161 // is zero. We could have zero-padded to the left instead, but
162 // this approach is slightly more robust against changes in
163 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600164 // so) because we really should be using a proper deterministic
165 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800166 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600167 SLOGI("Signing safely-padded object");
168 break;
169 default:
170 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000171 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600172 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000173 return keymaster_sign_object_for_cryptfs_scrypt(ftr->keymaster_blob, ftr->keymaster_blob_size,
174 KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign, to_sign_size, signature, signature_size);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600175}
176
Paul Lawrence399317e2014-03-10 13:20:50 -0700177/* Store password when userdata is successfully decrypted and mounted.
178 * Cleared by cryptfs_clear_password
179 *
180 * To avoid a double prompt at boot, we need to store the CryptKeeper
181 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
182 * Since the entire framework is torn down and rebuilt after encryption,
183 * we have to use a daemon or similar to store the password. Since vold
184 * is secured against IPC except from system processes, it seems a reasonable
185 * place to store this.
186 *
187 * password should be cleared once it has been used.
188 *
189 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800190 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700191static char* password = 0;
192static int password_expiry_time = 0;
193static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800194
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800195extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800196
Paul Lawrence87999172014-02-20 12:21:31 -0800197enum RebootType {reboot, recovery, shutdown};
198static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700199{
Paul Lawrence87999172014-02-20 12:21:31 -0800200 switch(rt) {
201 case reboot:
202 property_set(ANDROID_RB_PROPERTY, "reboot");
203 break;
204
205 case recovery:
206 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
207 break;
208
209 case shutdown:
210 property_set(ANDROID_RB_PROPERTY, "shutdown");
211 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700212 }
Paul Lawrence87999172014-02-20 12:21:31 -0800213
Ken Sumralladfba362013-06-04 16:37:52 -0700214 sleep(20);
215
216 /* Shouldn't get here, reboot should happen before sleep times out */
217 return;
218}
219
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800220static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
221{
222 memset(io, 0, dataSize);
223 io->data_size = dataSize;
224 io->data_start = sizeof(struct dm_ioctl);
225 io->version[0] = 4;
226 io->version[1] = 0;
227 io->version[2] = 0;
228 io->flags = flags;
229 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100230 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800231 }
232}
233
Kenny Rootc4c70f12013-06-14 12:11:38 -0700234/**
235 * Gets the default device scrypt parameters for key derivation time tuning.
236 * The parameters should lead to about one second derivation time for the
237 * given device.
238 */
239static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700240 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000241 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700242
Paul Crowley63c18d32016-02-10 14:02:47 +0000243 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
244 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
245 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
246 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700247 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000248 ftr->N_factor = Nf;
249 ftr->r_factor = rf;
250 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700251}
252
Ken Sumrall3ed82362011-01-28 23:31:16 -0800253static unsigned int get_fs_size(char *dev)
254{
255 int fd, block_size;
256 struct ext4_super_block sb;
257 off64_t len;
258
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700259 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800260 SLOGE("Cannot open device to get filesystem size ");
261 return 0;
262 }
263
264 if (lseek64(fd, 1024, SEEK_SET) < 0) {
265 SLOGE("Cannot seek to superblock");
266 return 0;
267 }
268
269 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
270 SLOGE("Cannot read superblock");
271 return 0;
272 }
273
274 close(fd);
275
Daniel Rosenberge82df162014-08-15 22:19:23 +0000276 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
277 SLOGE("Not a valid ext4 superblock");
278 return 0;
279 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800280 block_size = 1024 << sb.s_log_block_size;
281 /* compute length in bytes */
282 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
283
284 /* return length in sectors */
285 return (unsigned int) (len / 512);
286}
287
Ken Sumrall160b4d62013-04-22 12:15:39 -0700288static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
289{
290 static int cached_data = 0;
291 static off64_t cached_off = 0;
292 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
293 int fd;
294 char key_loc[PROPERTY_VALUE_MAX];
295 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700296 int rc = -1;
297
298 if (!cached_data) {
299 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
300
301 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700302 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700303 SLOGE("Cannot open real block device %s\n", real_blkdev);
304 return -1;
305 }
306
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900307 unsigned long nr_sec = 0;
308 get_blkdev_size(fd, &nr_sec);
309 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700310 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
311 * encryption info footer and key, and plenty of bytes to spare for future
312 * growth.
313 */
314 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
315 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
316 cached_data = 1;
317 } else {
318 SLOGE("Cannot get size of block device %s\n", real_blkdev);
319 }
320 close(fd);
321 } else {
322 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
323 cached_off = 0;
324 cached_data = 1;
325 }
326 }
327
328 if (cached_data) {
329 if (metadata_fname) {
330 *metadata_fname = cached_metadata_fname;
331 }
332 if (off) {
333 *off = cached_off;
334 }
335 rc = 0;
336 }
337
338 return rc;
339}
340
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800341/* Set sha256 checksum in structure */
342static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
343{
344 SHA256_CTX c;
345 SHA256_Init(&c);
346 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
347 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
348 SHA256_Final(crypt_ftr->sha256, &c);
349}
350
Ken Sumralle8744072011-01-18 22:01:55 -0800351/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800352 * update the failed mount count but not change the key.
353 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700354static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800355{
356 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800357 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700358 /* starting_off is set to the SEEK_SET offset
359 * where the crypto structure starts
360 */
361 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800362 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700363 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700364 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800365
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800366 set_ftr_sha(crypt_ftr);
367
Ken Sumrall160b4d62013-04-22 12:15:39 -0700368 if (get_crypt_ftr_info(&fname, &starting_off)) {
369 SLOGE("Unable to get crypt_ftr_info\n");
370 return -1;
371 }
372 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700373 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700374 return -1;
375 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700376 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700377 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378 return -1;
379 }
380
381 /* Seek to the start of the crypt footer */
382 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
383 SLOGE("Cannot seek to real block device footer\n");
384 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800385 }
386
387 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
388 SLOGE("Cannot write real block device footer\n");
389 goto errout;
390 }
391
Ken Sumrall3be890f2011-09-14 16:53:46 -0700392 fstat(fd, &statbuf);
393 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700394 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700395 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800396 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800397 goto errout;
398 }
399 }
400
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800401 /* Success! */
402 rc = 0;
403
404errout:
405 close(fd);
406 return rc;
407
408}
409
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800410static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
411{
412 struct crypt_mnt_ftr copy;
413 memcpy(&copy, crypt_ftr, sizeof(copy));
414 set_ftr_sha(&copy);
415 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
416}
417
Ken Sumrall160b4d62013-04-22 12:15:39 -0700418static inline int unix_read(int fd, void* buff, int len)
419{
420 return TEMP_FAILURE_RETRY(read(fd, buff, len));
421}
422
423static inline int unix_write(int fd, const void* buff, int len)
424{
425 return TEMP_FAILURE_RETRY(write(fd, buff, len));
426}
427
428static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
429{
430 memset(pdata, 0, len);
431 pdata->persist_magic = PERSIST_DATA_MAGIC;
432 pdata->persist_valid_entries = 0;
433}
434
435/* A routine to update the passed in crypt_ftr to the lastest version.
436 * fd is open read/write on the device that holds the crypto footer and persistent
437 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
438 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
439 */
440static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
441{
Kenny Root7434b312013-06-14 11:29:53 -0700442 int orig_major = crypt_ftr->major_version;
443 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700444
Kenny Root7434b312013-06-14 11:29:53 -0700445 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
446 struct crypt_persist_data *pdata;
447 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700448
Kenny Rootc4c70f12013-06-14 12:11:38 -0700449 SLOGW("upgrading crypto footer to 1.1");
450
Wei Wang4375f1b2017-02-24 17:43:01 -0800451 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700452 if (pdata == NULL) {
453 SLOGE("Cannot allocate persisent data\n");
454 return;
455 }
456 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
457
458 /* Need to initialize the persistent data area */
459 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
460 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100461 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700462 return;
463 }
464 /* Write all zeros to the first copy, making it invalid */
465 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
466
467 /* Write a valid but empty structure to the second copy */
468 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
469 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
470
471 /* Update the footer */
472 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
473 crypt_ftr->persist_data_offset[0] = pdata_offset;
474 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
475 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100476 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700477 }
478
Paul Lawrencef4faa572014-01-29 13:31:03 -0800479 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700480 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800481 /* But keep the old kdf_type.
482 * It will get updated later to KDF_SCRYPT after the password has been verified.
483 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700484 crypt_ftr->kdf_type = KDF_PBKDF2;
485 get_device_scrypt_params(crypt_ftr);
486 crypt_ftr->minor_version = 2;
487 }
488
Paul Lawrencef4faa572014-01-29 13:31:03 -0800489 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
490 SLOGW("upgrading crypto footer to 1.3");
491 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
492 crypt_ftr->minor_version = 3;
493 }
494
Kenny Root7434b312013-06-14 11:29:53 -0700495 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
496 if (lseek64(fd, offset, SEEK_SET) == -1) {
497 SLOGE("Cannot seek to crypt footer\n");
498 return;
499 }
500 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700501 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700502}
503
504
505static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800506{
507 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800508 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700509 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800510 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700511 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700512 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800513
Ken Sumrall160b4d62013-04-22 12:15:39 -0700514 if (get_crypt_ftr_info(&fname, &starting_off)) {
515 SLOGE("Unable to get crypt_ftr_info\n");
516 return -1;
517 }
518 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700519 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700520 return -1;
521 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700522 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700523 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700524 return -1;
525 }
526
527 /* Make sure it's 16 Kbytes in length */
528 fstat(fd, &statbuf);
529 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
530 SLOGE("footer file %s is not the expected size!\n", fname);
531 goto errout;
532 }
533
534 /* Seek to the start of the crypt footer */
535 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
536 SLOGE("Cannot seek to real block device footer\n");
537 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800538 }
539
540 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
541 SLOGE("Cannot read real block device footer\n");
542 goto errout;
543 }
544
545 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700546 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800547 goto errout;
548 }
549
Kenny Rootc96a5f82013-06-14 12:08:28 -0700550 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
551 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
552 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800553 goto errout;
554 }
555
Kenny Rootc96a5f82013-06-14 12:08:28 -0700556 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
557 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
558 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800559 }
560
Ken Sumrall160b4d62013-04-22 12:15:39 -0700561 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
562 * copy on disk before returning.
563 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700564 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700565 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800566 }
567
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800568 /* Success! */
569 rc = 0;
570
571errout:
572 close(fd);
573 return rc;
574}
575
Ken Sumrall160b4d62013-04-22 12:15:39 -0700576static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
577{
578 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
579 crypt_ftr->persist_data_offset[1]) {
580 SLOGE("Crypt_ftr persist data regions overlap");
581 return -1;
582 }
583
584 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
585 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
586 return -1;
587 }
588
589 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
590 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
591 CRYPT_FOOTER_OFFSET) {
592 SLOGE("Persistent data extends past crypto footer");
593 return -1;
594 }
595
596 return 0;
597}
598
599static int load_persistent_data(void)
600{
601 struct crypt_mnt_ftr crypt_ftr;
602 struct crypt_persist_data *pdata = NULL;
603 char encrypted_state[PROPERTY_VALUE_MAX];
604 char *fname;
605 int found = 0;
606 int fd;
607 int ret;
608 int i;
609
610 if (persist_data) {
611 /* Nothing to do, we've already loaded or initialized it */
612 return 0;
613 }
614
615
616 /* If not encrypted, just allocate an empty table and initialize it */
617 property_get("ro.crypto.state", encrypted_state, "");
618 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800619 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620 if (pdata) {
621 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
622 persist_data = pdata;
623 return 0;
624 }
625 return -1;
626 }
627
628 if(get_crypt_ftr_and_key(&crypt_ftr)) {
629 return -1;
630 }
631
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700632 if ((crypt_ftr.major_version < 1)
633 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700634 SLOGE("Crypt_ftr version doesn't support persistent data");
635 return -1;
636 }
637
638 if (get_crypt_ftr_info(&fname, NULL)) {
639 return -1;
640 }
641
642 ret = validate_persistent_data_storage(&crypt_ftr);
643 if (ret) {
644 return -1;
645 }
646
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700647 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700648 if (fd < 0) {
649 SLOGE("Cannot open %s metadata file", fname);
650 return -1;
651 }
652
Wei Wang4375f1b2017-02-24 17:43:01 -0800653 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800654 if (pdata == NULL) {
655 SLOGE("Cannot allocate memory for persistent data");
656 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700657 }
658
659 for (i = 0; i < 2; i++) {
660 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
661 SLOGE("Cannot seek to read persistent data on %s", fname);
662 goto err2;
663 }
664 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
665 SLOGE("Error reading persistent data on iteration %d", i);
666 goto err2;
667 }
668 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
669 found = 1;
670 break;
671 }
672 }
673
674 if (!found) {
675 SLOGI("Could not find valid persistent data, creating");
676 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
677 }
678
679 /* Success */
680 persist_data = pdata;
681 close(fd);
682 return 0;
683
684err2:
685 free(pdata);
686
687err:
688 close(fd);
689 return -1;
690}
691
692static int save_persistent_data(void)
693{
694 struct crypt_mnt_ftr crypt_ftr;
695 struct crypt_persist_data *pdata;
696 char *fname;
697 off64_t write_offset;
698 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700699 int fd;
700 int ret;
701
702 if (persist_data == NULL) {
703 SLOGE("No persistent data to save");
704 return -1;
705 }
706
707 if(get_crypt_ftr_and_key(&crypt_ftr)) {
708 return -1;
709 }
710
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700711 if ((crypt_ftr.major_version < 1)
712 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700713 SLOGE("Crypt_ftr version doesn't support persistent data");
714 return -1;
715 }
716
717 ret = validate_persistent_data_storage(&crypt_ftr);
718 if (ret) {
719 return -1;
720 }
721
722 if (get_crypt_ftr_info(&fname, NULL)) {
723 return -1;
724 }
725
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700726 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700727 if (fd < 0) {
728 SLOGE("Cannot open %s metadata file", fname);
729 return -1;
730 }
731
Wei Wang4375f1b2017-02-24 17:43:01 -0800732 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700733 if (pdata == NULL) {
734 SLOGE("Cannot allocate persistant data");
735 goto err;
736 }
737
738 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
739 SLOGE("Cannot seek to read persistent data on %s", fname);
740 goto err2;
741 }
742
743 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
744 SLOGE("Error reading persistent data before save");
745 goto err2;
746 }
747
748 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
749 /* The first copy is the curent valid copy, so write to
750 * the second copy and erase this one */
751 write_offset = crypt_ftr.persist_data_offset[1];
752 erase_offset = crypt_ftr.persist_data_offset[0];
753 } else {
754 /* The second copy must be the valid copy, so write to
755 * the first copy, and erase the second */
756 write_offset = crypt_ftr.persist_data_offset[0];
757 erase_offset = crypt_ftr.persist_data_offset[1];
758 }
759
760 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100761 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700762 SLOGE("Cannot seek to write persistent data");
763 goto err2;
764 }
765 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
766 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100767 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700768 SLOGE("Cannot seek to erase previous persistent data");
769 goto err2;
770 }
771 fsync(fd);
772 memset(pdata, 0, crypt_ftr.persist_data_size);
773 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
774 (int) crypt_ftr.persist_data_size) {
775 SLOGE("Cannot write to erase previous persistent data");
776 goto err2;
777 }
778 fsync(fd);
779 } else {
780 SLOGE("Cannot write to save persistent data");
781 goto err2;
782 }
783
784 /* Success */
785 free(pdata);
786 close(fd);
787 return 0;
788
789err2:
790 free(pdata);
791err:
792 close(fd);
793 return -1;
794}
795
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800796/* Convert a binary key of specified length into an ascii hex string equivalent,
797 * without the leading 0x and with null termination
798 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700799static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700800 unsigned int keysize, char *master_key_ascii) {
801 unsigned int i, a;
802 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800803
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700804 for (i=0, a=0; i<keysize; i++, a+=2) {
805 /* For each byte, write out two ascii hex digits */
806 nibble = (master_key[i] >> 4) & 0xf;
807 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800808
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700809 nibble = master_key[i] & 0xf;
810 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
811 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800812
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700813 /* Add the null termination */
814 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800815
816}
817
Jeff Sharkey9c484982015-03-31 10:35:33 -0700818static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
819 const unsigned char *master_key, const char *real_blk_name,
820 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800821 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800822 struct dm_ioctl *io;
823 struct dm_target_spec *tgt;
824 char *crypt_params;
825 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
George Burgess IV605d7ae2016-02-29 13:39:17 -0800826 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800827 int i;
828
829 io = (struct dm_ioctl *) buffer;
830
831 /* Load the mapping table for this device */
832 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
833
834 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
835 io->target_count = 1;
836 tgt->status = 0;
837 tgt->sector_start = 0;
838 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700839 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800840
841 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
842 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800843
844 buff_offset = crypt_params - buffer;
845 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
846 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
847 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800848 crypt_params += strlen(crypt_params) + 1;
849 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
850 tgt->next = crypt_params - buffer;
851
852 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
853 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
854 break;
855 }
856 usleep(500000);
857 }
858
859 if (i == TABLE_LOAD_RETRIES) {
860 /* We failed to load the table, return an error */
861 return -1;
862 } else {
863 return i + 1;
864 }
865}
866
867
868static int get_dm_crypt_version(int fd, const char *name, int *version)
869{
870 char buffer[DM_CRYPT_BUF_SIZE];
871 struct dm_ioctl *io;
872 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800873
874 io = (struct dm_ioctl *) buffer;
875
876 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
877
878 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
879 return -1;
880 }
881
882 /* Iterate over the returned versions, looking for name of "crypt".
883 * When found, get and return the version.
884 */
885 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
886 while (v->next) {
887 if (! strcmp(v->name, "crypt")) {
888 /* We found the crypt driver, return the version, and get out */
889 version[0] = v->version[0];
890 version[1] = v->version[1];
891 version[2] = v->version[2];
892 return 0;
893 }
894 v = (struct dm_target_versions *)(((char *)v) + v->next);
895 }
896
897 return -1;
898}
899
Jeff Sharkey9c484982015-03-31 10:35:33 -0700900static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
901 const unsigned char *master_key, const char *real_blk_name,
902 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800903 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800904 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800905 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -0700906 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800907 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800908 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800909 int version[3];
Wei Wang4375f1b2017-02-24 17:43:01 -0800910 const char *extra_params;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800911 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800912
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700913 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800914 SLOGE("Cannot open device-mapper\n");
915 goto errout;
916 }
917
918 io = (struct dm_ioctl *) buffer;
919
920 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -0800921 err = ioctl(fd, DM_DEV_CREATE, io);
922 if (err) {
923 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800924 goto errout;
925 }
926
927 /* Get the device status, in particular, the name of it's device file */
928 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
929 if (ioctl(fd, DM_DEV_STATUS, io)) {
930 SLOGE("Cannot retrieve dm-crypt device status\n");
931 goto errout;
932 }
933 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
934 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
935
Ken Sumralldb5e0262013-02-05 17:39:48 -0800936 extra_params = "";
937 if (! get_dm_crypt_version(fd, name, version)) {
938 /* Support for allow_discards was added in version 1.11.0 */
939 if ((version[0] >= 2) ||
940 ((version[0] == 1) && (version[1] >= 11))) {
941 extra_params = "1 allow_discards";
942 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
943 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700944 }
945
Ken Sumralldb5e0262013-02-05 17:39:48 -0800946 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
947 fd, extra_params);
948 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800949 SLOGE("Cannot load dm-crypt mapping table.\n");
950 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800951 } else if (load_count > 1) {
952 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800953 }
954
955 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800956 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800957
958 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
959 SLOGE("Cannot resume the dm-crypt device\n");
960 goto errout;
961 }
962
963 /* We made it here with no errors. Woot! */
964 retval = 0;
965
966errout:
967 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
968
969 return retval;
970}
971
Wei Wang4375f1b2017-02-24 17:43:01 -0800972static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800973{
974 int fd;
975 char buffer[DM_CRYPT_BUF_SIZE];
976 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800977 int retval = -1;
978
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700979 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800980 SLOGE("Cannot open device-mapper\n");
981 goto errout;
982 }
983
984 io = (struct dm_ioctl *) buffer;
985
986 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
987 if (ioctl(fd, DM_DEV_REMOVE, io)) {
988 SLOGE("Cannot remove dm-crypt device\n");
989 goto errout;
990 }
991
992 /* We made it here with no errors. Woot! */
993 retval = 0;
994
995errout:
996 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
997
998 return retval;
999
1000}
1001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001002static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001003 unsigned char *ikey, void *params UNUSED)
1004{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001005 SLOGI("Using pbkdf2 for cryptfs KDF");
1006
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001007 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001008 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1009 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1010 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001011}
1012
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001013static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001014 unsigned char *ikey, void *params)
1015{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001016 SLOGI("Using scrypt for cryptfs KDF");
1017
Kenny Rootc4c70f12013-06-14 12:11:38 -07001018 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1019
1020 int N = 1 << ftr->N_factor;
1021 int r = 1 << ftr->r_factor;
1022 int p = 1 << ftr->p_factor;
1023
1024 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001025 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001026 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1027 salt, SALT_LEN, N, r, p, ikey,
1028 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001029
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001030 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001031}
1032
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001033static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1034 unsigned char *ikey, void *params)
1035{
1036 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1037
1038 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001039 size_t signature_size;
1040 unsigned char* signature;
1041 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1042
1043 int N = 1 << ftr->N_factor;
1044 int r = 1 << ftr->r_factor;
1045 int p = 1 << ftr->p_factor;
1046
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001047 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1048 salt, SALT_LEN, N, r, p, ikey,
1049 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001050
1051 if (rc) {
1052 SLOGE("scrypt failed");
1053 return -1;
1054 }
1055
Shawn Willdene17a9c42014-09-08 13:04:08 -06001056 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1057 &signature, &signature_size)) {
1058 SLOGE("Signing failed");
1059 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001060 }
1061
1062 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1063 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1064 free(signature);
1065
1066 if (rc) {
1067 SLOGE("scrypt failed");
1068 return -1;
1069 }
1070
1071 return 0;
1072}
1073
1074static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1075 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001076 unsigned char *encrypted_master_key,
1077 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001078{
1079 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1080 EVP_CIPHER_CTX e_ctx;
1081 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001082 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001083
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001084 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001085 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001086
1087 switch (crypt_ftr->kdf_type) {
1088 case KDF_SCRYPT_KEYMASTER:
1089 if (keymaster_create_key(crypt_ftr)) {
1090 SLOGE("keymaster_create_key failed");
1091 return -1;
1092 }
1093
1094 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1095 SLOGE("scrypt failed");
1096 return -1;
1097 }
1098 break;
1099
1100 case KDF_SCRYPT:
1101 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1102 SLOGE("scrypt failed");
1103 return -1;
1104 }
1105 break;
1106
1107 default:
1108 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001109 return -1;
1110 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001111
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001112 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001113 EVP_CIPHER_CTX_init(&e_ctx);
1114 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001115 SLOGE("EVP_EncryptInit failed\n");
1116 return -1;
1117 }
1118 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001119
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001120 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001121 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001122 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001123 SLOGE("EVP_EncryptUpdate failed\n");
1124 return -1;
1125 }
Adam Langley889c4f12014-09-03 14:23:13 -07001126 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001127 SLOGE("EVP_EncryptFinal failed\n");
1128 return -1;
1129 }
1130
1131 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1132 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1133 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001134 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001135
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001136 /* Store the scrypt of the intermediate key, so we can validate if it's a
1137 password error or mount error when things go wrong.
1138 Note there's no need to check for errors, since if this is incorrect, we
1139 simply won't wipe userdata, which is the correct default behavior
1140 */
1141 int N = 1 << crypt_ftr->N_factor;
1142 int r = 1 << crypt_ftr->r_factor;
1143 int p = 1 << crypt_ftr->p_factor;
1144
1145 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1146 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1147 crypt_ftr->scrypted_intermediate_key,
1148 sizeof(crypt_ftr->scrypted_intermediate_key));
1149
1150 if (rc) {
1151 SLOGE("encrypt_master_key: crypto_scrypt failed");
1152 }
1153
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001154 EVP_CIPHER_CTX_cleanup(&e_ctx);
1155
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001156 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157}
1158
Paul Lawrence731a7a22015-04-28 22:14:15 +00001159static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001160 unsigned char *encrypted_master_key,
1161 unsigned char *decrypted_master_key,
1162 kdf_func kdf, void *kdf_params,
1163 unsigned char** intermediate_key,
1164 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165{
1166 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001167 EVP_CIPHER_CTX d_ctx;
1168 int decrypted_len, final_len;
1169
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001170 /* Turn the password into an intermediate key and IV that can decrypt the
1171 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001172 if (kdf(passwd, salt, ikey, kdf_params)) {
1173 SLOGE("kdf failed");
1174 return -1;
1175 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001176
1177 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001178 EVP_CIPHER_CTX_init(&d_ctx);
1179 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001180 return -1;
1181 }
1182 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1183 /* Decrypt the master key */
1184 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1185 encrypted_master_key, KEY_LEN_BYTES)) {
1186 return -1;
1187 }
Adam Langley889c4f12014-09-03 14:23:13 -07001188 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001189 return -1;
1190 }
1191
1192 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1193 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001194 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001195
1196 /* Copy intermediate key if needed by params */
1197 if (intermediate_key && intermediate_key_size) {
1198 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001199 if (*intermediate_key) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001200 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1201 *intermediate_key_size = KEY_LEN_BYTES;
1202 }
1203 }
1204
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001205 EVP_CIPHER_CTX_cleanup(&d_ctx);
1206
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001207 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001208}
1209
Kenny Rootc4c70f12013-06-14 12:11:38 -07001210static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001211{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001212 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001213 *kdf = scrypt_keymaster;
1214 *kdf_params = ftr;
1215 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001216 *kdf = scrypt;
1217 *kdf_params = ftr;
1218 } else {
1219 *kdf = pbkdf2;
1220 *kdf_params = NULL;
1221 }
1222}
1223
Paul Lawrence731a7a22015-04-28 22:14:15 +00001224static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001225 struct crypt_mnt_ftr *crypt_ftr,
1226 unsigned char** intermediate_key,
1227 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001228{
1229 kdf_func kdf;
1230 void *kdf_params;
1231 int ret;
1232
1233 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001234 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1235 decrypted_master_key, kdf, kdf_params,
1236 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001237 if (ret != 0) {
1238 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001239 }
1240
1241 return ret;
1242}
1243
Wei Wang4375f1b2017-02-24 17:43:01 -08001244static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001245 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001246 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001247 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001248
1249 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001250 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001251 read(fd, key_buf, sizeof(key_buf));
1252 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001253 close(fd);
1254
1255 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001256 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001257}
1258
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001259int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260{
Greg Hackmann955653e2014-09-24 14:55:20 -07001261 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001262#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001263
1264 /* Now umount the tmpfs filesystem */
1265 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001266 if (umount(mountpoint) == 0) {
1267 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001268 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001269
1270 if (errno == EINVAL) {
1271 /* EINVAL is returned if the directory is not a mountpoint,
1272 * i.e. there is no filesystem mounted there. So just get out.
1273 */
1274 break;
1275 }
1276
1277 err = errno;
1278
1279 /* If allowed, be increasingly aggressive before the last two retries */
1280 if (kill) {
1281 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1282 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001283 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001284 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1285 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001286 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001287 }
1288 }
1289
1290 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001291 }
1292
1293 if (i < WAIT_UNMOUNT_COUNT) {
1294 SLOGD("unmounting %s succeeded\n", mountpoint);
1295 rc = 0;
1296 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001297 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001298 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001299 rc = -1;
1300 }
1301
1302 return rc;
1303}
1304
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001305static int prep_data_fs(void)
1306{
1307 int i;
1308
Jeff Sharkey47695b22016-02-01 17:02:29 -07001309 // NOTE: post_fs_data results in init calling back around to vold, so all
1310 // callers to this method must be async
1311
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001312 /* Do the prep of the /data filesystem */
1313 property_set("vold.post_fs_data_done", "0");
1314 property_set("vold.decrypt", "trigger_post_fs_data");
1315 SLOGD("Just triggered post_fs_data\n");
1316
Ken Sumrallc5872692013-05-14 15:26:31 -07001317 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang4375f1b2017-02-24 17:43:01 -08001318 if (!android::base::WaitForProperty("vold.post_fs_data_done",
1319 "1",
1320 std::chrono::seconds(50))) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001321 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001322 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001323 return -1;
1324 } else {
1325 SLOGD("post_fs_data done\n");
1326 return 0;
1327 }
1328}
1329
Paul Lawrence74f29f12014-08-28 15:54:10 -07001330static void cryptfs_set_corrupt()
1331{
1332 // Mark the footer as bad
1333 struct crypt_mnt_ftr crypt_ftr;
1334 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1335 SLOGE("Failed to get crypto footer - panic");
1336 return;
1337 }
1338
1339 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1340 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1341 SLOGE("Failed to set crypto footer - panic");
1342 return;
1343 }
1344}
1345
1346static void cryptfs_trigger_restart_min_framework()
1347{
1348 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1349 SLOGE("Failed to mount tmpfs on data - panic");
1350 return;
1351 }
1352
1353 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1354 SLOGE("Failed to trigger post fs data - panic");
1355 return;
1356 }
1357
1358 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1359 SLOGE("Failed to trigger restart min framework - panic");
1360 return;
1361 }
1362}
1363
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001364/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001365static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001366{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001367 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001368 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001369 static int restart_successful = 0;
1370
1371 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001372 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001373 SLOGE("Encrypted filesystem not validated, aborting");
1374 return -1;
1375 }
1376
1377 if (restart_successful) {
1378 SLOGE("System already restarted with encrypted disk, aborting");
1379 return -1;
1380 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001381
Paul Lawrencef4faa572014-01-29 13:31:03 -08001382 if (restart_main) {
1383 /* Here is where we shut down the framework. The init scripts
1384 * start all services in one of three classes: core, main or late_start.
1385 * On boot, we start core and main. Now, we stop main, but not core,
1386 * as core includes vold and a few other really important things that
1387 * we need to keep running. Once main has stopped, we should be able
1388 * to umount the tmpfs /data, then mount the encrypted /data.
1389 * We then restart the class main, and also the class late_start.
1390 * At the moment, I've only put a few things in late_start that I know
1391 * are not needed to bring up the framework, and that also cause problems
1392 * with unmounting the tmpfs /data, but I hope to add add more services
1393 * to the late_start class as we optimize this to decrease the delay
1394 * till the user is asked for the password to the filesystem.
1395 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001396
Paul Lawrencef4faa572014-01-29 13:31:03 -08001397 /* The init files are setup to stop the class main when vold.decrypt is
1398 * set to trigger_reset_main.
1399 */
1400 property_set("vold.decrypt", "trigger_reset_main");
1401 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001402
Paul Lawrencef4faa572014-01-29 13:31:03 -08001403 /* Ugh, shutting down the framework is not synchronous, so until it
1404 * can be fixed, this horrible hack will wait a moment for it all to
1405 * shut down before proceeding. Without it, some devices cannot
1406 * restart the graphics services.
1407 */
1408 sleep(2);
1409 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001410
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001411 /* Now that the framework is shutdown, we should be able to umount()
1412 * the tmpfs filesystem, and mount the real one.
1413 */
1414
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001415 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1416 if (strlen(crypto_blkdev) == 0) {
1417 SLOGE("fs_crypto_blkdev not set\n");
1418 return -1;
1419 }
1420
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001421 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001422 /* If ro.crypto.readonly is set to 1, mount the decrypted
1423 * filesystem readonly. This is used when /data is mounted by
1424 * recovery mode.
1425 */
1426 char ro_prop[PROPERTY_VALUE_MAX];
1427 property_get("ro.crypto.readonly", ro_prop, "");
1428 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1429 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1430 rec->flags |= MS_RDONLY;
1431 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001432
Ken Sumralle5032c42012-04-01 23:58:44 -07001433 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001434 int retries = RETRY_MOUNT_ATTEMPTS;
1435 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001436
1437 /*
1438 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1439 * partitions in the fsck domain.
1440 */
1441 if (setexeccon(secontextFsck())){
1442 SLOGE("Failed to setexeccon");
1443 return -1;
1444 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001445 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1446 crypto_blkdev, 0))
1447 != 0) {
1448 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1449 /* TODO: invoke something similar to
1450 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1451 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1452 SLOGI("Failed to mount %s because it is busy - waiting",
1453 crypto_blkdev);
1454 if (--retries) {
1455 sleep(RETRY_MOUNT_DELAY_SECONDS);
1456 } else {
1457 /* Let's hope that a reboot clears away whatever is keeping
1458 the mount busy */
1459 cryptfs_reboot(reboot);
1460 }
1461 } else {
1462 SLOGE("Failed to mount decrypted data");
1463 cryptfs_set_corrupt();
1464 cryptfs_trigger_restart_min_framework();
1465 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001466 if (setexeccon(NULL)) {
1467 SLOGE("Failed to setexeccon");
1468 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001469 return -1;
1470 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001471 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001472 if (setexeccon(NULL)) {
1473 SLOGE("Failed to setexeccon");
1474 return -1;
1475 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001476
Ken Sumralle5032c42012-04-01 23:58:44 -07001477 /* Create necessary paths on /data */
1478 if (prep_data_fs()) {
1479 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001480 }
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001481 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001482
1483 /* startup service classes main and late_start */
1484 property_set("vold.decrypt", "trigger_restart_framework");
1485 SLOGD("Just triggered restart_framework\n");
1486
1487 /* Give it a few moments to get started */
1488 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001489 }
1490
Ken Sumrall0cc16632011-01-18 20:32:26 -08001491 if (rc == 0) {
1492 restart_successful = 1;
1493 }
1494
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001495 return rc;
1496}
1497
Paul Lawrencef4faa572014-01-29 13:31:03 -08001498int cryptfs_restart(void)
1499{
Paul Lawrence05335c32015-03-05 09:46:23 -08001500 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001501 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001502 SLOGE("cryptfs_restart not valid for file encryption:");
1503 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001504 }
1505
Paul Lawrencef4faa572014-01-29 13:31:03 -08001506 /* Call internal implementation forcing a restart of main service group */
1507 return cryptfs_restart_internal(1);
1508}
1509
Wei Wang4375f1b2017-02-24 17:43:01 -08001510static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001511{
1512 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001513 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001514 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001515
1516 property_get("ro.crypto.state", encrypted_state, "");
1517 if (strcmp(encrypted_state, "encrypted") ) {
1518 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001519 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001520 }
1521
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001522 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001523 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001524 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001525 }
1526
Ken Sumrall160b4d62013-04-22 12:15:39 -07001527 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001528 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001529
Ken Sumralle1a45852011-12-14 21:24:27 -08001530 /*
1531 * Only report this error if key_loc is a file and it exists.
1532 * If the device was never encrypted, and /data is not mountable for
1533 * some reason, returning 1 should prevent the UI from presenting the
1534 * a "enter password" screen, or worse, a "press button to wipe the
1535 * device" screen.
1536 */
1537 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1538 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001539 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001540 } else {
1541 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001542 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001543 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001544 }
1545
Paul Lawrence74f29f12014-08-28 15:54:10 -07001546 // Test for possible error flags
1547 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1548 SLOGE("Encryption process is partway completed\n");
1549 return CRYPTO_COMPLETE_PARTIAL;
1550 }
1551
1552 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1553 SLOGE("Encryption process was interrupted but cannot continue\n");
1554 return CRYPTO_COMPLETE_INCONSISTENT;
1555 }
1556
1557 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1558 SLOGE("Encryption is successful but data is corrupt\n");
1559 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001560 }
1561
1562 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001563 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001564}
1565
Paul Lawrencef4faa572014-01-29 13:31:03 -08001566static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001567 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001568{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001570 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571 char crypto_blkdev[MAXPATHLEN];
1572 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001573 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001574 unsigned int orig_failed_decrypt_count;
1575 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001576 int use_keymaster = 0;
1577 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001578 unsigned char* intermediate_key = 0;
1579 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001580 int N = 1 << crypt_ftr->N_factor;
1581 int r = 1 << crypt_ftr->r_factor;
1582 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001583
Paul Lawrencef4faa572014-01-29 13:31:03 -08001584 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1585 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001586
Paul Lawrencef4faa572014-01-29 13:31:03 -08001587 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001588 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1589 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001590 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001591 rc = -1;
1592 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001593 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001594 }
1595
Paul Lawrencef4faa572014-01-29 13:31:03 -08001596 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1597
Paul Lawrence74f29f12014-08-28 15:54:10 -07001598 // Create crypto block device - all (non fatal) code paths
1599 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001600 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1601 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001602 SLOGE("Error creating decrypted block device\n");
1603 rc = -1;
1604 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001605 }
1606
Paul Lawrence74f29f12014-08-28 15:54:10 -07001607 /* Work out if the problem is the password or the data */
1608 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1609 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001610
Paul Lawrence74f29f12014-08-28 15:54:10 -07001611 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1612 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1613 N, r, p, scrypted_intermediate_key,
1614 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001615
Paul Lawrence74f29f12014-08-28 15:54:10 -07001616 // Does the key match the crypto footer?
1617 if (rc == 0 && memcmp(scrypted_intermediate_key,
1618 crypt_ftr->scrypted_intermediate_key,
1619 sizeof(scrypted_intermediate_key)) == 0) {
1620 SLOGI("Password matches");
1621 rc = 0;
1622 } else {
1623 /* Try mounting the file system anyway, just in case the problem's with
1624 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001625 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1626 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001627 mkdir(tmp_mount_point, 0755);
1628 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1629 SLOGE("Error temp mounting decrypted block device\n");
1630 delete_crypto_blk_dev(label);
1631
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001632 rc = ++crypt_ftr->failed_decrypt_count;
1633 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001634 } else {
1635 /* Success! */
1636 SLOGI("Password did not match but decrypted drive mounted - continue");
1637 umount(tmp_mount_point);
1638 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001639 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001640 }
1641
1642 if (rc == 0) {
1643 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001644 if (orig_failed_decrypt_count != 0) {
1645 put_crypt_ftr_and_key(crypt_ftr);
1646 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001647
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001648 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001649 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001650 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001651
1652 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001653 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001654 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001655 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001656 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001657 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001658 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001659
Paul Lawrence74f29f12014-08-28 15:54:10 -07001660 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001661 use_keymaster = keymaster_check_compatibility();
1662 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001663 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001664 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1665 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1666 upgrade = 1;
1667 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001668 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001669 upgrade = 1;
1670 }
1671
1672 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001673 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1674 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001675 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001676 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001677 }
1678 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001679
1680 // Do not fail even if upgrade failed - machine is bootable
1681 // Note that if this code is ever hit, there is a *serious* problem
1682 // since KDFs should never fail. You *must* fix the kdf before
1683 // proceeding!
1684 if (rc) {
1685 SLOGW("Upgrade failed with error %d,"
1686 " but continuing with previous state",
1687 rc);
1688 rc = 0;
1689 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001690 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001691 }
1692
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001693 errout:
1694 if (intermediate_key) {
1695 memset(intermediate_key, 0, intermediate_key_size);
1696 free(intermediate_key);
1697 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001698 return rc;
1699}
1700
Ken Sumrall29d8da82011-05-18 17:20:07 -07001701/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001702 * Called by vold when it's asked to mount an encrypted external
1703 * storage volume. The incoming partition has no crypto header/footer,
1704 * as any metadata is been stored in a separate, small partition.
1705 *
1706 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001707 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001708int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1709 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001710 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001711 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001712 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001713 return -1;
1714 }
1715
1716 unsigned long nr_sec = 0;
1717 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001718 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001719
Ken Sumrall29d8da82011-05-18 17:20:07 -07001720 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001721 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001722 return -1;
1723 }
1724
Jeff Sharkey9c484982015-03-31 10:35:33 -07001725 struct crypt_mnt_ftr ext_crypt_ftr;
1726 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1727 ext_crypt_ftr.fs_size = nr_sec;
1728 ext_crypt_ftr.keysize = keysize;
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001729 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
1730 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001731
Jeff Sharkey9c484982015-03-31 10:35:33 -07001732 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1733 out_crypto_blkdev, label);
1734}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001735
Jeff Sharkey9c484982015-03-31 10:35:33 -07001736/*
1737 * Called by vold when it's asked to unmount an encrypted external
1738 * storage volume.
1739 */
1740int cryptfs_revert_ext_volume(const char* label) {
1741 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001742}
1743
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001744int cryptfs_crypto_complete(void)
1745{
1746 return do_crypto_complete("/data");
1747}
1748
Paul Lawrencef4faa572014-01-29 13:31:03 -08001749int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1750{
1751 char encrypted_state[PROPERTY_VALUE_MAX];
1752 property_get("ro.crypto.state", encrypted_state, "");
1753 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1754 SLOGE("encrypted fs already validated or not running with encryption,"
1755 " aborting");
1756 return -1;
1757 }
1758
1759 if (get_crypt_ftr_and_key(crypt_ftr)) {
1760 SLOGE("Error getting crypt footer and key");
1761 return -1;
1762 }
1763
1764 return 0;
1765}
1766
Wei Wang4375f1b2017-02-24 17:43:01 -08001767int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001768{
Paul Lawrence05335c32015-03-05 09:46:23 -08001769 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001770 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001771 SLOGE("cryptfs_check_passwd not valid for file encryption");
1772 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001773 }
1774
Paul Lawrencef4faa572014-01-29 13:31:03 -08001775 struct crypt_mnt_ftr crypt_ftr;
1776 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001777
Paul Lawrencef4faa572014-01-29 13:31:03 -08001778 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001779 if (rc) {
1780 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001781 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001782 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001783
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001784 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001785 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1786 if (rc) {
1787 SLOGE("Password did not match");
1788 return rc;
1789 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001790
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001791 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1792 // Here we have a default actual password but a real password
1793 // we must test against the scrypted value
1794 // First, we must delete the crypto block device that
1795 // test_mount_encrypted_fs leaves behind as a side effect
1796 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1797 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1798 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1799 if (rc) {
1800 SLOGE("Default password did not match on reboot encryption");
1801 return rc;
1802 }
1803
1804 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1805 put_crypt_ftr_and_key(&crypt_ftr);
1806 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1807 if (rc) {
1808 SLOGE("Could not change password on reboot encryption");
1809 return rc;
1810 }
1811 }
1812
1813 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001814 cryptfs_clear_password();
1815 password = strdup(passwd);
1816 struct timespec now;
1817 clock_gettime(CLOCK_BOOTTIME, &now);
1818 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001819 }
1820
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001821 return rc;
1822}
1823
Ken Sumrall3ad90722011-10-04 20:38:29 -07001824int cryptfs_verify_passwd(char *passwd)
1825{
1826 struct crypt_mnt_ftr crypt_ftr;
1827 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001828 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001829 char encrypted_state[PROPERTY_VALUE_MAX];
1830 int rc;
1831
1832 property_get("ro.crypto.state", encrypted_state, "");
1833 if (strcmp(encrypted_state, "encrypted") ) {
1834 SLOGE("device not encrypted, aborting");
1835 return -2;
1836 }
1837
1838 if (!master_key_saved) {
1839 SLOGE("encrypted fs not yet mounted, aborting");
1840 return -1;
1841 }
1842
1843 if (!saved_mount_point) {
1844 SLOGE("encrypted fs failed to save mount point, aborting");
1845 return -1;
1846 }
1847
Ken Sumrall160b4d62013-04-22 12:15:39 -07001848 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001849 SLOGE("Error getting crypt footer and key\n");
1850 return -1;
1851 }
1852
1853 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1854 /* If the device has no password, then just say the password is valid */
1855 rc = 0;
1856 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001857 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001858 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1859 /* They match, the password is correct */
1860 rc = 0;
1861 } else {
1862 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1863 sleep(1);
1864 rc = 1;
1865 }
1866 }
1867
1868 return rc;
1869}
1870
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001871/* Initialize a crypt_mnt_ftr structure. The keysize is
1872 * defaulted to 16 bytes, and the filesystem size to 0.
1873 * Presumably, at a minimum, the caller will update the
1874 * filesystem size and crypto_type_name after calling this function.
1875 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001876static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001877{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001878 off64_t off;
1879
1880 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001881 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001882 ftr->major_version = CURRENT_MAJOR_VERSION;
1883 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001884 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001885 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001886
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001887 switch (keymaster_check_compatibility()) {
1888 case 1:
1889 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1890 break;
1891
1892 case 0:
1893 ftr->kdf_type = KDF_SCRYPT;
1894 break;
1895
1896 default:
1897 SLOGE("keymaster_check_compatibility failed");
1898 return -1;
1899 }
1900
Kenny Rootc4c70f12013-06-14 12:11:38 -07001901 get_device_scrypt_params(ftr);
1902
Ken Sumrall160b4d62013-04-22 12:15:39 -07001903 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1904 if (get_crypt_ftr_info(NULL, &off) == 0) {
1905 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1906 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1907 ftr->persist_data_size;
1908 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001909
1910 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001911}
1912
Ken Sumrall29d8da82011-05-18 17:20:07 -07001913static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001914{
Ken Sumralle550f782013-08-20 13:48:23 -07001915 const char *args[10];
1916 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1917 int num_args;
1918 int status;
1919 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001920 int rc = -1;
1921
Ken Sumrall29d8da82011-05-18 17:20:07 -07001922 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001923#ifdef TARGET_USES_MKE2FS
1924 args[0] = "/system/bin/mke2fs";
1925 args[1] = "-M";
1926 args[2] = "/data";
1927 args[3] = "-b";
1928 args[4] = "4096";
1929 args[5] = "-t";
1930 args[6] = "ext4";
1931 args[7] = crypto_blkdev;
1932 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1933 args[8] = size_str;
1934 num_args = 9;
1935#else
Ken Sumralle550f782013-08-20 13:48:23 -07001936 args[0] = "/system/bin/make_ext4fs";
1937 args[1] = "-a";
1938 args[2] = "/data";
1939 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07001940 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07001941 args[4] = size_str;
1942 args[5] = crypto_blkdev;
1943 num_args = 6;
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08001944#endif
Ken Sumralle550f782013-08-20 13:48:23 -07001945 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1946 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001947 } else if (type == F2FS_FS) {
1948 args[0] = "/system/bin/mkfs.f2fs";
1949 args[1] = "-t";
1950 args[2] = "-d1";
1951 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001952 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07001953 args[4] = size_str;
1954 num_args = 5;
1955 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
1956 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001957 } else {
1958 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1959 return -1;
1960 }
1961
Ken Sumralle550f782013-08-20 13:48:23 -07001962 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1963
1964 if (tmp != 0) {
1965 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001966 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001967 if (WIFEXITED(status)) {
1968 if (WEXITSTATUS(status)) {
1969 SLOGE("Error creating filesystem on %s, exit status %d ",
1970 crypto_blkdev, WEXITSTATUS(status));
1971 } else {
1972 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1973 rc = 0;
1974 }
1975 } else {
1976 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1977 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001978 }
1979
1980 return rc;
1981}
1982
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001983#define CRYPTO_ENABLE_WIPE 1
1984#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001985
1986#define FRAMEWORK_BOOT_WAIT 60
1987
Paul Lawrence87999172014-02-20 12:21:31 -08001988static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1989{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001990 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001991 if (fd == -1) {
1992 SLOGE("Error opening file %s", filename);
1993 return -1;
1994 }
1995
1996 char block[CRYPT_INPLACE_BUFSIZE];
1997 memset(block, 0, sizeof(block));
1998 if (unix_read(fd, block, sizeof(block)) < 0) {
1999 SLOGE("Error reading file %s", filename);
2000 close(fd);
2001 return -1;
2002 }
2003
2004 close(fd);
2005
2006 SHA256_CTX c;
2007 SHA256_Init(&c);
2008 SHA256_Update(&c, block, sizeof(block));
2009 SHA256_Final(buf, &c);
2010
2011 return 0;
2012}
2013
JP Abgrall62c7af32014-06-16 13:01:23 -07002014static int get_fs_type(struct fstab_rec *rec)
2015{
2016 if (!strcmp(rec->fs_type, "ext4")) {
2017 return EXT4_FS;
2018 } else if (!strcmp(rec->fs_type, "f2fs")) {
2019 return F2FS_FS;
2020 } else {
2021 return -1;
2022 }
2023}
2024
Paul Lawrence87999172014-02-20 12:21:31 -08002025static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2026 char *crypto_blkdev, char *real_blkdev,
2027 int previously_encrypted_upto)
2028{
2029 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002030 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002031
Paul Lawrence73d7a022014-06-09 14:10:09 -07002032 if (!is_battery_ok_to_start()) {
2033 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002034 return 0;
2035 }
2036
2037 /* The size of the userdata partition, and add in the vold volumes below */
2038 tot_encryption_size = crypt_ftr->fs_size;
2039
2040 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002041 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2042 int fs_type = get_fs_type(rec);
2043 if (fs_type < 0) {
2044 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2045 return -1;
2046 }
2047 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002048 } else if (how == CRYPTO_ENABLE_INPLACE) {
2049 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2050 crypt_ftr->fs_size, &cur_encryption_done,
2051 tot_encryption_size,
2052 previously_encrypted_upto);
2053
JP Abgrall7fc1de82014-10-10 18:43:41 -07002054 if (rc == ENABLE_INPLACE_ERR_DEV) {
2055 /* Hack for b/17898962 */
2056 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2057 cryptfs_reboot(reboot);
2058 }
2059
Paul Lawrence73d7a022014-06-09 14:10:09 -07002060 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002061 crypt_ftr->encrypted_upto = cur_encryption_done;
2062 }
2063
Paul Lawrence73d7a022014-06-09 14:10:09 -07002064 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002065 /* The inplace routine never actually sets the progress to 100% due
2066 * to the round down nature of integer division, so set it here */
2067 property_set("vold.encrypt_progress", "100");
2068 }
2069 } else {
2070 /* Shouldn't happen */
2071 SLOGE("cryptfs_enable: internal error, unknown option\n");
2072 rc = -1;
2073 }
2074
2075 return rc;
2076}
2077
Wei Wang4375f1b2017-02-24 17:43:01 -08002078int cryptfs_enable_internal(char *howarg, int crypt_type, const char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002079 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002080{
2081 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002082 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002083 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002084 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002085 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002086 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002087 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002088 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002089 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002090 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002091 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002092 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002093 bool onlyCreateHeader = false;
2094 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002095
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002096 if (!strcmp(howarg, "wipe")) {
2097 how = CRYPTO_ENABLE_WIPE;
2098 } else if (! strcmp(howarg, "inplace")) {
2099 how = CRYPTO_ENABLE_INPLACE;
2100 } else {
2101 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002102 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002103 }
2104
Paul Lawrence87999172014-02-20 12:21:31 -08002105 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002106 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2107 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2108 /* An encryption was underway and was interrupted */
2109 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2110 crypt_ftr.encrypted_upto = 0;
2111 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002112
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002113 /* At this point, we are in an inconsistent state. Until we successfully
2114 complete encryption, a reboot will leave us broken. So mark the
2115 encryption failed in case that happens.
2116 On successfully completing encryption, remove this flag */
2117 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002118
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002119 put_crypt_ftr_and_key(&crypt_ftr);
2120 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2121 if (!check_ftr_sha(&crypt_ftr)) {
2122 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2123 put_crypt_ftr_and_key(&crypt_ftr);
2124 goto error_unencrypted;
2125 }
2126
2127 /* Doing a reboot-encryption*/
2128 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2129 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2130 rebootEncryption = true;
2131 }
Paul Lawrence87999172014-02-20 12:21:31 -08002132 }
2133
2134 property_get("ro.crypto.state", encrypted_state, "");
2135 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2136 SLOGE("Device is already running encrypted, aborting");
2137 goto error_unencrypted;
2138 }
2139
2140 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2141 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002142 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002143
Ken Sumrall3ed82362011-01-28 23:31:16 -08002144 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002145 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002146 if (fd == -1) {
2147 SLOGE("Cannot open block device %s\n", real_blkdev);
2148 goto error_unencrypted;
2149 }
2150 unsigned long nr_sec;
2151 get_blkdev_size(fd, &nr_sec);
2152 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002153 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2154 goto error_unencrypted;
2155 }
2156 close(fd);
2157
2158 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002159 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002160 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002161 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002162 if (fs_size_sec == 0)
2163 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2164
Paul Lawrence87999172014-02-20 12:21:31 -08002165 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002166
2167 if (fs_size_sec > max_fs_size_sec) {
2168 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2169 goto error_unencrypted;
2170 }
2171 }
2172
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002173 /* Get a wakelock as this may take a while, and we don't want the
2174 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2175 * wants to keep the screen on, it can grab a full wakelock.
2176 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002177 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002178 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2179
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002180 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002181 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002182 */
2183 property_set("vold.decrypt", "trigger_shutdown_framework");
2184 SLOGD("Just asked init to shut down class main\n");
2185
Jeff Sharkey9c484982015-03-31 10:35:33 -07002186 /* Ask vold to unmount all devices that it manages */
2187 if (vold_unmountAll()) {
2188 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002189 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002190
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002191 /* no_ui means we are being called from init, not settings.
2192 Now we always reboot from settings, so !no_ui means reboot
2193 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002194 if (!no_ui) {
2195 /* Try fallback, which is to reboot and try there */
2196 onlyCreateHeader = true;
2197 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2198 if (breadcrumb == 0) {
2199 SLOGE("Failed to create breadcrumb file");
2200 goto error_shutting_down;
2201 }
2202 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002203 }
2204
2205 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002206 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002207 /* Now that /data is unmounted, we need to mount a tmpfs
2208 * /data, set a property saying we're doing inplace encryption,
2209 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002210 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002211 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002212 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002213 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002214 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002215 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002216
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002217 /* restart the framework. */
2218 /* Create necessary paths on /data */
2219 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002220 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002221 }
2222
Ken Sumrall92736ef2012-10-17 20:57:14 -07002223 /* Ugh, shutting down the framework is not synchronous, so until it
2224 * can be fixed, this horrible hack will wait a moment for it all to
2225 * shut down before proceeding. Without it, some devices cannot
2226 * restart the graphics services.
2227 */
2228 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002229 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002230
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002231 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002232 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002233 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002234 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2235 goto error_shutting_down;
2236 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002237
Paul Lawrence87999172014-02-20 12:21:31 -08002238 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2239 crypt_ftr.fs_size = nr_sec
2240 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2241 } else {
2242 crypt_ftr.fs_size = nr_sec;
2243 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002244 /* At this point, we are in an inconsistent state. Until we successfully
2245 complete encryption, a reboot will leave us broken. So mark the
2246 encryption failed in case that happens.
2247 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002248 if (onlyCreateHeader) {
2249 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2250 } else {
2251 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2252 }
Paul Lawrence87999172014-02-20 12:21:31 -08002253 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002254 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002255
Paul Lawrence87999172014-02-20 12:21:31 -08002256 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002257 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2258 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002259 SLOGE("Cannot create encrypted master key\n");
2260 goto error_shutting_down;
2261 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002262
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002263 /* Replace scrypted intermediate key if we are preparing for a reboot */
2264 if (onlyCreateHeader) {
2265 unsigned char fake_master_key[KEY_LEN_BYTES];
2266 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2267 memset(fake_master_key, 0, sizeof(fake_master_key));
2268 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2269 encrypted_fake_master_key, &crypt_ftr);
2270 }
2271
Paul Lawrence87999172014-02-20 12:21:31 -08002272 /* Write the key to the end of the partition */
2273 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002274
Paul Lawrence87999172014-02-20 12:21:31 -08002275 /* If any persistent data has been remembered, save it.
2276 * If none, create a valid empty table and save that.
2277 */
2278 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002279 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002280 if (pdata) {
2281 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2282 persist_data = pdata;
2283 }
2284 }
2285 if (persist_data) {
2286 save_persistent_data();
2287 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002288 }
2289
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002290 if (onlyCreateHeader) {
2291 sleep(2);
2292 cryptfs_reboot(reboot);
2293 }
2294
2295 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002296 /* startup service classes main and late_start */
2297 property_set("vold.decrypt", "trigger_restart_min_framework");
2298 SLOGD("Just triggered restart_min_framework\n");
2299
2300 /* OK, the framework is restarted and will soon be showing a
2301 * progress bar. Time to setup an encrypted mapping, and
2302 * either write a new filesystem, or encrypt in place updating
2303 * the progress bar as we work.
2304 */
2305 }
2306
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002307 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002308 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002309 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002310
Paul Lawrence87999172014-02-20 12:21:31 -08002311 /* If we are continuing, check checksums match */
2312 rc = 0;
2313 if (previously_encrypted_upto) {
2314 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2315 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002316
Paul Lawrence87999172014-02-20 12:21:31 -08002317 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2318 sizeof(hash_first_block)) != 0) {
2319 SLOGE("Checksums do not match - trigger wipe");
2320 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002321 }
2322 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002323
Paul Lawrence87999172014-02-20 12:21:31 -08002324 if (!rc) {
2325 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2326 crypto_blkdev, real_blkdev,
2327 previously_encrypted_upto);
2328 }
2329
2330 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002331 if (!rc && how == CRYPTO_ENABLE_INPLACE
2332 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002333 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2334 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002335 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002336 SLOGE("Error calculating checksum for continuing encryption");
2337 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002338 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002339 }
2340
2341 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002342 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002343
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002344 if (! rc) {
2345 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002346 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002347
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002348 if (how == CRYPTO_ENABLE_INPLACE
2349 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002350 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2351 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002352 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002353 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002354
Paul Lawrence6bfed202014-07-28 12:47:22 -07002355 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002356
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002357 if (how == CRYPTO_ENABLE_WIPE
2358 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002359 char value[PROPERTY_VALUE_MAX];
2360 property_get("ro.crypto.state", value, "");
2361 if (!strcmp(value, "")) {
2362 /* default encryption - continue first boot sequence */
2363 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08002364 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002365 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002366 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2367 // Bring up cryptkeeper that will check the password and set it
2368 property_set("vold.decrypt", "trigger_shutdown_framework");
2369 sleep(2);
2370 property_set("vold.encrypt_progress", "");
2371 cryptfs_trigger_restart_min_framework();
2372 } else {
2373 cryptfs_check_passwd(DEFAULT_PASSWORD);
2374 cryptfs_restart_internal(1);
2375 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002376 return 0;
2377 } else {
2378 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002379 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002380 }
Paul Lawrence87999172014-02-20 12:21:31 -08002381 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002382 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08002383 cryptfs_reboot(shutdown);
2384 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002385 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002386 char value[PROPERTY_VALUE_MAX];
2387
Ken Sumrall319369a2012-06-27 16:30:18 -07002388 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002389 if (!strcmp(value, "1")) {
2390 /* wipe data if encryption failed */
2391 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002392 std::string err;
2393 const std::vector<std::string> options = {
2394 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2395 };
2396 if (!write_bootloader_message(options, &err)) {
2397 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002398 }
Paul Lawrence87999172014-02-20 12:21:31 -08002399 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002400 } else {
2401 /* set property to trigger dialog */
2402 property_set("vold.encrypt_progress", "error_partially_encrypted");
2403 release_wake_lock(lockid);
2404 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002405 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002406 }
2407
Ken Sumrall3ed82362011-01-28 23:31:16 -08002408 /* hrm, the encrypt step claims success, but the reboot failed.
2409 * This should not happen.
2410 * Set the property and return. Hope the framework can deal with it.
2411 */
2412 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002413 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002414 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002415
2416error_unencrypted:
2417 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002418 if (lockid[0]) {
2419 release_wake_lock(lockid);
2420 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002421 return -1;
2422
2423error_shutting_down:
2424 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2425 * but the framework is stopped and not restarted to show the error, so it's up to
2426 * vold to restart the system.
2427 */
2428 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08002429 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002430
2431 /* shouldn't get here */
2432 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002433 if (lockid[0]) {
2434 release_wake_lock(lockid);
2435 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002436 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002437}
2438
Paul Lawrence569649f2015-09-09 12:13:00 -07002439int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002440{
Paul Lawrence569649f2015-09-09 12:13:00 -07002441 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002442}
2443
Paul Lawrence569649f2015-09-09 12:13:00 -07002444int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08002445{
2446 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07002447 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002448}
2449
2450int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002451{
Paul Crowley38132a12016-02-09 09:50:32 +00002452 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002453 SLOGE("cryptfs_changepw not valid for file encryption");
2454 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002455 }
2456
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002457 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002458 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002459
2460 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002461 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002462 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002463 return -1;
2464 }
2465
Paul Lawrencef4faa572014-01-29 13:31:03 -08002466 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2467 SLOGE("Invalid crypt_type %d", crypt_type);
2468 return -1;
2469 }
2470
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002471 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002472 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002473 SLOGE("Error getting crypt footer and key");
2474 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002475 }
2476
Paul Lawrencef4faa572014-01-29 13:31:03 -08002477 crypt_ftr.crypt_type = crypt_type;
2478
JP Abgrall933216c2015-02-11 13:44:32 -08002479 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002480 : newpw,
2481 crypt_ftr.salt,
2482 saved_master_key,
2483 crypt_ftr.master_key,
2484 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002485 if (rc) {
2486 SLOGE("Encrypt master key failed: %d", rc);
2487 return -1;
2488 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002489 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002490 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002491
2492 return 0;
2493}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002494
Rubin Xu85c01f92014-10-13 12:49:54 +01002495static unsigned int persist_get_max_entries(int encrypted) {
2496 struct crypt_mnt_ftr crypt_ftr;
2497 unsigned int dsize;
2498 unsigned int max_persistent_entries;
2499
2500 /* If encrypted, use the values from the crypt_ftr, otherwise
2501 * use the values for the current spec.
2502 */
2503 if (encrypted) {
2504 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2505 return -1;
2506 }
2507 dsize = crypt_ftr.persist_data_size;
2508 } else {
2509 dsize = CRYPT_PERSIST_DATA_SIZE;
2510 }
2511
2512 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2513 sizeof(struct crypt_persist_entry);
2514
2515 return max_persistent_entries;
2516}
2517
2518static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002519{
2520 unsigned int i;
2521
2522 if (persist_data == NULL) {
2523 return -1;
2524 }
2525 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2526 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2527 /* We found it! */
2528 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2529 return 0;
2530 }
2531 }
2532
2533 return -1;
2534}
2535
Rubin Xu85c01f92014-10-13 12:49:54 +01002536static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002537{
2538 unsigned int i;
2539 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002540 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002541
2542 if (persist_data == NULL) {
2543 return -1;
2544 }
2545
Rubin Xu85c01f92014-10-13 12:49:54 +01002546 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002547
2548 num = persist_data->persist_valid_entries;
2549
2550 for (i = 0; i < num; i++) {
2551 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2552 /* We found an existing entry, update it! */
2553 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2554 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2555 return 0;
2556 }
2557 }
2558
2559 /* We didn't find it, add it to the end, if there is room */
2560 if (persist_data->persist_valid_entries < max_persistent_entries) {
2561 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2562 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2563 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2564 persist_data->persist_valid_entries++;
2565 return 0;
2566 }
2567
2568 return -1;
2569}
2570
Rubin Xu85c01f92014-10-13 12:49:54 +01002571/**
2572 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2573 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2574 */
2575static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002576 unsigned int field_len;
2577 unsigned int key_index;
2578 field_len = strlen(field);
2579
2580 if (index == 0) {
2581 // The first key in a multi-entry field is just the filedname itself.
2582 if (!strcmp(key, field)) {
2583 return 1;
2584 }
2585 }
2586 // Match key against "%s_%d" % (field, index)
2587 if (strlen(key) < field_len + 1 + 1) {
2588 // Need at least a '_' and a digit.
2589 return 0;
2590 }
2591 if (strncmp(key, field, field_len)) {
2592 // If the key does not begin with field, it's not a match.
2593 return 0;
2594 }
2595 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
2596 return 0;
2597 }
2598 return key_index >= index;
2599}
2600
2601/*
2602 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2603 * remaining entries starting from index will be deleted.
2604 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2605 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2606 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2607 *
2608 */
2609static int persist_del_keys(const char *fieldname, unsigned index)
2610{
2611 unsigned int i;
2612 unsigned int j;
2613 unsigned int num;
2614
2615 if (persist_data == NULL) {
2616 return PERSIST_DEL_KEY_ERROR_OTHER;
2617 }
2618
2619 num = persist_data->persist_valid_entries;
2620
2621 j = 0; // points to the end of non-deleted entries.
2622 // Filter out to-be-deleted entries in place.
2623 for (i = 0; i < num; i++) {
2624 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2625 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2626 j++;
2627 }
2628 }
2629
2630 if (j < num) {
2631 persist_data->persist_valid_entries = j;
2632 // Zeroise the remaining entries
2633 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2634 return PERSIST_DEL_KEY_OK;
2635 } else {
2636 // Did not find an entry matching the given fieldname
2637 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2638 }
2639}
2640
2641static int persist_count_keys(const char *fieldname)
2642{
2643 unsigned int i;
2644 unsigned int count;
2645
2646 if (persist_data == NULL) {
2647 return -1;
2648 }
2649
2650 count = 0;
2651 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2652 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2653 count++;
2654 }
2655 }
2656
2657 return count;
2658}
2659
Ken Sumrall160b4d62013-04-22 12:15:39 -07002660/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002661int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002662{
Paul Crowley38132a12016-02-09 09:50:32 +00002663 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002664 SLOGE("Cannot get field when file encrypted");
2665 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002666 }
2667
Ken Sumrall160b4d62013-04-22 12:15:39 -07002668 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002669 /* CRYPTO_GETFIELD_OK is success,
2670 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2671 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2672 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002673 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002674 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2675 int i;
2676 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002677
2678 if (persist_data == NULL) {
2679 load_persistent_data();
2680 if (persist_data == NULL) {
2681 SLOGE("Getfield error, cannot load persistent data");
2682 goto out;
2683 }
2684 }
2685
Rubin Xu85c01f92014-10-13 12:49:54 +01002686 // Read value from persistent entries. If the original value is split into multiple entries,
2687 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002688 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002689 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2690 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2691 // value too small
2692 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2693 goto out;
2694 }
2695 rc = CRYPTO_GETFIELD_OK;
2696
2697 for (i = 1; /* break explicitly */; i++) {
2698 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2699 (int) sizeof(temp_field)) {
2700 // If the fieldname is very long, we stop as soon as it begins to overflow the
2701 // maximum field length. At this point we have in fact fully read out the original
2702 // value because cryptfs_setfield would not allow fields with longer names to be
2703 // written in the first place.
2704 break;
2705 }
2706 if (!persist_get_key(temp_field, temp_value)) {
2707 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2708 // value too small.
2709 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2710 goto out;
2711 }
2712 } else {
2713 // Exhaust all entries.
2714 break;
2715 }
2716 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002717 } else {
2718 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002719 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002720 }
2721
2722out:
2723 return rc;
2724}
2725
2726/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002727int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002728{
Paul Crowley38132a12016-02-09 09:50:32 +00002729 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002730 SLOGE("Cannot set field when file encrypted");
2731 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002732 }
2733
Ken Sumrall160b4d62013-04-22 12:15:39 -07002734 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002735 /* 0 is success, negative values are error */
2736 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002737 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002738 unsigned int field_id;
2739 char temp_field[PROPERTY_KEY_MAX];
2740 unsigned int num_entries;
2741 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002742
2743 if (persist_data == NULL) {
2744 load_persistent_data();
2745 if (persist_data == NULL) {
2746 SLOGE("Setfield error, cannot load persistent data");
2747 goto out;
2748 }
2749 }
2750
2751 property_get("ro.crypto.state", encrypted_state, "");
2752 if (!strcmp(encrypted_state, "encrypted") ) {
2753 encrypted = 1;
2754 }
2755
Rubin Xu85c01f92014-10-13 12:49:54 +01002756 // Compute the number of entries required to store value, each entry can store up to
2757 // (PROPERTY_VALUE_MAX - 1) chars
2758 if (strlen(value) == 0) {
2759 // Empty value also needs one entry to store.
2760 num_entries = 1;
2761 } else {
2762 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2763 }
2764
2765 max_keylen = strlen(fieldname);
2766 if (num_entries > 1) {
2767 // Need an extra "_%d" suffix.
2768 max_keylen += 1 + log10(num_entries);
2769 }
2770 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2771 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002772 goto out;
2773 }
2774
Rubin Xu85c01f92014-10-13 12:49:54 +01002775 // Make sure we have enough space to write the new value
2776 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2777 persist_get_max_entries(encrypted)) {
2778 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2779 goto out;
2780 }
2781
2782 // Now that we know persist_data has enough space for value, let's delete the old field first
2783 // to make up space.
2784 persist_del_keys(fieldname, 0);
2785
2786 if (persist_set_key(fieldname, value, encrypted)) {
2787 // fail to set key, should not happen as we have already checked the available space
2788 SLOGE("persist_set_key() error during setfield()");
2789 goto out;
2790 }
2791
2792 for (field_id = 1; field_id < num_entries; field_id++) {
2793 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
2794
2795 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2796 // fail to set key, should not happen as we have already checked the available space.
2797 SLOGE("persist_set_key() error during setfield()");
2798 goto out;
2799 }
2800 }
2801
Ken Sumrall160b4d62013-04-22 12:15:39 -07002802 /* If we are running encrypted, save the persistent data now */
2803 if (encrypted) {
2804 if (save_persistent_data()) {
2805 SLOGE("Setfield error, cannot save persistent data");
2806 goto out;
2807 }
2808 }
2809
Rubin Xu85c01f92014-10-13 12:49:54 +01002810 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002811
2812out:
2813 return rc;
2814}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002815
2816/* Checks userdata. Attempt to mount the volume if default-
2817 * encrypted.
2818 * On success trigger next init phase and return 0.
2819 * Currently do not handle failure - see TODO below.
2820 */
2821int cryptfs_mount_default_encrypted(void)
2822{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002823 int crypt_type = cryptfs_get_password_type();
2824 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2825 SLOGE("Bad crypt type - error");
2826 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2827 SLOGD("Password is not default - "
2828 "starting min framework to prompt");
2829 property_set("vold.decrypt", "trigger_restart_min_framework");
2830 return 0;
2831 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2832 SLOGD("Password is default - restarting filesystem");
2833 cryptfs_restart_internal(0);
2834 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002835 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002836 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002837 }
2838
Paul Lawrence6bfed202014-07-28 12:47:22 -07002839 /** Corrupt. Allow us to boot into framework, which will detect bad
2840 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002841 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002842 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002843 return 0;
2844}
2845
2846/* Returns type of the password, default, pattern, pin or password.
2847 */
2848int cryptfs_get_password_type(void)
2849{
Paul Crowley38132a12016-02-09 09:50:32 +00002850 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002851 SLOGE("cryptfs_get_password_type not valid for file encryption");
2852 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002853 }
2854
Paul Lawrencef4faa572014-01-29 13:31:03 -08002855 struct crypt_mnt_ftr crypt_ftr;
2856
2857 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2858 SLOGE("Error getting crypt footer and key\n");
2859 return -1;
2860 }
2861
Paul Lawrence6bfed202014-07-28 12:47:22 -07002862 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2863 return -1;
2864 }
2865
Paul Lawrencef4faa572014-01-29 13:31:03 -08002866 return crypt_ftr.crypt_type;
2867}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002868
Paul Lawrence05335c32015-03-05 09:46:23 -08002869const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002870{
Paul Crowley38132a12016-02-09 09:50:32 +00002871 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002872 SLOGE("cryptfs_get_password not valid for file encryption");
2873 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002874 }
2875
Paul Lawrence399317e2014-03-10 13:20:50 -07002876 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002877 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002878 if (now.tv_sec < password_expiry_time) {
2879 return password;
2880 } else {
2881 cryptfs_clear_password();
2882 return 0;
2883 }
2884}
2885
2886void cryptfs_clear_password()
2887{
2888 if (password) {
2889 size_t len = strlen(password);
2890 memset(password, 0, len);
2891 free(password);
2892 password = 0;
2893 password_expiry_time = 0;
2894 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002895}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002896
Paul Lawrence0c247462015-10-29 10:30:57 -07002897int cryptfs_isConvertibleToFBE()
2898{
2899 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2900 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2901}
2902
Paul Lawrence731a7a22015-04-28 22:14:15 +00002903int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
2904{
2905 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
2906 SLOGE("Failed to initialize crypt_ftr");
2907 return -1;
2908 }
2909
2910 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
2911 crypt_ftr->salt, crypt_ftr)) {
2912 SLOGE("Cannot create encrypted master key\n");
2913 return -1;
2914 }
2915
2916 //crypt_ftr->keysize = key_length / 8;
2917 return 0;
2918}
2919
2920int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
2921 unsigned char* master_key)
2922{
2923 int rc;
2924
Paul Lawrence731a7a22015-04-28 22:14:15 +00002925 unsigned char* intermediate_key = 0;
2926 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002927
2928 if (password == 0 || *password == 0) {
2929 password = DEFAULT_PASSWORD;
2930 }
2931
Paul Lawrence731a7a22015-04-28 22:14:15 +00002932 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
2933 &intermediate_key_size);
2934
Paul Lawrence300dae72016-03-11 11:02:52 -08002935 if (rc) {
2936 SLOGE("Can't calculate intermediate key");
2937 return rc;
2938 }
2939
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002940 int N = 1 << ftr->N_factor;
2941 int r = 1 << ftr->r_factor;
2942 int p = 1 << ftr->p_factor;
2943
2944 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
2945
2946 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
2947 ftr->salt, sizeof(ftr->salt), N, r, p,
2948 scrypted_intermediate_key,
2949 sizeof(scrypted_intermediate_key));
2950
2951 free(intermediate_key);
2952
2953 if (rc) {
Paul Lawrence300dae72016-03-11 11:02:52 -08002954 SLOGE("Can't scrypt intermediate key");
Paul Lawrencec78c71b2015-04-14 15:26:29 -07002955 return rc;
2956 }
2957
2958 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
2959 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00002960}
2961
2962int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
2963 const unsigned char* master_key)
2964{
2965 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
2966 ftr);
2967}
Paul Lawrence6e410592016-05-24 14:20:38 -07002968
Eric Biggersb45caaf2017-02-02 14:52:12 -08002969void cryptfs_get_file_encryption_modes(const char **contents_mode_ret,
2970 const char **filenames_mode_ret)
Paul Lawrence6e410592016-05-24 14:20:38 -07002971{
2972 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
Eric Biggersb45caaf2017-02-02 14:52:12 -08002973 fs_mgr_get_file_encryption_modes(rec, contents_mode_ret, filenames_mode_ret);
Paul Lawrence6e410592016-05-24 14:20:38 -07002974}