blob: bd5807fd1ea4e2f29390fb038a9471a6b597eac3 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080041#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080046#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080047#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080048#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080049#define LOG_TAG "Cryptfs"
50#include "cutils/log.h"
51#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070052#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080053#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070054#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070055#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070056#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070057#include "crypto_scrypt.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000058#include "Ext4Crypt.h"
59#include "ext4_crypt_init_extensions.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080060#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000061#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080062#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080063#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080064
Shawn Willden8af33352015-02-24 09:51:34 -070065#include <hardware/keymaster0.h>
Shawn Willdenda6e8992015-06-03 09:40:45 -060066#include <hardware/keymaster1.h>
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070067
Mark Salyzyn3e971272014-01-21 13:27:04 -080068#define UNUSED __attribute__((unused))
69
Mark Salyzyn5eecc442014-02-12 14:16:14 -080070#define UNUSED __attribute__((unused))
71
Ajay Dudani87701e22014-09-17 21:02:52 -070072#ifdef CONFIG_HW_DISK_ENCRYPTION
73#include "cryptfs_hw.h"
74#endif
75
Ken Sumrall8f869aa2010-12-03 03:47:09 -080076#define DM_CRYPT_BUF_SIZE 4096
77
Jason parks70a4b3f2011-01-28 10:10:47 -060078#define HASH_COUNT 2000
79#define KEY_LEN_BYTES 16
80#define IV_LEN_BYTES 16
81
Ken Sumrall29d8da82011-05-18 17:20:07 -070082#define KEY_IN_FOOTER "footer"
83
Paul Lawrence3bd36d52015-06-09 13:37:44 -070084#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080085
Paul Lawrence3d99eba2015-11-20 07:07:19 -080086#define CRYPTO_BLOCK_DEVICE "userdata"
87
88#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
89
Ken Sumrall29d8da82011-05-18 17:20:07 -070090#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070091#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070092
Ken Sumralle919efe2012-09-29 17:07:41 -070093#define TABLE_LOAD_RETRIES 10
94
Shawn Willden47ba10d2014-09-03 17:07:06 -060095#define RSA_KEY_SIZE 2048
96#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
97#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060098#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070099
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700100#define RETRY_MOUNT_ATTEMPTS 10
101#define RETRY_MOUNT_DELAY_SECONDS 1
102
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800103char *me = "cryptfs";
104
Jason parks70a4b3f2011-01-28 10:10:47 -0600105static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700106static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600107static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700108static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800109
Shawn Willdenda6e8992015-06-03 09:40:45 -0600110static int keymaster_init(keymaster0_device_t **keymaster0_dev,
111 keymaster1_device_t **keymaster1_dev)
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700112{
113 int rc;
114
115 const hw_module_t* mod;
116 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
117 if (rc) {
118 ALOGE("could not find any keystore module");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600119 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700120 }
121
Shawn Willdenda6e8992015-06-03 09:40:45 -0600122 SLOGI("keymaster module name is %s", mod->name);
123 SLOGI("keymaster version is %d", mod->module_api_version);
124
125 *keymaster0_dev = NULL;
126 *keymaster1_dev = NULL;
127 if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
128 SLOGI("Found keymaster1 module, using keymaster1 API.");
129 rc = keymaster1_open(mod, keymaster1_dev);
130 } else {
131 SLOGI("Found keymaster0 module, using keymaster0 API.");
132 rc = keymaster0_open(mod, keymaster0_dev);
133 }
134
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700135 if (rc) {
136 ALOGE("could not open keymaster device in %s (%s)",
Shawn Willdenda6e8992015-06-03 09:40:45 -0600137 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
138 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700139 }
140
141 return 0;
142
Shawn Willdenda6e8992015-06-03 09:40:45 -0600143err:
144 *keymaster0_dev = NULL;
145 *keymaster1_dev = NULL;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700146 return rc;
147}
148
149/* Should we use keymaster? */
150static int keymaster_check_compatibility()
151{
Shawn Willdenda6e8992015-06-03 09:40:45 -0600152 keymaster0_device_t *keymaster0_dev = 0;
153 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700154 int rc = 0;
155
Shawn Willdenda6e8992015-06-03 09:40:45 -0600156 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700157 SLOGE("Failed to init keymaster");
158 rc = -1;
159 goto out;
160 }
161
Shawn Willdenda6e8992015-06-03 09:40:45 -0600162 if (keymaster1_dev) {
163 rc = 1;
164 goto out;
165 }
Paul Lawrence8c008392014-05-06 14:02:48 -0700166
Shawn Willdenda6e8992015-06-03 09:40:45 -0600167 // TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
168 // should work.
169 if (keymaster0_dev->common.module->module_api_version
Paul Lawrence8c008392014-05-06 14:02:48 -0700170 < KEYMASTER_MODULE_API_VERSION_0_3) {
171 rc = 0;
172 goto out;
173 }
174
Shawn Willdenda6e8992015-06-03 09:40:45 -0600175 if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
176 (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700177 rc = 1;
178 }
179
180out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600181 if (keymaster1_dev) {
182 keymaster1_close(keymaster1_dev);
183 }
184 if (keymaster0_dev) {
185 keymaster0_close(keymaster0_dev);
186 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700187 return rc;
188}
189
190/* Create a new keymaster key and store it in this footer */
191static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
192{
193 uint8_t* key = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600194 keymaster0_device_t *keymaster0_dev = 0;
195 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700196
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800197 if (ftr->keymaster_blob_size) {
198 SLOGI("Already have key");
199 return 0;
200 }
201
Shawn Willdenda6e8992015-06-03 09:40:45 -0600202 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700203 SLOGE("Failed to init keymaster");
204 return -1;
205 }
206
207 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600208 size_t key_size = 0;
209 if (keymaster1_dev) {
210 keymaster_key_param_t params[] = {
211 /* Algorithm & size specifications. Stick with RSA for now. Switch to AES later. */
212 keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
213 keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
214 keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700215
Shawn Willden86af3552015-06-24 07:21:54 -0700216 /* The only allowed purpose for this key is signing. */
217 keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
218
219 /* Padding & digest specifications. */
Shawn Willdenda6e8992015-06-03 09:40:45 -0600220 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
Shawn Willdenda6e8992015-06-03 09:40:45 -0600221 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700222
Shawn Willdenda6e8992015-06-03 09:40:45 -0600223 /* Require that the key be usable in standalone mode. File system isn't available. */
224 keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
225
226 /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
227 keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
228
Shawn Willdenda6e8992015-06-03 09:40:45 -0600229 /* Rate-limit key usage attempts, to rate-limit brute force */
230 keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
231 };
232 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
233 keymaster_key_blob_t key_blob;
234 keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, &param_set,
235 &key_blob,
236 NULL /* characteristics */);
237 if (error != KM_ERROR_OK) {
238 SLOGE("Failed to generate keymaster1 key, error %d", error);
239 rc = -1;
240 goto out;
241 }
242
243 key = (uint8_t*)key_blob.key_material;
244 key_size = key_blob.key_material_size;
245 }
246 else if (keymaster0_dev) {
247 keymaster_rsa_keygen_params_t params;
248 memset(&params, '\0', sizeof(params));
249 params.public_exponent = RSA_EXPONENT;
250 params.modulus_size = RSA_KEY_SIZE;
251
252 if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, &params,
253 &key, &key_size)) {
254 SLOGE("Failed to generate keypair");
255 rc = -1;
256 goto out;
257 }
258 } else {
259 SLOGE("Cryptfs bug: keymaster_init succeeded but didn't initialize a device");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700260 rc = -1;
261 goto out;
262 }
263
264 if (key_size > KEYMASTER_BLOB_SIZE) {
265 SLOGE("Keymaster key too large for crypto footer");
266 rc = -1;
267 goto out;
268 }
269
270 memcpy(ftr->keymaster_blob, key, key_size);
271 ftr->keymaster_blob_size = key_size;
272
273out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600274 if (keymaster0_dev)
275 keymaster0_close(keymaster0_dev);
276 if (keymaster1_dev)
277 keymaster1_close(keymaster1_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700278 free(key);
279 return rc;
280}
281
Shawn Willdene17a9c42014-09-08 13:04:08 -0600282/* This signs the given object using the keymaster key. */
283static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600284 const unsigned char *object,
285 const size_t object_size,
286 unsigned char **signature,
287 size_t *signature_size)
288{
289 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600290 keymaster0_device_t *keymaster0_dev = 0;
291 keymaster1_device_t *keymaster1_dev = 0;
292 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600293 SLOGE("Failed to init keymaster");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600294 rc = -1;
295 goto out;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600296 }
297
Shawn Willden47ba10d2014-09-03 17:07:06 -0600298 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600299 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600300 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600301
Shawn Willdene17a9c42014-09-08 13:04:08 -0600302 // To sign a message with RSA, the message must satisfy two
303 // constraints:
304 //
305 // 1. The message, when interpreted as a big-endian numeric value, must
306 // be strictly less than the public modulus of the RSA key. Note
307 // that because the most significant bit of the public modulus is
308 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
309 // key), an n-bit message with most significant bit 0 always
310 // satisfies this requirement.
311 //
312 // 2. The message must have the same length in bits as the public
313 // modulus of the RSA key. This requirement isn't mathematically
314 // necessary, but is necessary to ensure consistency in
315 // implementations.
316 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600317 case KDF_SCRYPT_KEYMASTER:
318 // This ensures the most significant byte of the signed message
319 // is zero. We could have zero-padded to the left instead, but
320 // this approach is slightly more robust against changes in
321 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600322 // so) because we really should be using a proper deterministic
323 // RSA padding function, such as PKCS1.
Shawn Willdene17a9c42014-09-08 13:04:08 -0600324 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
325 SLOGI("Signing safely-padded object");
326 break;
327 default:
328 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Shawn Willdenda6e8992015-06-03 09:40:45 -0600329 rc = -1;
330 goto out;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600331 }
332
Shawn Willdenda6e8992015-06-03 09:40:45 -0600333 if (keymaster0_dev) {
334 keymaster_rsa_sign_params_t params;
335 params.digest_type = DIGEST_NONE;
336 params.padding_type = PADDING_NONE;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600337
Shawn Willdenda6e8992015-06-03 09:40:45 -0600338 rc = keymaster0_dev->sign_data(keymaster0_dev,
339 &params,
340 ftr->keymaster_blob,
341 ftr->keymaster_blob_size,
342 to_sign,
343 to_sign_size,
344 signature,
345 signature_size);
346 goto out;
347 } else if (keymaster1_dev) {
348 keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
349 keymaster_key_param_t params[] = {
350 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
351 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
352 };
353 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
354 keymaster_operation_handle_t op_handle;
355 keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
356 &param_set, NULL /* out_params */,
357 &op_handle);
Shawn Willden04170602015-06-18 12:26:59 -0600358 if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
Shawn Willdenda6e8992015-06-03 09:40:45 -0600359 // Key usage has been rate-limited. Wait a bit and try again.
360 sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
361 error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
362 &param_set, NULL /* out_params */,
363 &op_handle);
364 }
365 if (error != KM_ERROR_OK) {
366 SLOGE("Error starting keymaster signature transaction: %d", error);
367 rc = -1;
368 goto out;
369 }
370
371 keymaster_blob_t input = { to_sign, to_sign_size };
372 size_t input_consumed;
373 error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
374 &input, &input_consumed, NULL /* out_params */,
375 NULL /* output */);
376 if (error != KM_ERROR_OK) {
377 SLOGE("Error sending data to keymaster signature transaction: %d", error);
378 rc = -1;
379 goto out;
380 }
381 if (input_consumed != to_sign_size) {
382 // This should never happen. If it does, it's a bug in the keymaster implementation.
383 SLOGE("Keymaster update() did not consume all data.");
384 keymaster1_dev->abort(keymaster1_dev, op_handle);
385 rc = -1;
386 goto out;
387 }
388
389 keymaster_blob_t tmp_sig;
390 error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
391 NULL /* verify signature */, NULL /* out_params */,
392 &tmp_sig);
393 if (error != KM_ERROR_OK) {
394 SLOGE("Error finishing keymaster signature transaction: %d", error);
395 rc = -1;
396 goto out;
397 }
398
399 *signature = (uint8_t*)tmp_sig.data;
400 *signature_size = tmp_sig.data_length;
401 } else {
402 SLOGE("Cryptfs bug: keymaster_init succeded but didn't initialize a device.");
403 rc = -1;
404 goto out;
405 }
406
407 out:
408 if (keymaster1_dev)
409 keymaster1_close(keymaster1_dev);
410 if (keymaster0_dev)
411 keymaster0_close(keymaster0_dev);
412
413 return rc;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600414}
415
Paul Lawrence399317e2014-03-10 13:20:50 -0700416/* Store password when userdata is successfully decrypted and mounted.
417 * Cleared by cryptfs_clear_password
418 *
419 * To avoid a double prompt at boot, we need to store the CryptKeeper
420 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
421 * Since the entire framework is torn down and rebuilt after encryption,
422 * we have to use a daemon or similar to store the password. Since vold
423 * is secured against IPC except from system processes, it seems a reasonable
424 * place to store this.
425 *
426 * password should be cleared once it has been used.
427 *
428 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800429 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700430static char* password = 0;
431static int password_expiry_time = 0;
432static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800433
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800434extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800435
Paul Lawrence87999172014-02-20 12:21:31 -0800436enum RebootType {reboot, recovery, shutdown};
437static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700438{
Paul Lawrence87999172014-02-20 12:21:31 -0800439 switch(rt) {
440 case reboot:
441 property_set(ANDROID_RB_PROPERTY, "reboot");
442 break;
443
444 case recovery:
445 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
446 break;
447
448 case shutdown:
449 property_set(ANDROID_RB_PROPERTY, "shutdown");
450 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700451 }
Paul Lawrence87999172014-02-20 12:21:31 -0800452
Ken Sumralladfba362013-06-04 16:37:52 -0700453 sleep(20);
454
455 /* Shouldn't get here, reboot should happen before sleep times out */
456 return;
457}
458
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800459static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
460{
461 memset(io, 0, dataSize);
462 io->data_size = dataSize;
463 io->data_start = sizeof(struct dm_ioctl);
464 io->version[0] = 4;
465 io->version[1] = 0;
466 io->version[2] = 0;
467 io->flags = flags;
468 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100469 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800470 }
471}
472
Kenny Rootc4c70f12013-06-14 12:11:38 -0700473/**
474 * Gets the default device scrypt parameters for key derivation time tuning.
475 * The parameters should lead to about one second derivation time for the
476 * given device.
477 */
478static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
479 const int default_params[] = SCRYPT_DEFAULTS;
480 int params[] = SCRYPT_DEFAULTS;
481 char paramstr[PROPERTY_VALUE_MAX];
482 char *token;
483 char *saveptr;
484 int i;
485
486 property_get(SCRYPT_PROP, paramstr, "");
487 if (paramstr[0] != '\0') {
488 /*
489 * The token we're looking for should be three integers separated by
490 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
491 */
Kenny Root2947e342013-08-14 15:54:49 -0700492 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
493 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700494 i++, token = strtok_r(NULL, ":", &saveptr)) {
495 char *endptr;
496 params[i] = strtol(token, &endptr, 10);
497
498 /*
499 * Check that there was a valid number and it's 8-bit. If not,
500 * break out and the end check will take the default values.
501 */
502 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
503 break;
504 }
505 }
506
507 /*
508 * If there were not enough tokens or a token was malformed (not an
509 * integer), it will end up here and the default parameters can be
510 * taken.
511 */
512 if ((i != 3) || (token != NULL)) {
513 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
514 memcpy(params, default_params, sizeof(params));
515 }
516 }
517
518 ftr->N_factor = params[0];
519 ftr->r_factor = params[1];
520 ftr->p_factor = params[2];
521}
522
Ken Sumrall3ed82362011-01-28 23:31:16 -0800523static unsigned int get_fs_size(char *dev)
524{
525 int fd, block_size;
526 struct ext4_super_block sb;
527 off64_t len;
528
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700529 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800530 SLOGE("Cannot open device to get filesystem size ");
531 return 0;
532 }
533
534 if (lseek64(fd, 1024, SEEK_SET) < 0) {
535 SLOGE("Cannot seek to superblock");
536 return 0;
537 }
538
539 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
540 SLOGE("Cannot read superblock");
541 return 0;
542 }
543
544 close(fd);
545
Daniel Rosenberge82df162014-08-15 22:19:23 +0000546 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
547 SLOGE("Not a valid ext4 superblock");
548 return 0;
549 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800550 block_size = 1024 << sb.s_log_block_size;
551 /* compute length in bytes */
552 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
553
554 /* return length in sectors */
555 return (unsigned int) (len / 512);
556}
557
Ken Sumrall160b4d62013-04-22 12:15:39 -0700558static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
559{
560 static int cached_data = 0;
561 static off64_t cached_off = 0;
562 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
563 int fd;
564 char key_loc[PROPERTY_VALUE_MAX];
565 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700566 int rc = -1;
567
568 if (!cached_data) {
569 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
570
571 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700572 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700573 SLOGE("Cannot open real block device %s\n", real_blkdev);
574 return -1;
575 }
576
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900577 unsigned long nr_sec = 0;
578 get_blkdev_size(fd, &nr_sec);
579 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700580 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
581 * encryption info footer and key, and plenty of bytes to spare for future
582 * growth.
583 */
584 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
585 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
586 cached_data = 1;
587 } else {
588 SLOGE("Cannot get size of block device %s\n", real_blkdev);
589 }
590 close(fd);
591 } else {
592 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
593 cached_off = 0;
594 cached_data = 1;
595 }
596 }
597
598 if (cached_data) {
599 if (metadata_fname) {
600 *metadata_fname = cached_metadata_fname;
601 }
602 if (off) {
603 *off = cached_off;
604 }
605 rc = 0;
606 }
607
608 return rc;
609}
610
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800611/* Set sha256 checksum in structure */
612static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
613{
614 SHA256_CTX c;
615 SHA256_Init(&c);
616 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
617 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
618 SHA256_Final(crypt_ftr->sha256, &c);
619}
620
Ken Sumralle8744072011-01-18 22:01:55 -0800621/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800622 * update the failed mount count but not change the key.
623 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700624static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800625{
626 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800627 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700628 /* starting_off is set to the SEEK_SET offset
629 * where the crypto structure starts
630 */
631 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800632 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700633 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700634 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800635
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800636 set_ftr_sha(crypt_ftr);
637
Ken Sumrall160b4d62013-04-22 12:15:39 -0700638 if (get_crypt_ftr_info(&fname, &starting_off)) {
639 SLOGE("Unable to get crypt_ftr_info\n");
640 return -1;
641 }
642 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700643 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700644 return -1;
645 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700646 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700647 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700648 return -1;
649 }
650
651 /* Seek to the start of the crypt footer */
652 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
653 SLOGE("Cannot seek to real block device footer\n");
654 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800655 }
656
657 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
658 SLOGE("Cannot write real block device footer\n");
659 goto errout;
660 }
661
Ken Sumrall3be890f2011-09-14 16:53:46 -0700662 fstat(fd, &statbuf);
663 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700664 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700665 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800666 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800667 goto errout;
668 }
669 }
670
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800671 /* Success! */
672 rc = 0;
673
674errout:
675 close(fd);
676 return rc;
677
678}
679
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800680static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
681{
682 struct crypt_mnt_ftr copy;
683 memcpy(&copy, crypt_ftr, sizeof(copy));
684 set_ftr_sha(&copy);
685 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
686}
687
Ken Sumrall160b4d62013-04-22 12:15:39 -0700688static inline int unix_read(int fd, void* buff, int len)
689{
690 return TEMP_FAILURE_RETRY(read(fd, buff, len));
691}
692
693static inline int unix_write(int fd, const void* buff, int len)
694{
695 return TEMP_FAILURE_RETRY(write(fd, buff, len));
696}
697
698static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
699{
700 memset(pdata, 0, len);
701 pdata->persist_magic = PERSIST_DATA_MAGIC;
702 pdata->persist_valid_entries = 0;
703}
704
705/* A routine to update the passed in crypt_ftr to the lastest version.
706 * fd is open read/write on the device that holds the crypto footer and persistent
707 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
708 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
709 */
710static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
711{
Kenny Root7434b312013-06-14 11:29:53 -0700712 int orig_major = crypt_ftr->major_version;
713 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700714
Kenny Root7434b312013-06-14 11:29:53 -0700715 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
716 struct crypt_persist_data *pdata;
717 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700718
Kenny Rootc4c70f12013-06-14 12:11:38 -0700719 SLOGW("upgrading crypto footer to 1.1");
720
Kenny Root7434b312013-06-14 11:29:53 -0700721 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
722 if (pdata == NULL) {
723 SLOGE("Cannot allocate persisent data\n");
724 return;
725 }
726 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
727
728 /* Need to initialize the persistent data area */
729 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
730 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100731 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700732 return;
733 }
734 /* Write all zeros to the first copy, making it invalid */
735 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
736
737 /* Write a valid but empty structure to the second copy */
738 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
739 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
740
741 /* Update the footer */
742 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
743 crypt_ftr->persist_data_offset[0] = pdata_offset;
744 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
745 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100746 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700747 }
748
Paul Lawrencef4faa572014-01-29 13:31:03 -0800749 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700750 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800751 /* But keep the old kdf_type.
752 * It will get updated later to KDF_SCRYPT after the password has been verified.
753 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700754 crypt_ftr->kdf_type = KDF_PBKDF2;
755 get_device_scrypt_params(crypt_ftr);
756 crypt_ftr->minor_version = 2;
757 }
758
Paul Lawrencef4faa572014-01-29 13:31:03 -0800759 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
760 SLOGW("upgrading crypto footer to 1.3");
761 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
762 crypt_ftr->minor_version = 3;
763 }
764
Kenny Root7434b312013-06-14 11:29:53 -0700765 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
766 if (lseek64(fd, offset, SEEK_SET) == -1) {
767 SLOGE("Cannot seek to crypt footer\n");
768 return;
769 }
770 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700771 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700772}
773
774
775static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800776{
777 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800778 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700779 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800780 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700781 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700782 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800783
Ken Sumrall160b4d62013-04-22 12:15:39 -0700784 if (get_crypt_ftr_info(&fname, &starting_off)) {
785 SLOGE("Unable to get crypt_ftr_info\n");
786 return -1;
787 }
788 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700789 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700790 return -1;
791 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700792 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700793 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700794 return -1;
795 }
796
797 /* Make sure it's 16 Kbytes in length */
798 fstat(fd, &statbuf);
799 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
800 SLOGE("footer file %s is not the expected size!\n", fname);
801 goto errout;
802 }
803
804 /* Seek to the start of the crypt footer */
805 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
806 SLOGE("Cannot seek to real block device footer\n");
807 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800808 }
809
810 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
811 SLOGE("Cannot read real block device footer\n");
812 goto errout;
813 }
814
815 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700816 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800817 goto errout;
818 }
819
Kenny Rootc96a5f82013-06-14 12:08:28 -0700820 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
821 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
822 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800823 goto errout;
824 }
825
Kenny Rootc96a5f82013-06-14 12:08:28 -0700826 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
827 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
828 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800829 }
830
Ken Sumrall160b4d62013-04-22 12:15:39 -0700831 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
832 * copy on disk before returning.
833 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700834 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700835 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800836 }
837
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800838 /* Success! */
839 rc = 0;
840
841errout:
842 close(fd);
843 return rc;
844}
845
Ken Sumrall160b4d62013-04-22 12:15:39 -0700846static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
847{
848 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
849 crypt_ftr->persist_data_offset[1]) {
850 SLOGE("Crypt_ftr persist data regions overlap");
851 return -1;
852 }
853
854 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
855 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
856 return -1;
857 }
858
859 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
860 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
861 CRYPT_FOOTER_OFFSET) {
862 SLOGE("Persistent data extends past crypto footer");
863 return -1;
864 }
865
866 return 0;
867}
868
869static int load_persistent_data(void)
870{
871 struct crypt_mnt_ftr crypt_ftr;
872 struct crypt_persist_data *pdata = NULL;
873 char encrypted_state[PROPERTY_VALUE_MAX];
874 char *fname;
875 int found = 0;
876 int fd;
877 int ret;
878 int i;
879
880 if (persist_data) {
881 /* Nothing to do, we've already loaded or initialized it */
882 return 0;
883 }
884
885
886 /* If not encrypted, just allocate an empty table and initialize it */
887 property_get("ro.crypto.state", encrypted_state, "");
888 if (strcmp(encrypted_state, "encrypted") ) {
889 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
890 if (pdata) {
891 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
892 persist_data = pdata;
893 return 0;
894 }
895 return -1;
896 }
897
898 if(get_crypt_ftr_and_key(&crypt_ftr)) {
899 return -1;
900 }
901
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700902 if ((crypt_ftr.major_version < 1)
903 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700904 SLOGE("Crypt_ftr version doesn't support persistent data");
905 return -1;
906 }
907
908 if (get_crypt_ftr_info(&fname, NULL)) {
909 return -1;
910 }
911
912 ret = validate_persistent_data_storage(&crypt_ftr);
913 if (ret) {
914 return -1;
915 }
916
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700917 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700918 if (fd < 0) {
919 SLOGE("Cannot open %s metadata file", fname);
920 return -1;
921 }
922
923 if (persist_data == NULL) {
924 pdata = malloc(crypt_ftr.persist_data_size);
925 if (pdata == NULL) {
926 SLOGE("Cannot allocate memory for persistent data");
927 goto err;
928 }
929 }
930
931 for (i = 0; i < 2; i++) {
932 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
933 SLOGE("Cannot seek to read persistent data on %s", fname);
934 goto err2;
935 }
936 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
937 SLOGE("Error reading persistent data on iteration %d", i);
938 goto err2;
939 }
940 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
941 found = 1;
942 break;
943 }
944 }
945
946 if (!found) {
947 SLOGI("Could not find valid persistent data, creating");
948 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
949 }
950
951 /* Success */
952 persist_data = pdata;
953 close(fd);
954 return 0;
955
956err2:
957 free(pdata);
958
959err:
960 close(fd);
961 return -1;
962}
963
964static int save_persistent_data(void)
965{
966 struct crypt_mnt_ftr crypt_ftr;
967 struct crypt_persist_data *pdata;
968 char *fname;
969 off64_t write_offset;
970 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700971 int fd;
972 int ret;
973
974 if (persist_data == NULL) {
975 SLOGE("No persistent data to save");
976 return -1;
977 }
978
979 if(get_crypt_ftr_and_key(&crypt_ftr)) {
980 return -1;
981 }
982
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700983 if ((crypt_ftr.major_version < 1)
984 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700985 SLOGE("Crypt_ftr version doesn't support persistent data");
986 return -1;
987 }
988
989 ret = validate_persistent_data_storage(&crypt_ftr);
990 if (ret) {
991 return -1;
992 }
993
994 if (get_crypt_ftr_info(&fname, NULL)) {
995 return -1;
996 }
997
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700998 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700999 if (fd < 0) {
1000 SLOGE("Cannot open %s metadata file", fname);
1001 return -1;
1002 }
1003
1004 pdata = malloc(crypt_ftr.persist_data_size);
1005 if (pdata == NULL) {
1006 SLOGE("Cannot allocate persistant data");
1007 goto err;
1008 }
1009
1010 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1011 SLOGE("Cannot seek to read persistent data on %s", fname);
1012 goto err2;
1013 }
1014
1015 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
1016 SLOGE("Error reading persistent data before save");
1017 goto err2;
1018 }
1019
1020 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1021 /* The first copy is the curent valid copy, so write to
1022 * the second copy and erase this one */
1023 write_offset = crypt_ftr.persist_data_offset[1];
1024 erase_offset = crypt_ftr.persist_data_offset[0];
1025 } else {
1026 /* The second copy must be the valid copy, so write to
1027 * the first copy, and erase the second */
1028 write_offset = crypt_ftr.persist_data_offset[0];
1029 erase_offset = crypt_ftr.persist_data_offset[1];
1030 }
1031
1032 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001033 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001034 SLOGE("Cannot seek to write persistent data");
1035 goto err2;
1036 }
1037 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1038 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001039 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001040 SLOGE("Cannot seek to erase previous persistent data");
1041 goto err2;
1042 }
1043 fsync(fd);
1044 memset(pdata, 0, crypt_ftr.persist_data_size);
1045 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
1046 (int) crypt_ftr.persist_data_size) {
1047 SLOGE("Cannot write to erase previous persistent data");
1048 goto err2;
1049 }
1050 fsync(fd);
1051 } else {
1052 SLOGE("Cannot write to save persistent data");
1053 goto err2;
1054 }
1055
1056 /* Success */
1057 free(pdata);
1058 close(fd);
1059 return 0;
1060
1061err2:
1062 free(pdata);
1063err:
1064 close(fd);
1065 return -1;
1066}
1067
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001068/* Convert a binary key of specified length into an ascii hex string equivalent,
1069 * without the leading 0x and with null termination
1070 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001071static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001072 unsigned int keysize, char *master_key_ascii) {
1073 unsigned int i, a;
1074 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001075
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001076 for (i=0, a=0; i<keysize; i++, a+=2) {
1077 /* For each byte, write out two ascii hex digits */
1078 nibble = (master_key[i] >> 4) & 0xf;
1079 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001080
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001081 nibble = master_key[i] & 0xf;
1082 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1083 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001084
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001085 /* Add the null termination */
1086 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001087
1088}
1089
Jeff Sharkey9c484982015-03-31 10:35:33 -07001090static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
1091 const unsigned char *master_key, const char *real_blk_name,
1092 const char *name, int fd, const char *extra_params) {
Dan Albertc07fa3f2014-12-18 10:00:55 -08001093 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001094 struct dm_ioctl *io;
1095 struct dm_target_spec *tgt;
1096 char *crypt_params;
1097 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1098 int i;
1099
1100 io = (struct dm_ioctl *) buffer;
1101
1102 /* Load the mapping table for this device */
1103 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1104
1105 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1106 io->target_count = 1;
1107 tgt->status = 0;
1108 tgt->sector_start = 0;
1109 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -07001110#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001111 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1112 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1113 }
1114 else {
1115 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1116 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001117#else
1118 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1119#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001120
1121 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1122 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1123 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1124 master_key_ascii, real_blk_name, extra_params);
1125 crypt_params += strlen(crypt_params) + 1;
1126 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1127 tgt->next = crypt_params - buffer;
1128
1129 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1130 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1131 break;
1132 }
1133 usleep(500000);
1134 }
1135
1136 if (i == TABLE_LOAD_RETRIES) {
1137 /* We failed to load the table, return an error */
1138 return -1;
1139 } else {
1140 return i + 1;
1141 }
1142}
1143
1144
1145static int get_dm_crypt_version(int fd, const char *name, int *version)
1146{
1147 char buffer[DM_CRYPT_BUF_SIZE];
1148 struct dm_ioctl *io;
1149 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001150
1151 io = (struct dm_ioctl *) buffer;
1152
1153 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1154
1155 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1156 return -1;
1157 }
1158
1159 /* Iterate over the returned versions, looking for name of "crypt".
1160 * When found, get and return the version.
1161 */
1162 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1163 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001164#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001165 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001166#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001167 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001168#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001169 /* We found the crypt driver, return the version, and get out */
1170 version[0] = v->version[0];
1171 version[1] = v->version[1];
1172 version[2] = v->version[2];
1173 return 0;
1174 }
1175 v = (struct dm_target_versions *)(((char *)v) + v->next);
1176 }
1177
1178 return -1;
1179}
1180
Jeff Sharkey9c484982015-03-31 10:35:33 -07001181static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
1182 const unsigned char *master_key, const char *real_blk_name,
1183 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001184 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001185 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001186 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001187 int fd=0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001188 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001189 int version[3];
1190 char *extra_params;
1191 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001192
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001193 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001194 SLOGE("Cannot open device-mapper\n");
1195 goto errout;
1196 }
1197
1198 io = (struct dm_ioctl *) buffer;
1199
1200 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1201 if (ioctl(fd, DM_DEV_CREATE, io)) {
1202 SLOGE("Cannot create dm-crypt device\n");
1203 goto errout;
1204 }
1205
1206 /* Get the device status, in particular, the name of it's device file */
1207 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1208 if (ioctl(fd, DM_DEV_STATUS, io)) {
1209 SLOGE("Cannot retrieve dm-crypt device status\n");
1210 goto errout;
1211 }
1212 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1213 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1214
Ken Sumralldb5e0262013-02-05 17:39:48 -08001215 extra_params = "";
1216 if (! get_dm_crypt_version(fd, name, version)) {
1217 /* Support for allow_discards was added in version 1.11.0 */
1218 if ((version[0] >= 2) ||
1219 ((version[0] == 1) && (version[1] >= 11))) {
1220 extra_params = "1 allow_discards";
1221 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1222 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001223 }
1224
Ken Sumralldb5e0262013-02-05 17:39:48 -08001225 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1226 fd, extra_params);
1227 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001228 SLOGE("Cannot load dm-crypt mapping table.\n");
1229 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001230 } else if (load_count > 1) {
1231 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001232 }
1233
1234 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001235 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001236
1237 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1238 SLOGE("Cannot resume the dm-crypt device\n");
1239 goto errout;
1240 }
1241
1242 /* We made it here with no errors. Woot! */
1243 retval = 0;
1244
1245errout:
1246 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1247
1248 return retval;
1249}
1250
Ken Sumrall29d8da82011-05-18 17:20:07 -07001251static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001252{
1253 int fd;
1254 char buffer[DM_CRYPT_BUF_SIZE];
1255 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001256 int retval = -1;
1257
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001258 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259 SLOGE("Cannot open device-mapper\n");
1260 goto errout;
1261 }
1262
1263 io = (struct dm_ioctl *) buffer;
1264
1265 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1266 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1267 SLOGE("Cannot remove dm-crypt device\n");
1268 goto errout;
1269 }
1270
1271 /* We made it here with no errors. Woot! */
1272 retval = 0;
1273
1274errout:
1275 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1276
1277 return retval;
1278
1279}
1280
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001281static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001282 unsigned char *ikey, void *params UNUSED)
1283{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001284 SLOGI("Using pbkdf2 for cryptfs KDF");
1285
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001286 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001287 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1288 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1289 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001290}
1291
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001292static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001293 unsigned char *ikey, void *params)
1294{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001295 SLOGI("Using scrypt for cryptfs KDF");
1296
Kenny Rootc4c70f12013-06-14 12:11:38 -07001297 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1298
1299 int N = 1 << ftr->N_factor;
1300 int r = 1 << ftr->r_factor;
1301 int p = 1 << ftr->p_factor;
1302
1303 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001304 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001305 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1306 salt, SALT_LEN, N, r, p, ikey,
1307 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001308
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001309 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001310}
1311
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001312static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1313 unsigned char *ikey, void *params)
1314{
1315 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1316
1317 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001318 size_t signature_size;
1319 unsigned char* signature;
1320 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1321
1322 int N = 1 << ftr->N_factor;
1323 int r = 1 << ftr->r_factor;
1324 int p = 1 << ftr->p_factor;
1325
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001326 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1327 salt, SALT_LEN, N, r, p, ikey,
1328 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001329
1330 if (rc) {
1331 SLOGE("scrypt failed");
1332 return -1;
1333 }
1334
Shawn Willdene17a9c42014-09-08 13:04:08 -06001335 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1336 &signature, &signature_size)) {
1337 SLOGE("Signing failed");
1338 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001339 }
1340
1341 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1342 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1343 free(signature);
1344
1345 if (rc) {
1346 SLOGE("scrypt failed");
1347 return -1;
1348 }
1349
1350 return 0;
1351}
1352
1353static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1354 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001355 unsigned char *encrypted_master_key,
1356 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001357{
1358 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1359 EVP_CIPHER_CTX e_ctx;
1360 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001361 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001362
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001363 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001364 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001365
1366 switch (crypt_ftr->kdf_type) {
1367 case KDF_SCRYPT_KEYMASTER:
1368 if (keymaster_create_key(crypt_ftr)) {
1369 SLOGE("keymaster_create_key failed");
1370 return -1;
1371 }
1372
1373 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1374 SLOGE("scrypt failed");
1375 return -1;
1376 }
1377 break;
1378
1379 case KDF_SCRYPT:
1380 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1381 SLOGE("scrypt failed");
1382 return -1;
1383 }
1384 break;
1385
1386 default:
1387 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001388 return -1;
1389 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001390
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001392 EVP_CIPHER_CTX_init(&e_ctx);
1393 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001394 SLOGE("EVP_EncryptInit failed\n");
1395 return -1;
1396 }
1397 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001398
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001399 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001400 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001401 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001402 SLOGE("EVP_EncryptUpdate failed\n");
1403 return -1;
1404 }
Adam Langley889c4f12014-09-03 14:23:13 -07001405 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001406 SLOGE("EVP_EncryptFinal failed\n");
1407 return -1;
1408 }
1409
1410 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1411 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1412 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001414
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001415 /* Store the scrypt of the intermediate key, so we can validate if it's a
1416 password error or mount error when things go wrong.
1417 Note there's no need to check for errors, since if this is incorrect, we
1418 simply won't wipe userdata, which is the correct default behavior
1419 */
1420 int N = 1 << crypt_ftr->N_factor;
1421 int r = 1 << crypt_ftr->r_factor;
1422 int p = 1 << crypt_ftr->p_factor;
1423
1424 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1425 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1426 crypt_ftr->scrypted_intermediate_key,
1427 sizeof(crypt_ftr->scrypted_intermediate_key));
1428
1429 if (rc) {
1430 SLOGE("encrypt_master_key: crypto_scrypt failed");
1431 }
1432
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001433 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001434}
1435
Paul Lawrence731a7a22015-04-28 22:14:15 +00001436static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001437 unsigned char *encrypted_master_key,
1438 unsigned char *decrypted_master_key,
1439 kdf_func kdf, void *kdf_params,
1440 unsigned char** intermediate_key,
1441 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001442{
1443 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 -08001444 EVP_CIPHER_CTX d_ctx;
1445 int decrypted_len, final_len;
1446
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001447 /* Turn the password into an intermediate key and IV that can decrypt the
1448 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001449 if (kdf(passwd, salt, ikey, kdf_params)) {
1450 SLOGE("kdf failed");
1451 return -1;
1452 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001453
1454 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001455 EVP_CIPHER_CTX_init(&d_ctx);
1456 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001457 return -1;
1458 }
1459 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1460 /* Decrypt the master key */
1461 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1462 encrypted_master_key, KEY_LEN_BYTES)) {
1463 return -1;
1464 }
Adam Langley889c4f12014-09-03 14:23:13 -07001465 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001466 return -1;
1467 }
1468
1469 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1470 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001471 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001472
1473 /* Copy intermediate key if needed by params */
1474 if (intermediate_key && intermediate_key_size) {
1475 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1476 if (intermediate_key) {
1477 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1478 *intermediate_key_size = KEY_LEN_BYTES;
1479 }
1480 }
1481
1482 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001483}
1484
Kenny Rootc4c70f12013-06-14 12:11:38 -07001485static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001486{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001487 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001488 *kdf = scrypt_keymaster;
1489 *kdf_params = ftr;
1490 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001491 *kdf = scrypt;
1492 *kdf_params = ftr;
1493 } else {
1494 *kdf = pbkdf2;
1495 *kdf_params = NULL;
1496 }
1497}
1498
Paul Lawrence731a7a22015-04-28 22:14:15 +00001499static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001500 struct crypt_mnt_ftr *crypt_ftr,
1501 unsigned char** intermediate_key,
1502 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001503{
1504 kdf_func kdf;
1505 void *kdf_params;
1506 int ret;
1507
1508 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001509 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1510 decrypted_master_key, kdf, kdf_params,
1511 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001512 if (ret != 0) {
1513 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001514 }
1515
1516 return ret;
1517}
1518
1519static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1520 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001521 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001522 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001523
1524 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001525 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001526 read(fd, key_buf, sizeof(key_buf));
1527 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001528 close(fd);
1529
1530 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001531 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001532}
1533
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001534int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001535{
Greg Hackmann955653e2014-09-24 14:55:20 -07001536 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001537#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001538
1539 /* Now umount the tmpfs filesystem */
1540 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001541 if (umount(mountpoint) == 0) {
1542 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001543 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001544
1545 if (errno == EINVAL) {
1546 /* EINVAL is returned if the directory is not a mountpoint,
1547 * i.e. there is no filesystem mounted there. So just get out.
1548 */
1549 break;
1550 }
1551
1552 err = errno;
1553
1554 /* If allowed, be increasingly aggressive before the last two retries */
1555 if (kill) {
1556 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1557 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001558 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001559 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1560 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001561 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001562 }
1563 }
1564
1565 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001566 }
1567
1568 if (i < WAIT_UNMOUNT_COUNT) {
1569 SLOGD("unmounting %s succeeded\n", mountpoint);
1570 rc = 0;
1571 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001572 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001573 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001574 rc = -1;
1575 }
1576
1577 return rc;
1578}
1579
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001580#define DATA_PREP_TIMEOUT 1000
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001581static int prep_data_fs(void)
1582{
1583 int i;
1584
Jeff Sharkey47695b22016-02-01 17:02:29 -07001585 // NOTE: post_fs_data results in init calling back around to vold, so all
1586 // callers to this method must be async
1587
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001588 /* Do the prep of the /data filesystem */
1589 property_set("vold.post_fs_data_done", "0");
1590 property_set("vold.decrypt", "trigger_post_fs_data");
1591 SLOGD("Just triggered post_fs_data\n");
1592
Ken Sumrallc5872692013-05-14 15:26:31 -07001593 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001594 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001595 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001596
1597 property_get("vold.post_fs_data_done", p, "0");
1598 if (*p == '1') {
1599 break;
1600 } else {
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001601 usleep(50000);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001602 }
1603 }
1604 if (i == DATA_PREP_TIMEOUT) {
1605 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001606 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001607 return -1;
1608 } else {
1609 SLOGD("post_fs_data done\n");
1610 return 0;
1611 }
1612}
1613
Paul Lawrence74f29f12014-08-28 15:54:10 -07001614static void cryptfs_set_corrupt()
1615{
1616 // Mark the footer as bad
1617 struct crypt_mnt_ftr crypt_ftr;
1618 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1619 SLOGE("Failed to get crypto footer - panic");
1620 return;
1621 }
1622
1623 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1624 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1625 SLOGE("Failed to set crypto footer - panic");
1626 return;
1627 }
1628}
1629
1630static void cryptfs_trigger_restart_min_framework()
1631{
1632 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1633 SLOGE("Failed to mount tmpfs on data - panic");
1634 return;
1635 }
1636
1637 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1638 SLOGE("Failed to trigger post fs data - panic");
1639 return;
1640 }
1641
1642 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1643 SLOGE("Failed to trigger restart min framework - panic");
1644 return;
1645 }
1646}
1647
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001648/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001649static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001650{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001651 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001652 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001653 static int restart_successful = 0;
1654
1655 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001656 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001657 SLOGE("Encrypted filesystem not validated, aborting");
1658 return -1;
1659 }
1660
1661 if (restart_successful) {
1662 SLOGE("System already restarted with encrypted disk, aborting");
1663 return -1;
1664 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001665
Paul Lawrencef4faa572014-01-29 13:31:03 -08001666 if (restart_main) {
1667 /* Here is where we shut down the framework. The init scripts
1668 * start all services in one of three classes: core, main or late_start.
1669 * On boot, we start core and main. Now, we stop main, but not core,
1670 * as core includes vold and a few other really important things that
1671 * we need to keep running. Once main has stopped, we should be able
1672 * to umount the tmpfs /data, then mount the encrypted /data.
1673 * We then restart the class main, and also the class late_start.
1674 * At the moment, I've only put a few things in late_start that I know
1675 * are not needed to bring up the framework, and that also cause problems
1676 * with unmounting the tmpfs /data, but I hope to add add more services
1677 * to the late_start class as we optimize this to decrease the delay
1678 * till the user is asked for the password to the filesystem.
1679 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001680
Paul Lawrencef4faa572014-01-29 13:31:03 -08001681 /* The init files are setup to stop the class main when vold.decrypt is
1682 * set to trigger_reset_main.
1683 */
1684 property_set("vold.decrypt", "trigger_reset_main");
1685 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001686
Paul Lawrencef4faa572014-01-29 13:31:03 -08001687 /* Ugh, shutting down the framework is not synchronous, so until it
1688 * can be fixed, this horrible hack will wait a moment for it all to
1689 * shut down before proceeding. Without it, some devices cannot
1690 * restart the graphics services.
1691 */
1692 sleep(2);
1693 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001694
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001695 /* Now that the framework is shutdown, we should be able to umount()
1696 * the tmpfs filesystem, and mount the real one.
1697 */
1698
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001699 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1700 if (strlen(crypto_blkdev) == 0) {
1701 SLOGE("fs_crypto_blkdev not set\n");
1702 return -1;
1703 }
1704
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001705 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001706 /* If ro.crypto.readonly is set to 1, mount the decrypted
1707 * filesystem readonly. This is used when /data is mounted by
1708 * recovery mode.
1709 */
1710 char ro_prop[PROPERTY_VALUE_MAX];
1711 property_get("ro.crypto.readonly", ro_prop, "");
1712 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1713 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1714 rec->flags |= MS_RDONLY;
1715 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001716
Ken Sumralle5032c42012-04-01 23:58:44 -07001717 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001718 int retries = RETRY_MOUNT_ATTEMPTS;
1719 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001720
1721 /*
1722 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1723 * partitions in the fsck domain.
1724 */
1725 if (setexeccon(secontextFsck())){
1726 SLOGE("Failed to setexeccon");
1727 return -1;
1728 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001729 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1730 crypto_blkdev, 0))
1731 != 0) {
1732 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1733 /* TODO: invoke something similar to
1734 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1735 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1736 SLOGI("Failed to mount %s because it is busy - waiting",
1737 crypto_blkdev);
1738 if (--retries) {
1739 sleep(RETRY_MOUNT_DELAY_SECONDS);
1740 } else {
1741 /* Let's hope that a reboot clears away whatever is keeping
1742 the mount busy */
1743 cryptfs_reboot(reboot);
1744 }
1745 } else {
1746 SLOGE("Failed to mount decrypted data");
1747 cryptfs_set_corrupt();
1748 cryptfs_trigger_restart_min_framework();
1749 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001750 if (setexeccon(NULL)) {
1751 SLOGE("Failed to setexeccon");
1752 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001753 return -1;
1754 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001755 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001756 if (setexeccon(NULL)) {
1757 SLOGE("Failed to setexeccon");
1758 return -1;
1759 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001760
Ken Sumralle5032c42012-04-01 23:58:44 -07001761 property_set("vold.decrypt", "trigger_load_persist_props");
1762 /* Create necessary paths on /data */
1763 if (prep_data_fs()) {
1764 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001765 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001766
1767 /* startup service classes main and late_start */
1768 property_set("vold.decrypt", "trigger_restart_framework");
1769 SLOGD("Just triggered restart_framework\n");
1770
1771 /* Give it a few moments to get started */
1772 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001773 }
1774
Ken Sumrall0cc16632011-01-18 20:32:26 -08001775 if (rc == 0) {
1776 restart_successful = 1;
1777 }
1778
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001779 return rc;
1780}
1781
Paul Lawrencef4faa572014-01-29 13:31:03 -08001782int cryptfs_restart(void)
1783{
Paul Lawrence05335c32015-03-05 09:46:23 -08001784 SLOGI("cryptfs_restart");
1785 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001786 SLOGE("cryptfs_restart not valid for file encryption:");
1787 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001788 }
1789
Paul Lawrencef4faa572014-01-29 13:31:03 -08001790 /* Call internal implementation forcing a restart of main service group */
1791 return cryptfs_restart_internal(1);
1792}
1793
Paul Lawrence05335c32015-03-05 09:46:23 -08001794static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001795{
1796 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001797 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001798 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001799
1800 property_get("ro.crypto.state", encrypted_state, "");
1801 if (strcmp(encrypted_state, "encrypted") ) {
1802 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001803 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001804 }
1805
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001806 // crypto_complete is full disk encrypted status
Paul Lawrence05335c32015-03-05 09:46:23 -08001807 if (e4crypt_crypto_complete(mount_point) == 0) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001808 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001809 }
1810
Ken Sumrall160b4d62013-04-22 12:15:39 -07001811 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001812 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001813
Ken Sumralle1a45852011-12-14 21:24:27 -08001814 /*
1815 * Only report this error if key_loc is a file and it exists.
1816 * If the device was never encrypted, and /data is not mountable for
1817 * some reason, returning 1 should prevent the UI from presenting the
1818 * a "enter password" screen, or worse, a "press button to wipe the
1819 * device" screen.
1820 */
1821 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1822 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001823 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001824 } else {
1825 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001826 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001827 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001828 }
1829
Paul Lawrence74f29f12014-08-28 15:54:10 -07001830 // Test for possible error flags
1831 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1832 SLOGE("Encryption process is partway completed\n");
1833 return CRYPTO_COMPLETE_PARTIAL;
1834 }
1835
1836 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1837 SLOGE("Encryption process was interrupted but cannot continue\n");
1838 return CRYPTO_COMPLETE_INCONSISTENT;
1839 }
1840
1841 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1842 SLOGE("Encryption is successful but data is corrupt\n");
1843 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001844 }
1845
1846 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001847 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001848}
1849
Paul Lawrencef4faa572014-01-29 13:31:03 -08001850static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1851 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001852{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001853 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001854 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001855 char crypto_blkdev[MAXPATHLEN];
1856 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001857 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001858 unsigned int orig_failed_decrypt_count;
1859 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001860 int use_keymaster = 0;
1861 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001862 unsigned char* intermediate_key = 0;
1863 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001864
Paul Lawrencef4faa572014-01-29 13:31:03 -08001865 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1866 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001867
Paul Lawrencef4faa572014-01-29 13:31:03 -08001868 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001869 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1870 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001871 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001872 rc = -1;
1873 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001874 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001875 }
1876
Paul Lawrencef4faa572014-01-29 13:31:03 -08001877 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1878
Ajay Dudani87701e22014-09-17 21:02:52 -07001879#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001880 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1881 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1882 SLOGE("Hardware encryption key does not match");
1883 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001884 }
1885#endif
1886
Paul Lawrence74f29f12014-08-28 15:54:10 -07001887 // Create crypto block device - all (non fatal) code paths
1888 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001889 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1890 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001891 SLOGE("Error creating decrypted block device\n");
1892 rc = -1;
1893 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001894 }
1895
Paul Lawrence74f29f12014-08-28 15:54:10 -07001896 /* Work out if the problem is the password or the data */
1897 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1898 scrypted_intermediate_key)];
1899 int N = 1 << crypt_ftr->N_factor;
1900 int r = 1 << crypt_ftr->r_factor;
1901 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001902
Paul Lawrence74f29f12014-08-28 15:54:10 -07001903 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1904 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1905 N, r, p, scrypted_intermediate_key,
1906 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001907
Paul Lawrence74f29f12014-08-28 15:54:10 -07001908 // Does the key match the crypto footer?
1909 if (rc == 0 && memcmp(scrypted_intermediate_key,
1910 crypt_ftr->scrypted_intermediate_key,
1911 sizeof(scrypted_intermediate_key)) == 0) {
1912 SLOGI("Password matches");
1913 rc = 0;
1914 } else {
1915 /* Try mounting the file system anyway, just in case the problem's with
1916 * the footer, not the key. */
1917 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1918 mkdir(tmp_mount_point, 0755);
1919 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1920 SLOGE("Error temp mounting decrypted block device\n");
1921 delete_crypto_blk_dev(label);
1922
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001923 rc = ++crypt_ftr->failed_decrypt_count;
1924 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001925 } else {
1926 /* Success! */
1927 SLOGI("Password did not match but decrypted drive mounted - continue");
1928 umount(tmp_mount_point);
1929 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001930 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001931 }
1932
1933 if (rc == 0) {
1934 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001935 if (orig_failed_decrypt_count != 0) {
1936 put_crypt_ftr_and_key(crypt_ftr);
1937 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001938
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001939 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001940 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001941 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001942
1943 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001944 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001945 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001946 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001947 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001948 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001949 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001950
Paul Lawrence74f29f12014-08-28 15:54:10 -07001951 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001952 use_keymaster = keymaster_check_compatibility();
1953 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001954 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001955 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1956 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1957 upgrade = 1;
1958 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001959 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001960 upgrade = 1;
1961 }
1962
1963 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001964 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1965 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001966 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001967 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001968 }
1969 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001970
1971 // Do not fail even if upgrade failed - machine is bootable
1972 // Note that if this code is ever hit, there is a *serious* problem
1973 // since KDFs should never fail. You *must* fix the kdf before
1974 // proceeding!
1975 if (rc) {
1976 SLOGW("Upgrade failed with error %d,"
1977 " but continuing with previous state",
1978 rc);
1979 rc = 0;
1980 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001981 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001982 }
1983
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001984 errout:
1985 if (intermediate_key) {
1986 memset(intermediate_key, 0, intermediate_key_size);
1987 free(intermediate_key);
1988 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001989 return rc;
1990}
1991
Ken Sumrall29d8da82011-05-18 17:20:07 -07001992/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001993 * Called by vold when it's asked to mount an encrypted external
1994 * storage volume. The incoming partition has no crypto header/footer,
1995 * as any metadata is been stored in a separate, small partition.
1996 *
1997 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001998 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001999int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
2000 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002001 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002002 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002003 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002004 return -1;
2005 }
2006
2007 unsigned long nr_sec = 0;
2008 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002009 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002010
Ken Sumrall29d8da82011-05-18 17:20:07 -07002011 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002012 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002013 return -1;
2014 }
2015
Jeff Sharkey9c484982015-03-31 10:35:33 -07002016 struct crypt_mnt_ftr ext_crypt_ftr;
2017 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2018 ext_crypt_ftr.fs_size = nr_sec;
2019 ext_crypt_ftr.keysize = keysize;
2020 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002021
Jeff Sharkey9c484982015-03-31 10:35:33 -07002022 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
2023 out_crypto_blkdev, label);
2024}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002025
Jeff Sharkey9c484982015-03-31 10:35:33 -07002026/*
2027 * Called by vold when it's asked to unmount an encrypted external
2028 * storage volume.
2029 */
2030int cryptfs_revert_ext_volume(const char* label) {
2031 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002032}
2033
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002034int cryptfs_crypto_complete(void)
2035{
2036 return do_crypto_complete("/data");
2037}
2038
Paul Lawrencef4faa572014-01-29 13:31:03 -08002039int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2040{
2041 char encrypted_state[PROPERTY_VALUE_MAX];
2042 property_get("ro.crypto.state", encrypted_state, "");
2043 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2044 SLOGE("encrypted fs already validated or not running with encryption,"
2045 " aborting");
2046 return -1;
2047 }
2048
2049 if (get_crypt_ftr_and_key(crypt_ftr)) {
2050 SLOGE("Error getting crypt footer and key");
2051 return -1;
2052 }
2053
2054 return 0;
2055}
2056
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002057int cryptfs_check_passwd(char *passwd)
2058{
Paul Lawrence05335c32015-03-05 09:46:23 -08002059 SLOGI("cryptfs_check_passwd");
2060 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002061 SLOGE("cryptfs_check_passwd not valid for file encryption");
2062 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002063 }
2064
Paul Lawrencef4faa572014-01-29 13:31:03 -08002065 struct crypt_mnt_ftr crypt_ftr;
2066 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002067
Paul Lawrencef4faa572014-01-29 13:31:03 -08002068 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002069 if (rc) {
2070 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002071 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002072 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002073
Paul Lawrence3bd36d52015-06-09 13:37:44 -07002074 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002075 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2076 if (rc) {
2077 SLOGE("Password did not match");
2078 return rc;
2079 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002080
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002081 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2082 // Here we have a default actual password but a real password
2083 // we must test against the scrypted value
2084 // First, we must delete the crypto block device that
2085 // test_mount_encrypted_fs leaves behind as a side effect
2086 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2087 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2088 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2089 if (rc) {
2090 SLOGE("Default password did not match on reboot encryption");
2091 return rc;
2092 }
2093
2094 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2095 put_crypt_ftr_and_key(&crypt_ftr);
2096 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2097 if (rc) {
2098 SLOGE("Could not change password on reboot encryption");
2099 return rc;
2100 }
2101 }
2102
2103 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002104 cryptfs_clear_password();
2105 password = strdup(passwd);
2106 struct timespec now;
2107 clock_gettime(CLOCK_BOOTTIME, &now);
2108 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002109 }
2110
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002111 return rc;
2112}
2113
Ken Sumrall3ad90722011-10-04 20:38:29 -07002114int cryptfs_verify_passwd(char *passwd)
2115{
2116 struct crypt_mnt_ftr crypt_ftr;
2117 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002118 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002119 char encrypted_state[PROPERTY_VALUE_MAX];
2120 int rc;
2121
2122 property_get("ro.crypto.state", encrypted_state, "");
2123 if (strcmp(encrypted_state, "encrypted") ) {
2124 SLOGE("device not encrypted, aborting");
2125 return -2;
2126 }
2127
2128 if (!master_key_saved) {
2129 SLOGE("encrypted fs not yet mounted, aborting");
2130 return -1;
2131 }
2132
2133 if (!saved_mount_point) {
2134 SLOGE("encrypted fs failed to save mount point, aborting");
2135 return -1;
2136 }
2137
Ken Sumrall160b4d62013-04-22 12:15:39 -07002138 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002139 SLOGE("Error getting crypt footer and key\n");
2140 return -1;
2141 }
2142
2143 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2144 /* If the device has no password, then just say the password is valid */
2145 rc = 0;
2146 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002147 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002148 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2149 /* They match, the password is correct */
2150 rc = 0;
2151 } else {
2152 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2153 sleep(1);
2154 rc = 1;
2155 }
2156 }
2157
2158 return rc;
2159}
2160
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002161/* Initialize a crypt_mnt_ftr structure. The keysize is
2162 * defaulted to 16 bytes, and the filesystem size to 0.
2163 * Presumably, at a minimum, the caller will update the
2164 * filesystem size and crypto_type_name after calling this function.
2165 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002166static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002167{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002168 off64_t off;
2169
2170 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002171 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002172 ftr->major_version = CURRENT_MAJOR_VERSION;
2173 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002174 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002175 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002176
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002177 switch (keymaster_check_compatibility()) {
2178 case 1:
2179 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2180 break;
2181
2182 case 0:
2183 ftr->kdf_type = KDF_SCRYPT;
2184 break;
2185
2186 default:
2187 SLOGE("keymaster_check_compatibility failed");
2188 return -1;
2189 }
2190
Kenny Rootc4c70f12013-06-14 12:11:38 -07002191 get_device_scrypt_params(ftr);
2192
Ken Sumrall160b4d62013-04-22 12:15:39 -07002193 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2194 if (get_crypt_ftr_info(NULL, &off) == 0) {
2195 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2196 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2197 ftr->persist_data_size;
2198 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002199
2200 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002201}
2202
Ken Sumrall29d8da82011-05-18 17:20:07 -07002203static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002204{
Ken Sumralle550f782013-08-20 13:48:23 -07002205 const char *args[10];
2206 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2207 int num_args;
2208 int status;
2209 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002210 int rc = -1;
2211
Ken Sumrall29d8da82011-05-18 17:20:07 -07002212 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002213 args[0] = "/system/bin/make_ext4fs";
2214 args[1] = "-a";
2215 args[2] = "/data";
2216 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002217 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002218 args[4] = size_str;
2219 args[5] = crypto_blkdev;
2220 num_args = 6;
2221 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2222 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002223 } else if (type == F2FS_FS) {
2224 args[0] = "/system/bin/mkfs.f2fs";
2225 args[1] = "-t";
2226 args[2] = "-d1";
2227 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002228 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002229 args[4] = size_str;
2230 num_args = 5;
2231 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2232 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002233 } else {
2234 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2235 return -1;
2236 }
2237
Ken Sumralle550f782013-08-20 13:48:23 -07002238 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2239
2240 if (tmp != 0) {
2241 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002242 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002243 if (WIFEXITED(status)) {
2244 if (WEXITSTATUS(status)) {
2245 SLOGE("Error creating filesystem on %s, exit status %d ",
2246 crypto_blkdev, WEXITSTATUS(status));
2247 } else {
2248 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2249 rc = 0;
2250 }
2251 } else {
2252 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2253 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002254 }
2255
2256 return rc;
2257}
2258
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002259#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002260#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2261#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002262
2263/* aligned 32K writes tends to make flash happy.
2264 * SD card association recommends it.
2265 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002266#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002267#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002268#else
2269#define BLOCKS_AT_A_TIME 1024
2270#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002271
2272struct encryptGroupsData
2273{
2274 int realfd;
2275 int cryptofd;
2276 off64_t numblocks;
2277 off64_t one_pct, cur_pct, new_pct;
2278 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002279 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002280 char* real_blkdev, * crypto_blkdev;
2281 int count;
2282 off64_t offset;
2283 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002284 off64_t last_written_sector;
2285 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002286 time_t time_started;
2287 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002288};
2289
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002290static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002291{
2292 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002293
2294 if (is_used) {
2295 data->used_blocks_already_done++;
2296 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002297 if (data->tot_used_blocks) {
2298 data->new_pct = data->used_blocks_already_done / data->one_pct;
2299 } else {
2300 data->new_pct = data->blocks_already_done / data->one_pct;
2301 }
2302
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002303 if (data->new_pct > data->cur_pct) {
2304 char buf[8];
2305 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002306 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002307 property_set("vold.encrypt_progress", buf);
2308 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002309
2310 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002311 struct timespec time_now;
2312 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2313 SLOGW("Error getting time");
2314 } else {
2315 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2316 off64_t remaining_blocks = data->tot_used_blocks
2317 - data->used_blocks_already_done;
2318 int remaining_time = (int)(elapsed_time * remaining_blocks
2319 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002320
Paul Lawrence9c58a872014-09-30 09:12:51 -07002321 // Change time only if not yet set, lower, or a lot higher for
2322 // best user experience
2323 if (data->remaining_time == -1
2324 || remaining_time < data->remaining_time
2325 || remaining_time > data->remaining_time + 60) {
2326 char buf[8];
2327 snprintf(buf, sizeof(buf), "%d", remaining_time);
2328 property_set("vold.encrypt_time_remaining", buf);
2329 data->remaining_time = remaining_time;
2330 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002331 }
2332 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002333}
2334
Paul Lawrence3846be12014-09-22 11:33:54 -07002335static void log_progress(struct encryptGroupsData const* data, bool completed)
2336{
2337 // Precondition - if completed data = 0 else data != 0
2338
2339 // Track progress so we can skip logging blocks
2340 static off64_t offset = -1;
2341
2342 // Need to close existing 'Encrypting from' log?
2343 if (completed || (offset != -1 && data->offset != offset)) {
2344 SLOGI("Encrypted to sector %" PRId64,
2345 offset / info.block_size * CRYPT_SECTOR_SIZE);
2346 offset = -1;
2347 }
2348
2349 // Need to start new 'Encrypting from' log?
2350 if (!completed && offset != data->offset) {
2351 SLOGI("Encrypting from sector %" PRId64,
2352 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2353 }
2354
2355 // Update offset
2356 if (!completed) {
2357 offset = data->offset + (off64_t)data->count * info.block_size;
2358 }
2359}
2360
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002361static int flush_outstanding_data(struct encryptGroupsData* data)
2362{
2363 if (data->count == 0) {
2364 return 0;
2365 }
2366
Elliott Hughes231bdba2014-06-25 18:36:19 -07002367 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002368
2369 if (pread64(data->realfd, data->buffer,
2370 info.block_size * data->count, data->offset)
2371 <= 0) {
2372 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2373 data->real_blkdev);
2374 return -1;
2375 }
2376
2377 if (pwrite64(data->cryptofd, data->buffer,
2378 info.block_size * data->count, data->offset)
2379 <= 0) {
2380 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2381 data->crypto_blkdev);
2382 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002383 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002384 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002385 }
2386
2387 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002388 data->last_written_sector = (data->offset + data->count)
2389 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002390 return 0;
2391}
2392
2393static int encrypt_groups(struct encryptGroupsData* data)
2394{
2395 unsigned int i;
2396 u8 *block_bitmap = 0;
2397 unsigned int block;
2398 off64_t ret;
2399 int rc = -1;
2400
2401 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2402 if (!data->buffer) {
2403 SLOGE("Failed to allocate crypto buffer");
2404 goto errout;
2405 }
2406
2407 block_bitmap = malloc(info.block_size);
2408 if (!block_bitmap) {
2409 SLOGE("failed to allocate block bitmap");
2410 goto errout;
2411 }
2412
2413 for (i = 0; i < aux_info.groups; ++i) {
2414 SLOGI("Encrypting group %d", i);
2415
2416 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2417 u32 block_count = min(info.blocks_per_group,
2418 aux_info.len_blocks - first_block);
2419
2420 off64_t offset = (u64)info.block_size
2421 * aux_info.bg_desc[i].bg_block_bitmap;
2422
2423 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2424 if (ret != (int)info.block_size) {
2425 SLOGE("failed to read all of block group bitmap %d", i);
2426 goto errout;
2427 }
2428
2429 offset = (u64)info.block_size * first_block;
2430
2431 data->count = 0;
2432
2433 for (block = 0; block < block_count; block++) {
liminghaoaa08e582016-01-06 10:30:49 +08002434 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
2435 0 : bitmap_get_bit(block_bitmap, block);
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002436 update_progress(data, used);
2437 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002438 if (data->count == 0) {
2439 data->offset = offset;
2440 }
2441 data->count++;
2442 } else {
2443 if (flush_outstanding_data(data)) {
2444 goto errout;
2445 }
2446 }
2447
2448 offset += info.block_size;
2449
2450 /* Write data if we are aligned or buffer size reached */
2451 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2452 || data->count == BLOCKS_AT_A_TIME) {
2453 if (flush_outstanding_data(data)) {
2454 goto errout;
2455 }
2456 }
Paul Lawrence87999172014-02-20 12:21:31 -08002457
Paul Lawrence73d7a022014-06-09 14:10:09 -07002458 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002459 SLOGE("Stopping encryption due to low battery");
2460 rc = 0;
2461 goto errout;
2462 }
2463
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002464 }
2465 if (flush_outstanding_data(data)) {
2466 goto errout;
2467 }
2468 }
2469
Paul Lawrence87999172014-02-20 12:21:31 -08002470 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002471 rc = 0;
2472
2473errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002474 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002475 free(data->buffer);
2476 free(block_bitmap);
2477 return rc;
2478}
2479
2480static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2481 char *real_blkdev,
2482 off64_t size,
2483 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002484 off64_t tot_size,
2485 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002486{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002487 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002488 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002489 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002490
Paul Lawrence87999172014-02-20 12:21:31 -08002491 if (previously_encrypted_upto > *size_already_done) {
2492 SLOGD("Not fast encrypting since resuming part way through");
2493 return -1;
2494 }
2495
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002496 memset(&data, 0, sizeof(data));
2497 data.real_blkdev = real_blkdev;
2498 data.crypto_blkdev = crypto_blkdev;
2499
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002500 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002501 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2502 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002503 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002504 goto errout;
2505 }
2506
David Ng82fd8042015-01-21 13:55:21 -08002507 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2508 int retries = RETRY_MOUNT_ATTEMPTS;
2509 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2510 if (--retries) {
2511 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2512 crypto_blkdev, errno, strerror(errno));
2513 sleep(RETRY_MOUNT_DELAY_SECONDS);
2514 } else {
2515 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2516 crypto_blkdev, errno, strerror(errno));
2517 rc = ENABLE_INPLACE_ERR_DEV;
2518 goto errout;
2519 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002520 }
2521
2522 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002523 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002524 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002525 goto errout;
2526 }
2527
2528 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002529 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002530 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002531 goto errout;
2532 }
2533
2534 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2535 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2536 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2537
JP Abgrall7fc1de82014-10-10 18:43:41 -07002538 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002539
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002540 data.tot_used_blocks = data.numblocks;
2541 for (i = 0; i < aux_info.groups; ++i) {
2542 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2543 }
2544
2545 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002546 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002547
2548 struct timespec time_started = {0};
2549 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2550 SLOGW("Error getting time at start");
2551 // Note - continue anyway - we'll run with 0
2552 }
2553 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002554 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002555
2556 rc = encrypt_groups(&data);
2557 if (rc) {
2558 SLOGE("Error encrypting groups");
2559 goto errout;
2560 }
2561
Paul Lawrence87999172014-02-20 12:21:31 -08002562 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002563 rc = 0;
2564
2565errout:
2566 close(data.realfd);
2567 close(data.cryptofd);
2568
2569 return rc;
2570}
2571
Paul Lawrence3846be12014-09-22 11:33:54 -07002572static void log_progress_f2fs(u64 block, bool completed)
2573{
2574 // Precondition - if completed data = 0 else data != 0
2575
2576 // Track progress so we can skip logging blocks
2577 static u64 last_block = (u64)-1;
2578
2579 // Need to close existing 'Encrypting from' log?
2580 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2581 SLOGI("Encrypted to block %" PRId64, last_block);
2582 last_block = -1;
2583 }
2584
2585 // Need to start new 'Encrypting from' log?
2586 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2587 SLOGI("Encrypting from block %" PRId64, block);
2588 }
2589
2590 // Update offset
2591 if (!completed) {
2592 last_block = block;
2593 }
2594}
2595
Daniel Rosenberge82df162014-08-15 22:19:23 +00002596static int encrypt_one_block_f2fs(u64 pos, void *data)
2597{
2598 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2599
2600 priv_dat->blocks_already_done = pos - 1;
2601 update_progress(priv_dat, 1);
2602
2603 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2604
2605 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002606 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002607 return -1;
2608 }
2609
2610 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002611 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002612 return -1;
2613 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002614 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002615 }
2616
2617 return 0;
2618}
2619
2620static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2621 char *real_blkdev,
2622 off64_t size,
2623 off64_t *size_already_done,
2624 off64_t tot_size,
2625 off64_t previously_encrypted_upto)
2626{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002627 struct encryptGroupsData data;
2628 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002629 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002630 if (previously_encrypted_upto > *size_already_done) {
2631 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002632 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002633 }
2634 memset(&data, 0, sizeof(data));
2635 data.real_blkdev = real_blkdev;
2636 data.crypto_blkdev = crypto_blkdev;
2637 data.realfd = -1;
2638 data.cryptofd = -1;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002639 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002640 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002641 real_blkdev);
2642 goto errout;
2643 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002644 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002645 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002646 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002647 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002648 goto errout;
2649 }
2650
2651 f2fs_info = generate_f2fs_info(data.realfd);
2652 if (!f2fs_info)
2653 goto errout;
2654
2655 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2656 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2657 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2658
2659 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2660
2661 data.one_pct = data.tot_used_blocks / 100;
2662 data.cur_pct = 0;
2663 data.time_started = time(NULL);
2664 data.remaining_time = -1;
2665
2666 data.buffer = malloc(f2fs_info->block_size);
2667 if (!data.buffer) {
2668 SLOGE("Failed to allocate crypto buffer");
2669 goto errout;
2670 }
2671
2672 data.count = 0;
2673
2674 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2675 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2676
2677 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002678 SLOGE("Error in running over f2fs blocks");
2679 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002680 goto errout;
2681 }
2682
2683 *size_already_done += size;
2684 rc = 0;
2685
2686errout:
2687 if (rc)
2688 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2689
Paul Lawrence3846be12014-09-22 11:33:54 -07002690 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002691 free(f2fs_info);
2692 free(data.buffer);
2693 close(data.realfd);
2694 close(data.cryptofd);
2695
2696 return rc;
2697}
2698
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002699static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2700 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002701 off64_t tot_size,
2702 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002703{
2704 int realfd, cryptofd;
2705 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002706 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002707 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002708 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002709 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002710
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002711 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002712 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002713 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002714 }
2715
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002716 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002717 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2718 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002719 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002720 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002721 }
2722
2723 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2724 * The size passed in is the number of 512 byte sectors in the filesystem.
2725 * So compute the number of whole 4K blocks we should read/write,
2726 * and the remainder.
2727 */
2728 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2729 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002730 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2731 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002732
2733 SLOGE("Encrypting filesystem in place...");
2734
Paul Lawrence87999172014-02-20 12:21:31 -08002735 i = previously_encrypted_upto + 1 - *size_already_done;
2736
2737 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2738 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2739 goto errout;
2740 }
2741
2742 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2743 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2744 goto errout;
2745 }
2746
2747 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2748 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2749 SLOGE("Error reading initial sectors from real_blkdev %s for "
2750 "inplace encrypt\n", crypto_blkdev);
2751 goto errout;
2752 }
2753 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2754 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2755 "inplace encrypt\n", crypto_blkdev);
2756 goto errout;
2757 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002758 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002759 }
2760 }
2761
Ken Sumrall29d8da82011-05-18 17:20:07 -07002762 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002763 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002764 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002765 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002766 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002767 if (new_pct > cur_pct) {
2768 char buf[8];
2769
2770 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002771 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002772 property_set("vold.encrypt_progress", buf);
2773 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002774 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002775 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002776 goto errout;
2777 }
2778 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002779 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2780 goto errout;
2781 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002782 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002783 CRYPT_SECTORS_PER_BUFSIZE,
2784 i * CRYPT_SECTORS_PER_BUFSIZE);
2785 }
2786
Paul Lawrence73d7a022014-06-09 14:10:09 -07002787 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002788 SLOGE("Stopping encryption due to low battery");
2789 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2790 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002791 goto errout;
2792 }
2793 }
2794
2795 /* Do any remaining sectors */
2796 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002797 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2798 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002799 goto errout;
2800 }
Paul Lawrence87999172014-02-20 12:21:31 -08002801 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2802 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002803 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002804 } else {
2805 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002806 }
2807 }
2808
Ken Sumrall29d8da82011-05-18 17:20:07 -07002809 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002810 rc = 0;
2811
2812errout:
2813 close(realfd);
2814 close(cryptofd);
2815
2816 return rc;
2817}
2818
JP Abgrall7fc1de82014-10-10 18:43:41 -07002819/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002820static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2821 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002822 off64_t tot_size,
2823 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002824{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002825 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002826 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002827 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002828 }
2829
2830 if (*size_already_done + size < previously_encrypted_upto) {
2831 *size_already_done += size;
2832 return 0;
2833 }
2834
Daniel Rosenberge82df162014-08-15 22:19:23 +00002835 /* TODO: identify filesystem type.
2836 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2837 * then we will drop down to cryptfs_enable_inplace_f2fs.
2838 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002839 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002840 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002841 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002842 return 0;
2843 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002844 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002845
JP Abgrall7fc1de82014-10-10 18:43:41 -07002846 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002847 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002848 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002849 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002850 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002851 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002852
JP Abgrall7fc1de82014-10-10 18:43:41 -07002853 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002854 size, size_already_done, tot_size,
2855 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002856 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2857
2858 /* Hack for b/17898962, the following is the symptom... */
2859 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2860 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2861 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2862 return ENABLE_INPLACE_ERR_DEV;
2863 }
2864 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002865}
2866
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002867#define CRYPTO_ENABLE_WIPE 1
2868#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002869
2870#define FRAMEWORK_BOOT_WAIT 60
2871
Paul Lawrence87999172014-02-20 12:21:31 -08002872static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2873{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002874 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002875 if (fd == -1) {
2876 SLOGE("Error opening file %s", filename);
2877 return -1;
2878 }
2879
2880 char block[CRYPT_INPLACE_BUFSIZE];
2881 memset(block, 0, sizeof(block));
2882 if (unix_read(fd, block, sizeof(block)) < 0) {
2883 SLOGE("Error reading file %s", filename);
2884 close(fd);
2885 return -1;
2886 }
2887
2888 close(fd);
2889
2890 SHA256_CTX c;
2891 SHA256_Init(&c);
2892 SHA256_Update(&c, block, sizeof(block));
2893 SHA256_Final(buf, &c);
2894
2895 return 0;
2896}
2897
JP Abgrall62c7af32014-06-16 13:01:23 -07002898static int get_fs_type(struct fstab_rec *rec)
2899{
2900 if (!strcmp(rec->fs_type, "ext4")) {
2901 return EXT4_FS;
2902 } else if (!strcmp(rec->fs_type, "f2fs")) {
2903 return F2FS_FS;
2904 } else {
2905 return -1;
2906 }
2907}
2908
Paul Lawrence87999172014-02-20 12:21:31 -08002909static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2910 char *crypto_blkdev, char *real_blkdev,
2911 int previously_encrypted_upto)
2912{
2913 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002914 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002915
Paul Lawrence73d7a022014-06-09 14:10:09 -07002916 if (!is_battery_ok_to_start()) {
2917 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002918 return 0;
2919 }
2920
2921 /* The size of the userdata partition, and add in the vold volumes below */
2922 tot_encryption_size = crypt_ftr->fs_size;
2923
2924 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002925 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2926 int fs_type = get_fs_type(rec);
2927 if (fs_type < 0) {
2928 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2929 return -1;
2930 }
2931 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002932 } else if (how == CRYPTO_ENABLE_INPLACE) {
2933 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2934 crypt_ftr->fs_size, &cur_encryption_done,
2935 tot_encryption_size,
2936 previously_encrypted_upto);
2937
JP Abgrall7fc1de82014-10-10 18:43:41 -07002938 if (rc == ENABLE_INPLACE_ERR_DEV) {
2939 /* Hack for b/17898962 */
2940 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2941 cryptfs_reboot(reboot);
2942 }
2943
Paul Lawrence73d7a022014-06-09 14:10:09 -07002944 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002945 crypt_ftr->encrypted_upto = cur_encryption_done;
2946 }
2947
Paul Lawrence73d7a022014-06-09 14:10:09 -07002948 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002949 /* The inplace routine never actually sets the progress to 100% due
2950 * to the round down nature of integer division, so set it here */
2951 property_set("vold.encrypt_progress", "100");
2952 }
2953 } else {
2954 /* Shouldn't happen */
2955 SLOGE("cryptfs_enable: internal error, unknown option\n");
2956 rc = -1;
2957 }
2958
2959 return rc;
2960}
2961
Paul Lawrence13486032014-02-03 13:28:11 -08002962int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002963 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002964{
2965 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002966 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002967 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002968 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002969 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002970 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002971 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002972 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002973 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002974 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002975 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002976 bool rebootEncryption = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002977
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002978 if (!strcmp(howarg, "wipe")) {
2979 how = CRYPTO_ENABLE_WIPE;
2980 } else if (! strcmp(howarg, "inplace")) {
2981 how = CRYPTO_ENABLE_INPLACE;
2982 } else {
2983 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002984 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002985 }
2986
Paul Lawrence87999172014-02-20 12:21:31 -08002987 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002988 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2989 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2990 /* An encryption was underway and was interrupted */
2991 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2992 crypt_ftr.encrypted_upto = 0;
2993 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002994
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002995 /* At this point, we are in an inconsistent state. Until we successfully
2996 complete encryption, a reboot will leave us broken. So mark the
2997 encryption failed in case that happens.
2998 On successfully completing encryption, remove this flag */
2999 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07003000
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003001 put_crypt_ftr_and_key(&crypt_ftr);
3002 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
3003 if (!check_ftr_sha(&crypt_ftr)) {
3004 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
3005 put_crypt_ftr_and_key(&crypt_ftr);
3006 goto error_unencrypted;
3007 }
3008
3009 /* Doing a reboot-encryption*/
3010 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
3011 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
3012 rebootEncryption = true;
3013 }
Paul Lawrence87999172014-02-20 12:21:31 -08003014 }
3015
3016 property_get("ro.crypto.state", encrypted_state, "");
3017 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
3018 SLOGE("Device is already running encrypted, aborting");
3019 goto error_unencrypted;
3020 }
3021
3022 // TODO refactor fs_mgr_get_crypt_info to get both in one call
3023 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08003024 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003025
Ken Sumrall3ed82362011-01-28 23:31:16 -08003026 /* Get the size of the real block device */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003027 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09003028 if (fd == -1) {
3029 SLOGE("Cannot open block device %s\n", real_blkdev);
3030 goto error_unencrypted;
3031 }
3032 unsigned long nr_sec;
3033 get_blkdev_size(fd, &nr_sec);
3034 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003035 SLOGE("Cannot get size of block device %s\n", real_blkdev);
3036 goto error_unencrypted;
3037 }
3038 close(fd);
3039
3040 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003041 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003042 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00003043 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00003044 if (fs_size_sec == 0)
3045 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3046
Paul Lawrence87999172014-02-20 12:21:31 -08003047 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003048
3049 if (fs_size_sec > max_fs_size_sec) {
3050 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3051 goto error_unencrypted;
3052 }
3053 }
3054
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003055 /* Get a wakelock as this may take a while, and we don't want the
3056 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3057 * wants to keep the screen on, it can grab a full wakelock.
3058 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003059 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003060 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3061
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003062 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003063 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003064 */
3065 property_set("vold.decrypt", "trigger_shutdown_framework");
3066 SLOGD("Just asked init to shut down class main\n");
3067
Jeff Sharkey9c484982015-03-31 10:35:33 -07003068 /* Ask vold to unmount all devices that it manages */
3069 if (vold_unmountAll()) {
3070 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003071 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003072
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003073 /* no_ui means we are being called from init, not settings.
3074 Now we always reboot from settings, so !no_ui means reboot
3075 */
3076 bool onlyCreateHeader = false;
3077 if (!no_ui) {
3078 /* Try fallback, which is to reboot and try there */
3079 onlyCreateHeader = true;
3080 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
3081 if (breadcrumb == 0) {
3082 SLOGE("Failed to create breadcrumb file");
3083 goto error_shutting_down;
3084 }
3085 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003086 }
3087
3088 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003089 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003090 /* Now that /data is unmounted, we need to mount a tmpfs
3091 * /data, set a property saying we're doing inplace encryption,
3092 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003093 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003094 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003095 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003096 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003097 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003098 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003099
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003100 /* restart the framework. */
3101 /* Create necessary paths on /data */
3102 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003103 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003104 }
3105
Ken Sumrall92736ef2012-10-17 20:57:14 -07003106 /* Ugh, shutting down the framework is not synchronous, so until it
3107 * can be fixed, this horrible hack will wait a moment for it all to
3108 * shut down before proceeding. Without it, some devices cannot
3109 * restart the graphics services.
3110 */
3111 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003112 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003113
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003114 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003115 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003116 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003117 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3118 goto error_shutting_down;
3119 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003120
Paul Lawrence87999172014-02-20 12:21:31 -08003121 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3122 crypt_ftr.fs_size = nr_sec
3123 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3124 } else {
3125 crypt_ftr.fs_size = nr_sec;
3126 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003127 /* At this point, we are in an inconsistent state. Until we successfully
3128 complete encryption, a reboot will leave us broken. So mark the
3129 encryption failed in case that happens.
3130 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003131 if (onlyCreateHeader) {
3132 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
3133 } else {
3134 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3135 }
Paul Lawrence87999172014-02-20 12:21:31 -08003136 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003137#ifndef CONFIG_HW_DISK_ENCRYPTION
3138 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3139#else
3140 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3141
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003142 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003143 if (!rc) {
3144 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3145 }
3146
3147 rc = set_hw_device_encryption_key(passwd,
3148 (char*) crypt_ftr.crypto_type_name);
3149 if (!rc) {
3150 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3151 goto error_shutting_down;
3152 }
3153#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003154
Paul Lawrence87999172014-02-20 12:21:31 -08003155 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003156 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
3157 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08003158 SLOGE("Cannot create encrypted master key\n");
3159 goto error_shutting_down;
3160 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003161
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003162 /* Replace scrypted intermediate key if we are preparing for a reboot */
3163 if (onlyCreateHeader) {
3164 unsigned char fake_master_key[KEY_LEN_BYTES];
3165 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
3166 memset(fake_master_key, 0, sizeof(fake_master_key));
3167 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
3168 encrypted_fake_master_key, &crypt_ftr);
3169 }
3170
Paul Lawrence87999172014-02-20 12:21:31 -08003171 /* Write the key to the end of the partition */
3172 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003173
Paul Lawrence87999172014-02-20 12:21:31 -08003174 /* If any persistent data has been remembered, save it.
3175 * If none, create a valid empty table and save that.
3176 */
3177 if (!persist_data) {
3178 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3179 if (pdata) {
3180 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3181 persist_data = pdata;
3182 }
3183 }
3184 if (persist_data) {
3185 save_persistent_data();
3186 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003187 }
3188
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003189 if (onlyCreateHeader) {
3190 sleep(2);
3191 cryptfs_reboot(reboot);
3192 }
3193
3194 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07003195 /* startup service classes main and late_start */
3196 property_set("vold.decrypt", "trigger_restart_min_framework");
3197 SLOGD("Just triggered restart_min_framework\n");
3198
3199 /* OK, the framework is restarted and will soon be showing a
3200 * progress bar. Time to setup an encrypted mapping, and
3201 * either write a new filesystem, or encrypt in place updating
3202 * the progress bar as we work.
3203 */
3204 }
3205
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003206 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003207 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003208 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003209
Paul Lawrence87999172014-02-20 12:21:31 -08003210 /* If we are continuing, check checksums match */
3211 rc = 0;
3212 if (previously_encrypted_upto) {
3213 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3214 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003215
Paul Lawrence87999172014-02-20 12:21:31 -08003216 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3217 sizeof(hash_first_block)) != 0) {
3218 SLOGE("Checksums do not match - trigger wipe");
3219 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003220 }
3221 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003222
Paul Lawrence87999172014-02-20 12:21:31 -08003223 if (!rc) {
3224 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3225 crypto_blkdev, real_blkdev,
3226 previously_encrypted_upto);
3227 }
3228
3229 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003230 if (!rc && how == CRYPTO_ENABLE_INPLACE
3231 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003232 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3233 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003234 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003235 SLOGE("Error calculating checksum for continuing encryption");
3236 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003237 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003238 }
3239
3240 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003241 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003242
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003243 if (! rc) {
3244 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003245 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003246
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003247 if (how == CRYPTO_ENABLE_INPLACE
3248 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003249 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3250 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003251 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003252 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003253
Paul Lawrence6bfed202014-07-28 12:47:22 -07003254 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003255
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003256 if (how == CRYPTO_ENABLE_WIPE
3257 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003258 char value[PROPERTY_VALUE_MAX];
3259 property_get("ro.crypto.state", value, "");
3260 if (!strcmp(value, "")) {
3261 /* default encryption - continue first boot sequence */
3262 property_set("ro.crypto.state", "encrypted");
3263 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003264 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
3265 // Bring up cryptkeeper that will check the password and set it
3266 property_set("vold.decrypt", "trigger_shutdown_framework");
3267 sleep(2);
3268 property_set("vold.encrypt_progress", "");
3269 cryptfs_trigger_restart_min_framework();
3270 } else {
3271 cryptfs_check_passwd(DEFAULT_PASSWORD);
3272 cryptfs_restart_internal(1);
3273 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003274 return 0;
3275 } else {
3276 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003277 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003278 }
Paul Lawrence87999172014-02-20 12:21:31 -08003279 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003280 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003281 cryptfs_reboot(shutdown);
3282 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003283 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003284 char value[PROPERTY_VALUE_MAX];
3285
Ken Sumrall319369a2012-06-27 16:30:18 -07003286 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003287 if (!strcmp(value, "1")) {
3288 /* wipe data if encryption failed */
3289 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3290 mkdir("/cache/recovery", 0700);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003291 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003292 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003293 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3294 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003295 close(fd);
3296 } else {
3297 SLOGE("could not open /cache/recovery/command\n");
3298 }
Paul Lawrence87999172014-02-20 12:21:31 -08003299 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003300 } else {
3301 /* set property to trigger dialog */
3302 property_set("vold.encrypt_progress", "error_partially_encrypted");
3303 release_wake_lock(lockid);
3304 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003305 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003306 }
3307
Ken Sumrall3ed82362011-01-28 23:31:16 -08003308 /* hrm, the encrypt step claims success, but the reboot failed.
3309 * This should not happen.
3310 * Set the property and return. Hope the framework can deal with it.
3311 */
3312 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003313 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003314 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003315
3316error_unencrypted:
3317 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003318 if (lockid[0]) {
3319 release_wake_lock(lockid);
3320 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003321 return -1;
3322
3323error_shutting_down:
3324 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3325 * but the framework is stopped and not restarted to show the error, so it's up to
3326 * vold to restart the system.
3327 */
3328 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003329 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003330
3331 /* shouldn't get here */
3332 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003333 if (lockid[0]) {
3334 release_wake_lock(lockid);
3335 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003336 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003337}
3338
Paul Lawrence569649f2015-09-09 12:13:00 -07003339int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003340{
Paul Lawrence569649f2015-09-09 12:13:00 -07003341 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003342}
3343
Paul Lawrence569649f2015-09-09 12:13:00 -07003344int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003345{
3346 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07003347 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003348}
3349
3350int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003351{
Paul Lawrence05335c32015-03-05 09:46:23 -08003352 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003353 SLOGE("cryptfs_changepw not valid for file encryption");
3354 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003355 }
3356
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003357 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003358 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003359
3360 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003361 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003362 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003363 return -1;
3364 }
3365
Paul Lawrencef4faa572014-01-29 13:31:03 -08003366 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3367 SLOGE("Invalid crypt_type %d", crypt_type);
3368 return -1;
3369 }
3370
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003371 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003372 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003373 SLOGE("Error getting crypt footer and key");
3374 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003375 }
3376
Paul Lawrencef4faa572014-01-29 13:31:03 -08003377 crypt_ftr.crypt_type = crypt_type;
3378
JP Abgrall933216c2015-02-11 13:44:32 -08003379 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003380 : newpw,
3381 crypt_ftr.salt,
3382 saved_master_key,
3383 crypt_ftr.master_key,
3384 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003385 if (rc) {
3386 SLOGE("Encrypt master key failed: %d", rc);
3387 return -1;
3388 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003389 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003390 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003391
Ajay Dudani87701e22014-09-17 21:02:52 -07003392#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003393 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3394 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3395 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3396 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3397 if (!rc)
3398 return -1;
3399 } else {
3400 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3401 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3402 if (!rc)
3403 return -1;
3404 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003405 }
3406#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003407 return 0;
3408}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003409
Rubin Xu85c01f92014-10-13 12:49:54 +01003410static unsigned int persist_get_max_entries(int encrypted) {
3411 struct crypt_mnt_ftr crypt_ftr;
3412 unsigned int dsize;
3413 unsigned int max_persistent_entries;
3414
3415 /* If encrypted, use the values from the crypt_ftr, otherwise
3416 * use the values for the current spec.
3417 */
3418 if (encrypted) {
3419 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3420 return -1;
3421 }
3422 dsize = crypt_ftr.persist_data_size;
3423 } else {
3424 dsize = CRYPT_PERSIST_DATA_SIZE;
3425 }
3426
3427 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3428 sizeof(struct crypt_persist_entry);
3429
3430 return max_persistent_entries;
3431}
3432
3433static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003434{
3435 unsigned int i;
3436
3437 if (persist_data == NULL) {
3438 return -1;
3439 }
3440 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3441 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3442 /* We found it! */
3443 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3444 return 0;
3445 }
3446 }
3447
3448 return -1;
3449}
3450
Rubin Xu85c01f92014-10-13 12:49:54 +01003451static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003452{
3453 unsigned int i;
3454 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003455 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003456
3457 if (persist_data == NULL) {
3458 return -1;
3459 }
3460
Rubin Xu85c01f92014-10-13 12:49:54 +01003461 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003462
3463 num = persist_data->persist_valid_entries;
3464
3465 for (i = 0; i < num; i++) {
3466 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3467 /* We found an existing entry, update it! */
3468 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3469 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3470 return 0;
3471 }
3472 }
3473
3474 /* We didn't find it, add it to the end, if there is room */
3475 if (persist_data->persist_valid_entries < max_persistent_entries) {
3476 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3477 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3478 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3479 persist_data->persist_valid_entries++;
3480 return 0;
3481 }
3482
3483 return -1;
3484}
3485
Rubin Xu85c01f92014-10-13 12:49:54 +01003486/**
3487 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3488 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3489 */
3490static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003491 unsigned int field_len;
3492 unsigned int key_index;
3493 field_len = strlen(field);
3494
3495 if (index == 0) {
3496 // The first key in a multi-entry field is just the filedname itself.
3497 if (!strcmp(key, field)) {
3498 return 1;
3499 }
3500 }
3501 // Match key against "%s_%d" % (field, index)
3502 if (strlen(key) < field_len + 1 + 1) {
3503 // Need at least a '_' and a digit.
3504 return 0;
3505 }
3506 if (strncmp(key, field, field_len)) {
3507 // If the key does not begin with field, it's not a match.
3508 return 0;
3509 }
3510 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3511 return 0;
3512 }
3513 return key_index >= index;
3514}
3515
3516/*
3517 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3518 * remaining entries starting from index will be deleted.
3519 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3520 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3521 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3522 *
3523 */
3524static int persist_del_keys(const char *fieldname, unsigned index)
3525{
3526 unsigned int i;
3527 unsigned int j;
3528 unsigned int num;
3529
3530 if (persist_data == NULL) {
3531 return PERSIST_DEL_KEY_ERROR_OTHER;
3532 }
3533
3534 num = persist_data->persist_valid_entries;
3535
3536 j = 0; // points to the end of non-deleted entries.
3537 // Filter out to-be-deleted entries in place.
3538 for (i = 0; i < num; i++) {
3539 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3540 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3541 j++;
3542 }
3543 }
3544
3545 if (j < num) {
3546 persist_data->persist_valid_entries = j;
3547 // Zeroise the remaining entries
3548 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3549 return PERSIST_DEL_KEY_OK;
3550 } else {
3551 // Did not find an entry matching the given fieldname
3552 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3553 }
3554}
3555
3556static int persist_count_keys(const char *fieldname)
3557{
3558 unsigned int i;
3559 unsigned int count;
3560
3561 if (persist_data == NULL) {
3562 return -1;
3563 }
3564
3565 count = 0;
3566 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3567 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3568 count++;
3569 }
3570 }
3571
3572 return count;
3573}
3574
Ken Sumrall160b4d62013-04-22 12:15:39 -07003575/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003576int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003577{
Paul Lawrence368d7942015-04-15 14:12:00 -07003578 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003579 SLOGE("Cannot get field when file encrypted");
3580 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003581 }
3582
Ken Sumrall160b4d62013-04-22 12:15:39 -07003583 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003584 /* CRYPTO_GETFIELD_OK is success,
3585 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3586 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3587 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003588 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003589 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3590 int i;
3591 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003592
3593 if (persist_data == NULL) {
3594 load_persistent_data();
3595 if (persist_data == NULL) {
3596 SLOGE("Getfield error, cannot load persistent data");
3597 goto out;
3598 }
3599 }
3600
Rubin Xu85c01f92014-10-13 12:49:54 +01003601 // Read value from persistent entries. If the original value is split into multiple entries,
3602 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003603 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003604 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3605 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3606 // value too small
3607 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3608 goto out;
3609 }
3610 rc = CRYPTO_GETFIELD_OK;
3611
3612 for (i = 1; /* break explicitly */; i++) {
3613 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3614 (int) sizeof(temp_field)) {
3615 // If the fieldname is very long, we stop as soon as it begins to overflow the
3616 // maximum field length. At this point we have in fact fully read out the original
3617 // value because cryptfs_setfield would not allow fields with longer names to be
3618 // written in the first place.
3619 break;
3620 }
3621 if (!persist_get_key(temp_field, temp_value)) {
3622 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3623 // value too small.
3624 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3625 goto out;
3626 }
3627 } else {
3628 // Exhaust all entries.
3629 break;
3630 }
3631 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003632 } else {
3633 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003634 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003635 }
3636
3637out:
3638 return rc;
3639}
3640
3641/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003642int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003643{
Paul Lawrence368d7942015-04-15 14:12:00 -07003644 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003645 SLOGE("Cannot set field when file encrypted");
3646 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003647 }
3648
Ken Sumrall160b4d62013-04-22 12:15:39 -07003649 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003650 /* 0 is success, negative values are error */
3651 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003652 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003653 unsigned int field_id;
3654 char temp_field[PROPERTY_KEY_MAX];
3655 unsigned int num_entries;
3656 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003657
3658 if (persist_data == NULL) {
3659 load_persistent_data();
3660 if (persist_data == NULL) {
3661 SLOGE("Setfield error, cannot load persistent data");
3662 goto out;
3663 }
3664 }
3665
3666 property_get("ro.crypto.state", encrypted_state, "");
3667 if (!strcmp(encrypted_state, "encrypted") ) {
3668 encrypted = 1;
3669 }
3670
Rubin Xu85c01f92014-10-13 12:49:54 +01003671 // Compute the number of entries required to store value, each entry can store up to
3672 // (PROPERTY_VALUE_MAX - 1) chars
3673 if (strlen(value) == 0) {
3674 // Empty value also needs one entry to store.
3675 num_entries = 1;
3676 } else {
3677 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3678 }
3679
3680 max_keylen = strlen(fieldname);
3681 if (num_entries > 1) {
3682 // Need an extra "_%d" suffix.
3683 max_keylen += 1 + log10(num_entries);
3684 }
3685 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3686 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003687 goto out;
3688 }
3689
Rubin Xu85c01f92014-10-13 12:49:54 +01003690 // Make sure we have enough space to write the new value
3691 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3692 persist_get_max_entries(encrypted)) {
3693 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3694 goto out;
3695 }
3696
3697 // Now that we know persist_data has enough space for value, let's delete the old field first
3698 // to make up space.
3699 persist_del_keys(fieldname, 0);
3700
3701 if (persist_set_key(fieldname, value, encrypted)) {
3702 // fail to set key, should not happen as we have already checked the available space
3703 SLOGE("persist_set_key() error during setfield()");
3704 goto out;
3705 }
3706
3707 for (field_id = 1; field_id < num_entries; field_id++) {
3708 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3709
3710 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3711 // fail to set key, should not happen as we have already checked the available space.
3712 SLOGE("persist_set_key() error during setfield()");
3713 goto out;
3714 }
3715 }
3716
Ken Sumrall160b4d62013-04-22 12:15:39 -07003717 /* If we are running encrypted, save the persistent data now */
3718 if (encrypted) {
3719 if (save_persistent_data()) {
3720 SLOGE("Setfield error, cannot save persistent data");
3721 goto out;
3722 }
3723 }
3724
Rubin Xu85c01f92014-10-13 12:49:54 +01003725 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003726
3727out:
3728 return rc;
3729}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003730
3731/* Checks userdata. Attempt to mount the volume if default-
3732 * encrypted.
3733 * On success trigger next init phase and return 0.
3734 * Currently do not handle failure - see TODO below.
3735 */
3736int cryptfs_mount_default_encrypted(void)
3737{
3738 char decrypt_state[PROPERTY_VALUE_MAX];
3739 property_get("vold.decrypt", decrypt_state, "0");
3740 if (!strcmp(decrypt_state, "0")) {
3741 SLOGE("Not encrypted - should not call here");
3742 } else {
3743 int crypt_type = cryptfs_get_password_type();
3744 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3745 SLOGE("Bad crypt type - error");
3746 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3747 SLOGD("Password is not default - "
3748 "starting min framework to prompt");
3749 property_set("vold.decrypt", "trigger_restart_min_framework");
3750 return 0;
3751 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3752 SLOGD("Password is default - restarting filesystem");
3753 cryptfs_restart_internal(0);
3754 return 0;
3755 } else {
3756 SLOGE("Encrypted, default crypt type but can't decrypt");
3757 }
3758 }
3759
Paul Lawrence6bfed202014-07-28 12:47:22 -07003760 /** Corrupt. Allow us to boot into framework, which will detect bad
3761 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003762 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003763 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003764 return 0;
3765}
3766
3767/* Returns type of the password, default, pattern, pin or password.
3768 */
3769int cryptfs_get_password_type(void)
3770{
Paul Lawrence05335c32015-03-05 09:46:23 -08003771 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003772 SLOGE("cryptfs_get_password_type not valid for file encryption");
3773 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003774 }
3775
Paul Lawrencef4faa572014-01-29 13:31:03 -08003776 struct crypt_mnt_ftr crypt_ftr;
3777
3778 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3779 SLOGE("Error getting crypt footer and key\n");
3780 return -1;
3781 }
3782
Paul Lawrence6bfed202014-07-28 12:47:22 -07003783 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3784 return -1;
3785 }
3786
Paul Lawrencef4faa572014-01-29 13:31:03 -08003787 return crypt_ftr.crypt_type;
3788}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003789
Paul Lawrence05335c32015-03-05 09:46:23 -08003790const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003791{
Paul Lawrence05335c32015-03-05 09:46:23 -08003792 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003793 SLOGE("cryptfs_get_password not valid for file encryption");
3794 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003795 }
3796
Paul Lawrence399317e2014-03-10 13:20:50 -07003797 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003798 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003799 if (now.tv_sec < password_expiry_time) {
3800 return password;
3801 } else {
3802 cryptfs_clear_password();
3803 return 0;
3804 }
3805}
3806
3807void cryptfs_clear_password()
3808{
3809 if (password) {
3810 size_t len = strlen(password);
3811 memset(password, 0, len);
3812 free(password);
3813 password = 0;
3814 password_expiry_time = 0;
3815 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003816}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003817
3818int cryptfs_enable_file()
3819{
3820 return e4crypt_enable(DATA_MNT_POINT);
3821}
3822
Paul Lawrence0c247462015-10-29 10:30:57 -07003823int cryptfs_isConvertibleToFBE()
3824{
3825 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3826 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
3827}
3828
Paul Lawrence731a7a22015-04-28 22:14:15 +00003829int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3830{
3831 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3832 SLOGE("Failed to initialize crypt_ftr");
3833 return -1;
3834 }
3835
3836 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3837 crypt_ftr->salt, crypt_ftr)) {
3838 SLOGE("Cannot create encrypted master key\n");
3839 return -1;
3840 }
3841
3842 //crypt_ftr->keysize = key_length / 8;
3843 return 0;
3844}
3845
3846int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3847 unsigned char* master_key)
3848{
3849 int rc;
3850
Paul Lawrence731a7a22015-04-28 22:14:15 +00003851 unsigned char* intermediate_key = 0;
3852 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003853
3854 if (password == 0 || *password == 0) {
3855 password = DEFAULT_PASSWORD;
3856 }
3857
Paul Lawrence731a7a22015-04-28 22:14:15 +00003858 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3859 &intermediate_key_size);
3860
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003861 int N = 1 << ftr->N_factor;
3862 int r = 1 << ftr->r_factor;
3863 int p = 1 << ftr->p_factor;
3864
3865 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3866
3867 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3868 ftr->salt, sizeof(ftr->salt), N, r, p,
3869 scrypted_intermediate_key,
3870 sizeof(scrypted_intermediate_key));
3871
3872 free(intermediate_key);
3873
3874 if (rc) {
3875 SLOGE("Can't calculate intermediate key");
3876 return rc;
3877 }
3878
3879 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3880 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00003881}
3882
3883int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3884 const unsigned char* master_key)
3885{
3886 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3887 ftr);
3888}