blob: f6698f6260df93ad7a3ddf8518a47ee7d492e11f [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Tao Bao989fec22016-10-05 18:01:19 -070041#include <ext4_utils/ext4.h>
42#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070058#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070059#include "crypto_scrypt.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000060#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000061#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080062#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080063#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080064
Yabin Cui1fb59662016-06-24 14:48:49 -070065#include <bootloader_message/bootloader_message.h>
Shawn Willden8af33352015-02-24 09:51:34 -070066#include <hardware/keymaster0.h>
Shawn Willdenda6e8992015-06-03 09:40:45 -060067#include <hardware/keymaster1.h>
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070068
Mark Salyzyn3e971272014-01-21 13:27:04 -080069#define UNUSED __attribute__((unused))
70
Mark Salyzyn5eecc442014-02-12 14:16:14 -080071#define UNUSED __attribute__((unused))
72
Ajay Dudani87701e22014-09-17 21:02:52 -070073#ifdef CONFIG_HW_DISK_ENCRYPTION
74#include "cryptfs_hw.h"
75#endif
76
Ken Sumrall8f869aa2010-12-03 03:47:09 -080077#define DM_CRYPT_BUF_SIZE 4096
78
Jason parks70a4b3f2011-01-28 10:10:47 -060079#define HASH_COUNT 2000
80#define KEY_LEN_BYTES 16
81#define IV_LEN_BYTES 16
82
Ken Sumrall29d8da82011-05-18 17:20:07 -070083#define KEY_IN_FOOTER "footer"
84
Paul Lawrence3bd36d52015-06-09 13:37:44 -070085#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080086
Paul Lawrence3d99eba2015-11-20 07:07:19 -080087#define CRYPTO_BLOCK_DEVICE "userdata"
88
89#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
90
Ken Sumrall29d8da82011-05-18 17:20:07 -070091#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070092#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070093
Ken Sumralle919efe2012-09-29 17:07:41 -070094#define TABLE_LOAD_RETRIES 10
95
Shawn Willden47ba10d2014-09-03 17:07:06 -060096#define RSA_KEY_SIZE 2048
97#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
98#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060099#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700100
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700101#define RETRY_MOUNT_ATTEMPTS 10
102#define RETRY_MOUNT_DELAY_SECONDS 1
103
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800104char *me = "cryptfs";
105
Jason parks70a4b3f2011-01-28 10:10:47 -0600106static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700107static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600108static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700109static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800110
Shawn Willdenda6e8992015-06-03 09:40:45 -0600111static int keymaster_init(keymaster0_device_t **keymaster0_dev,
112 keymaster1_device_t **keymaster1_dev)
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700113{
114 int rc;
115
116 const hw_module_t* mod;
117 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
118 if (rc) {
119 ALOGE("could not find any keystore module");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600120 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700121 }
122
Shawn Willdenda6e8992015-06-03 09:40:45 -0600123 SLOGI("keymaster module name is %s", mod->name);
124 SLOGI("keymaster version is %d", mod->module_api_version);
125
126 *keymaster0_dev = NULL;
127 *keymaster1_dev = NULL;
128 if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
129 SLOGI("Found keymaster1 module, using keymaster1 API.");
130 rc = keymaster1_open(mod, keymaster1_dev);
131 } else {
132 SLOGI("Found keymaster0 module, using keymaster0 API.");
133 rc = keymaster0_open(mod, keymaster0_dev);
134 }
135
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700136 if (rc) {
137 ALOGE("could not open keymaster device in %s (%s)",
Shawn Willdenda6e8992015-06-03 09:40:45 -0600138 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
139 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700140 }
141
142 return 0;
143
Shawn Willdenda6e8992015-06-03 09:40:45 -0600144err:
145 *keymaster0_dev = NULL;
146 *keymaster1_dev = NULL;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700147 return rc;
148}
149
150/* Should we use keymaster? */
151static int keymaster_check_compatibility()
152{
Shawn Willdenda6e8992015-06-03 09:40:45 -0600153 keymaster0_device_t *keymaster0_dev = 0;
154 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700155 int rc = 0;
156
Shawn Willdenda6e8992015-06-03 09:40:45 -0600157 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700158 SLOGE("Failed to init keymaster");
159 rc = -1;
160 goto out;
161 }
162
Shawn Willdenda6e8992015-06-03 09:40:45 -0600163 if (keymaster1_dev) {
164 rc = 1;
165 goto out;
166 }
Paul Lawrence8c008392014-05-06 14:02:48 -0700167
Paul Lawrence300dae72016-03-11 11:02:52 -0800168 if (!keymaster0_dev || !keymaster0_dev->common.module) {
169 rc = -1;
170 goto out;
171 }
172
Shawn Willdenda6e8992015-06-03 09:40:45 -0600173 // TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
174 // should work.
175 if (keymaster0_dev->common.module->module_api_version
Paul Lawrence8c008392014-05-06 14:02:48 -0700176 < KEYMASTER_MODULE_API_VERSION_0_3) {
177 rc = 0;
178 goto out;
179 }
180
Shawn Willdenda6e8992015-06-03 09:40:45 -0600181 if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
182 (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700183 rc = 1;
184 }
185
186out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600187 if (keymaster1_dev) {
188 keymaster1_close(keymaster1_dev);
189 }
190 if (keymaster0_dev) {
191 keymaster0_close(keymaster0_dev);
192 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700193 return rc;
194}
195
196/* Create a new keymaster key and store it in this footer */
197static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
198{
199 uint8_t* key = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600200 keymaster0_device_t *keymaster0_dev = 0;
201 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700202
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800203 if (ftr->keymaster_blob_size) {
204 SLOGI("Already have key");
205 return 0;
206 }
207
Shawn Willdenda6e8992015-06-03 09:40:45 -0600208 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700209 SLOGE("Failed to init keymaster");
210 return -1;
211 }
212
213 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600214 size_t key_size = 0;
215 if (keymaster1_dev) {
216 keymaster_key_param_t params[] = {
217 /* Algorithm & size specifications. Stick with RSA for now. Switch to AES later. */
218 keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
219 keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
220 keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700221
Shawn Willden86af3552015-06-24 07:21:54 -0700222 /* The only allowed purpose for this key is signing. */
223 keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
224
225 /* Padding & digest specifications. */
Shawn Willdenda6e8992015-06-03 09:40:45 -0600226 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
Shawn Willdenda6e8992015-06-03 09:40:45 -0600227 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700228
Shawn Willdenda6e8992015-06-03 09:40:45 -0600229 /* Require that the key be usable in standalone mode. File system isn't available. */
230 keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
231
232 /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
233 keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
234
Shawn Willdenda6e8992015-06-03 09:40:45 -0600235 /* Rate-limit key usage attempts, to rate-limit brute force */
236 keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
237 };
238 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
239 keymaster_key_blob_t key_blob;
240 keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, &param_set,
241 &key_blob,
242 NULL /* characteristics */);
243 if (error != KM_ERROR_OK) {
244 SLOGE("Failed to generate keymaster1 key, error %d", error);
245 rc = -1;
246 goto out;
247 }
248
249 key = (uint8_t*)key_blob.key_material;
250 key_size = key_blob.key_material_size;
251 }
252 else if (keymaster0_dev) {
253 keymaster_rsa_keygen_params_t params;
254 memset(&params, '\0', sizeof(params));
255 params.public_exponent = RSA_EXPONENT;
256 params.modulus_size = RSA_KEY_SIZE;
257
258 if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, &params,
259 &key, &key_size)) {
260 SLOGE("Failed to generate keypair");
261 rc = -1;
262 goto out;
263 }
264 } else {
265 SLOGE("Cryptfs bug: keymaster_init succeeded but didn't initialize a device");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700266 rc = -1;
267 goto out;
268 }
269
270 if (key_size > KEYMASTER_BLOB_SIZE) {
271 SLOGE("Keymaster key too large for crypto footer");
272 rc = -1;
273 goto out;
274 }
275
276 memcpy(ftr->keymaster_blob, key, key_size);
277 ftr->keymaster_blob_size = key_size;
278
279out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600280 if (keymaster0_dev)
281 keymaster0_close(keymaster0_dev);
282 if (keymaster1_dev)
283 keymaster1_close(keymaster1_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700284 free(key);
285 return rc;
286}
287
Shawn Willdene17a9c42014-09-08 13:04:08 -0600288/* This signs the given object using the keymaster key. */
289static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600290 const unsigned char *object,
291 const size_t object_size,
292 unsigned char **signature,
293 size_t *signature_size)
294{
295 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600296 keymaster0_device_t *keymaster0_dev = 0;
297 keymaster1_device_t *keymaster1_dev = 0;
298 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600299 SLOGE("Failed to init keymaster");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600300 rc = -1;
301 goto out;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600302 }
303
Shawn Willden47ba10d2014-09-03 17:07:06 -0600304 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600305 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600306 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600307
Shawn Willdene17a9c42014-09-08 13:04:08 -0600308 // To sign a message with RSA, the message must satisfy two
309 // constraints:
310 //
311 // 1. The message, when interpreted as a big-endian numeric value, must
312 // be strictly less than the public modulus of the RSA key. Note
313 // that because the most significant bit of the public modulus is
314 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
315 // key), an n-bit message with most significant bit 0 always
316 // satisfies this requirement.
317 //
318 // 2. The message must have the same length in bits as the public
319 // modulus of the RSA key. This requirement isn't mathematically
320 // necessary, but is necessary to ensure consistency in
321 // implementations.
322 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600323 case KDF_SCRYPT_KEYMASTER:
324 // This ensures the most significant byte of the signed message
325 // is zero. We could have zero-padded to the left instead, but
326 // this approach is slightly more robust against changes in
327 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600328 // so) because we really should be using a proper deterministic
329 // RSA padding function, such as PKCS1.
Shawn Willdene17a9c42014-09-08 13:04:08 -0600330 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
331 SLOGI("Signing safely-padded object");
332 break;
333 default:
334 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Shawn Willdenda6e8992015-06-03 09:40:45 -0600335 rc = -1;
336 goto out;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600337 }
338
Shawn Willdenda6e8992015-06-03 09:40:45 -0600339 if (keymaster0_dev) {
340 keymaster_rsa_sign_params_t params;
341 params.digest_type = DIGEST_NONE;
342 params.padding_type = PADDING_NONE;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600343
Shawn Willdenda6e8992015-06-03 09:40:45 -0600344 rc = keymaster0_dev->sign_data(keymaster0_dev,
345 &params,
346 ftr->keymaster_blob,
347 ftr->keymaster_blob_size,
348 to_sign,
349 to_sign_size,
350 signature,
351 signature_size);
352 goto out;
353 } else if (keymaster1_dev) {
354 keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
355 keymaster_key_param_t params[] = {
356 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
357 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
358 };
359 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
360 keymaster_operation_handle_t op_handle;
361 keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
362 &param_set, NULL /* out_params */,
363 &op_handle);
Shawn Willden04170602015-06-18 12:26:59 -0600364 if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
Shawn Willdenda6e8992015-06-03 09:40:45 -0600365 // Key usage has been rate-limited. Wait a bit and try again.
366 sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
367 error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
368 &param_set, NULL /* out_params */,
369 &op_handle);
370 }
371 if (error != KM_ERROR_OK) {
372 SLOGE("Error starting keymaster signature transaction: %d", error);
373 rc = -1;
374 goto out;
375 }
376
377 keymaster_blob_t input = { to_sign, to_sign_size };
378 size_t input_consumed;
379 error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
380 &input, &input_consumed, NULL /* out_params */,
381 NULL /* output */);
382 if (error != KM_ERROR_OK) {
383 SLOGE("Error sending data to keymaster signature transaction: %d", error);
384 rc = -1;
385 goto out;
386 }
387 if (input_consumed != to_sign_size) {
388 // This should never happen. If it does, it's a bug in the keymaster implementation.
389 SLOGE("Keymaster update() did not consume all data.");
390 keymaster1_dev->abort(keymaster1_dev, op_handle);
391 rc = -1;
392 goto out;
393 }
394
395 keymaster_blob_t tmp_sig;
396 error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
397 NULL /* verify signature */, NULL /* out_params */,
398 &tmp_sig);
399 if (error != KM_ERROR_OK) {
400 SLOGE("Error finishing keymaster signature transaction: %d", error);
401 rc = -1;
402 goto out;
403 }
404
405 *signature = (uint8_t*)tmp_sig.data;
406 *signature_size = tmp_sig.data_length;
407 } else {
408 SLOGE("Cryptfs bug: keymaster_init succeded but didn't initialize a device.");
409 rc = -1;
410 goto out;
411 }
412
413 out:
414 if (keymaster1_dev)
415 keymaster1_close(keymaster1_dev);
416 if (keymaster0_dev)
417 keymaster0_close(keymaster0_dev);
418
419 return rc;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600420}
421
Paul Lawrence399317e2014-03-10 13:20:50 -0700422/* Store password when userdata is successfully decrypted and mounted.
423 * Cleared by cryptfs_clear_password
424 *
425 * To avoid a double prompt at boot, we need to store the CryptKeeper
426 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
427 * Since the entire framework is torn down and rebuilt after encryption,
428 * we have to use a daemon or similar to store the password. Since vold
429 * is secured against IPC except from system processes, it seems a reasonable
430 * place to store this.
431 *
432 * password should be cleared once it has been used.
433 *
434 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800435 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700436static char* password = 0;
437static int password_expiry_time = 0;
438static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800439
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800440extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800441
Paul Lawrence87999172014-02-20 12:21:31 -0800442enum RebootType {reboot, recovery, shutdown};
443static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700444{
Paul Lawrence87999172014-02-20 12:21:31 -0800445 switch(rt) {
446 case reboot:
447 property_set(ANDROID_RB_PROPERTY, "reboot");
448 break;
449
450 case recovery:
451 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
452 break;
453
454 case shutdown:
455 property_set(ANDROID_RB_PROPERTY, "shutdown");
456 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700457 }
Paul Lawrence87999172014-02-20 12:21:31 -0800458
Ken Sumralladfba362013-06-04 16:37:52 -0700459 sleep(20);
460
461 /* Shouldn't get here, reboot should happen before sleep times out */
462 return;
463}
464
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800465static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
466{
467 memset(io, 0, dataSize);
468 io->data_size = dataSize;
469 io->data_start = sizeof(struct dm_ioctl);
470 io->version[0] = 4;
471 io->version[1] = 0;
472 io->version[2] = 0;
473 io->flags = flags;
474 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100475 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800476 }
477}
478
Kenny Rootc4c70f12013-06-14 12:11:38 -0700479/**
480 * Gets the default device scrypt parameters for key derivation time tuning.
481 * The parameters should lead to about one second derivation time for the
482 * given device.
483 */
484static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700485 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000486 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700487
Paul Crowley63c18d32016-02-10 14:02:47 +0000488 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
489 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
490 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
491 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700492 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000493 ftr->N_factor = Nf;
494 ftr->r_factor = rf;
495 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700496}
497
Ken Sumrall3ed82362011-01-28 23:31:16 -0800498static unsigned int get_fs_size(char *dev)
499{
500 int fd, block_size;
501 struct ext4_super_block sb;
502 off64_t len;
503
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700504 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800505 SLOGE("Cannot open device to get filesystem size ");
506 return 0;
507 }
508
509 if (lseek64(fd, 1024, SEEK_SET) < 0) {
510 SLOGE("Cannot seek to superblock");
511 return 0;
512 }
513
514 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
515 SLOGE("Cannot read superblock");
516 return 0;
517 }
518
519 close(fd);
520
Daniel Rosenberge82df162014-08-15 22:19:23 +0000521 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
522 SLOGE("Not a valid ext4 superblock");
523 return 0;
524 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800525 block_size = 1024 << sb.s_log_block_size;
526 /* compute length in bytes */
527 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
528
529 /* return length in sectors */
530 return (unsigned int) (len / 512);
531}
532
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
534{
535 static int cached_data = 0;
536 static off64_t cached_off = 0;
537 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
538 int fd;
539 char key_loc[PROPERTY_VALUE_MAX];
540 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700541 int rc = -1;
542
543 if (!cached_data) {
544 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
545
546 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700547 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700548 SLOGE("Cannot open real block device %s\n", real_blkdev);
549 return -1;
550 }
551
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900552 unsigned long nr_sec = 0;
553 get_blkdev_size(fd, &nr_sec);
554 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700555 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
556 * encryption info footer and key, and plenty of bytes to spare for future
557 * growth.
558 */
559 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
560 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
561 cached_data = 1;
562 } else {
563 SLOGE("Cannot get size of block device %s\n", real_blkdev);
564 }
565 close(fd);
566 } else {
567 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
568 cached_off = 0;
569 cached_data = 1;
570 }
571 }
572
573 if (cached_data) {
574 if (metadata_fname) {
575 *metadata_fname = cached_metadata_fname;
576 }
577 if (off) {
578 *off = cached_off;
579 }
580 rc = 0;
581 }
582
583 return rc;
584}
585
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800586/* Set sha256 checksum in structure */
587static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
588{
589 SHA256_CTX c;
590 SHA256_Init(&c);
591 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
592 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
593 SHA256_Final(crypt_ftr->sha256, &c);
594}
595
Ken Sumralle8744072011-01-18 22:01:55 -0800596/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800597 * update the failed mount count but not change the key.
598 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700599static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800600{
601 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800602 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700603 /* starting_off is set to the SEEK_SET offset
604 * where the crypto structure starts
605 */
606 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800607 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700608 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700609 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800610
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800611 set_ftr_sha(crypt_ftr);
612
Ken Sumrall160b4d62013-04-22 12:15:39 -0700613 if (get_crypt_ftr_info(&fname, &starting_off)) {
614 SLOGE("Unable to get crypt_ftr_info\n");
615 return -1;
616 }
617 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700618 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619 return -1;
620 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700621 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700622 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700623 return -1;
624 }
625
626 /* Seek to the start of the crypt footer */
627 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
628 SLOGE("Cannot seek to real block device footer\n");
629 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800630 }
631
632 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
633 SLOGE("Cannot write real block device footer\n");
634 goto errout;
635 }
636
Ken Sumrall3be890f2011-09-14 16:53:46 -0700637 fstat(fd, &statbuf);
638 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700639 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700640 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800641 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800642 goto errout;
643 }
644 }
645
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800646 /* Success! */
647 rc = 0;
648
649errout:
650 close(fd);
651 return rc;
652
653}
654
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800655static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
656{
657 struct crypt_mnt_ftr copy;
658 memcpy(&copy, crypt_ftr, sizeof(copy));
659 set_ftr_sha(&copy);
660 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
661}
662
Ken Sumrall160b4d62013-04-22 12:15:39 -0700663static inline int unix_read(int fd, void* buff, int len)
664{
665 return TEMP_FAILURE_RETRY(read(fd, buff, len));
666}
667
668static inline int unix_write(int fd, const void* buff, int len)
669{
670 return TEMP_FAILURE_RETRY(write(fd, buff, len));
671}
672
673static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
674{
675 memset(pdata, 0, len);
676 pdata->persist_magic = PERSIST_DATA_MAGIC;
677 pdata->persist_valid_entries = 0;
678}
679
680/* A routine to update the passed in crypt_ftr to the lastest version.
681 * fd is open read/write on the device that holds the crypto footer and persistent
682 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
683 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
684 */
685static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
686{
Kenny Root7434b312013-06-14 11:29:53 -0700687 int orig_major = crypt_ftr->major_version;
688 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700689
Kenny Root7434b312013-06-14 11:29:53 -0700690 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
691 struct crypt_persist_data *pdata;
692 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700693
Kenny Rootc4c70f12013-06-14 12:11:38 -0700694 SLOGW("upgrading crypto footer to 1.1");
695
Kenny Root7434b312013-06-14 11:29:53 -0700696 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
697 if (pdata == NULL) {
698 SLOGE("Cannot allocate persisent data\n");
699 return;
700 }
701 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
702
703 /* Need to initialize the persistent data area */
704 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
705 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100706 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700707 return;
708 }
709 /* Write all zeros to the first copy, making it invalid */
710 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
711
712 /* Write a valid but empty structure to the second copy */
713 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
714 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
715
716 /* Update the footer */
717 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
718 crypt_ftr->persist_data_offset[0] = pdata_offset;
719 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
720 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100721 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700722 }
723
Paul Lawrencef4faa572014-01-29 13:31:03 -0800724 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700725 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800726 /* But keep the old kdf_type.
727 * It will get updated later to KDF_SCRYPT after the password has been verified.
728 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700729 crypt_ftr->kdf_type = KDF_PBKDF2;
730 get_device_scrypt_params(crypt_ftr);
731 crypt_ftr->minor_version = 2;
732 }
733
Paul Lawrencef4faa572014-01-29 13:31:03 -0800734 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
735 SLOGW("upgrading crypto footer to 1.3");
736 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
737 crypt_ftr->minor_version = 3;
738 }
739
Kenny Root7434b312013-06-14 11:29:53 -0700740 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
741 if (lseek64(fd, offset, SEEK_SET) == -1) {
742 SLOGE("Cannot seek to crypt footer\n");
743 return;
744 }
745 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700746 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700747}
748
749
750static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800751{
752 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800753 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700754 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800755 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700756 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700757 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800758
Ken Sumrall160b4d62013-04-22 12:15:39 -0700759 if (get_crypt_ftr_info(&fname, &starting_off)) {
760 SLOGE("Unable to get crypt_ftr_info\n");
761 return -1;
762 }
763 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700764 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700765 return -1;
766 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700767 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700768 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700769 return -1;
770 }
771
772 /* Make sure it's 16 Kbytes in length */
773 fstat(fd, &statbuf);
774 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
775 SLOGE("footer file %s is not the expected size!\n", fname);
776 goto errout;
777 }
778
779 /* Seek to the start of the crypt footer */
780 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
781 SLOGE("Cannot seek to real block device footer\n");
782 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800783 }
784
785 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
786 SLOGE("Cannot read real block device footer\n");
787 goto errout;
788 }
789
790 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700791 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800792 goto errout;
793 }
794
Kenny Rootc96a5f82013-06-14 12:08:28 -0700795 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
796 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
797 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800798 goto errout;
799 }
800
Kenny Rootc96a5f82013-06-14 12:08:28 -0700801 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
802 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
803 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800804 }
805
Ken Sumrall160b4d62013-04-22 12:15:39 -0700806 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
807 * copy on disk before returning.
808 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700809 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700810 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800811 }
812
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800813 /* Success! */
814 rc = 0;
815
816errout:
817 close(fd);
818 return rc;
819}
820
Ken Sumrall160b4d62013-04-22 12:15:39 -0700821static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
822{
823 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
824 crypt_ftr->persist_data_offset[1]) {
825 SLOGE("Crypt_ftr persist data regions overlap");
826 return -1;
827 }
828
829 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
830 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
831 return -1;
832 }
833
834 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
835 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
836 CRYPT_FOOTER_OFFSET) {
837 SLOGE("Persistent data extends past crypto footer");
838 return -1;
839 }
840
841 return 0;
842}
843
844static int load_persistent_data(void)
845{
846 struct crypt_mnt_ftr crypt_ftr;
847 struct crypt_persist_data *pdata = NULL;
848 char encrypted_state[PROPERTY_VALUE_MAX];
849 char *fname;
850 int found = 0;
851 int fd;
852 int ret;
853 int i;
854
855 if (persist_data) {
856 /* Nothing to do, we've already loaded or initialized it */
857 return 0;
858 }
859
860
861 /* If not encrypted, just allocate an empty table and initialize it */
862 property_get("ro.crypto.state", encrypted_state, "");
863 if (strcmp(encrypted_state, "encrypted") ) {
864 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
865 if (pdata) {
866 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
867 persist_data = pdata;
868 return 0;
869 }
870 return -1;
871 }
872
873 if(get_crypt_ftr_and_key(&crypt_ftr)) {
874 return -1;
875 }
876
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700877 if ((crypt_ftr.major_version < 1)
878 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700879 SLOGE("Crypt_ftr version doesn't support persistent data");
880 return -1;
881 }
882
883 if (get_crypt_ftr_info(&fname, NULL)) {
884 return -1;
885 }
886
887 ret = validate_persistent_data_storage(&crypt_ftr);
888 if (ret) {
889 return -1;
890 }
891
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700892 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700893 if (fd < 0) {
894 SLOGE("Cannot open %s metadata file", fname);
895 return -1;
896 }
897
Paul Lawrence300dae72016-03-11 11:02:52 -0800898 pdata = malloc(crypt_ftr.persist_data_size);
899 if (pdata == NULL) {
900 SLOGE("Cannot allocate memory for persistent data");
901 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700902 }
903
904 for (i = 0; i < 2; i++) {
905 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
906 SLOGE("Cannot seek to read persistent data on %s", fname);
907 goto err2;
908 }
909 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
910 SLOGE("Error reading persistent data on iteration %d", i);
911 goto err2;
912 }
913 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
914 found = 1;
915 break;
916 }
917 }
918
919 if (!found) {
920 SLOGI("Could not find valid persistent data, creating");
921 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
922 }
923
924 /* Success */
925 persist_data = pdata;
926 close(fd);
927 return 0;
928
929err2:
930 free(pdata);
931
932err:
933 close(fd);
934 return -1;
935}
936
937static int save_persistent_data(void)
938{
939 struct crypt_mnt_ftr crypt_ftr;
940 struct crypt_persist_data *pdata;
941 char *fname;
942 off64_t write_offset;
943 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700944 int fd;
945 int ret;
946
947 if (persist_data == NULL) {
948 SLOGE("No persistent data to save");
949 return -1;
950 }
951
952 if(get_crypt_ftr_and_key(&crypt_ftr)) {
953 return -1;
954 }
955
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700956 if ((crypt_ftr.major_version < 1)
957 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700958 SLOGE("Crypt_ftr version doesn't support persistent data");
959 return -1;
960 }
961
962 ret = validate_persistent_data_storage(&crypt_ftr);
963 if (ret) {
964 return -1;
965 }
966
967 if (get_crypt_ftr_info(&fname, NULL)) {
968 return -1;
969 }
970
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700971 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700972 if (fd < 0) {
973 SLOGE("Cannot open %s metadata file", fname);
974 return -1;
975 }
976
977 pdata = malloc(crypt_ftr.persist_data_size);
978 if (pdata == NULL) {
979 SLOGE("Cannot allocate persistant data");
980 goto err;
981 }
982
983 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
984 SLOGE("Cannot seek to read persistent data on %s", fname);
985 goto err2;
986 }
987
988 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
989 SLOGE("Error reading persistent data before save");
990 goto err2;
991 }
992
993 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
994 /* The first copy is the curent valid copy, so write to
995 * the second copy and erase this one */
996 write_offset = crypt_ftr.persist_data_offset[1];
997 erase_offset = crypt_ftr.persist_data_offset[0];
998 } else {
999 /* The second copy must be the valid copy, so write to
1000 * the first copy, and erase the second */
1001 write_offset = crypt_ftr.persist_data_offset[0];
1002 erase_offset = crypt_ftr.persist_data_offset[1];
1003 }
1004
1005 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001006 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001007 SLOGE("Cannot seek to write persistent data");
1008 goto err2;
1009 }
1010 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1011 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001012 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001013 SLOGE("Cannot seek to erase previous persistent data");
1014 goto err2;
1015 }
1016 fsync(fd);
1017 memset(pdata, 0, crypt_ftr.persist_data_size);
1018 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
1019 (int) crypt_ftr.persist_data_size) {
1020 SLOGE("Cannot write to erase previous persistent data");
1021 goto err2;
1022 }
1023 fsync(fd);
1024 } else {
1025 SLOGE("Cannot write to save persistent data");
1026 goto err2;
1027 }
1028
1029 /* Success */
1030 free(pdata);
1031 close(fd);
1032 return 0;
1033
1034err2:
1035 free(pdata);
1036err:
1037 close(fd);
1038 return -1;
1039}
1040
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001041/* Convert a binary key of specified length into an ascii hex string equivalent,
1042 * without the leading 0x and with null termination
1043 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001044static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001045 unsigned int keysize, char *master_key_ascii) {
1046 unsigned int i, a;
1047 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001048
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001049 for (i=0, a=0; i<keysize; i++, a+=2) {
1050 /* For each byte, write out two ascii hex digits */
1051 nibble = (master_key[i] >> 4) & 0xf;
1052 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001053
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001054 nibble = master_key[i] & 0xf;
1055 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1056 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001057
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001058 /* Add the null termination */
1059 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001060
1061}
1062
Jeff Sharkey9c484982015-03-31 10:35:33 -07001063static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
1064 const unsigned char *master_key, const char *real_blk_name,
1065 const char *name, int fd, const char *extra_params) {
Dan Albertc07fa3f2014-12-18 10:00:55 -08001066 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001067 struct dm_ioctl *io;
1068 struct dm_target_spec *tgt;
1069 char *crypt_params;
1070 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1071 int i;
1072
1073 io = (struct dm_ioctl *) buffer;
1074
1075 /* Load the mapping table for this device */
1076 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1077
1078 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1079 io->target_count = 1;
1080 tgt->status = 0;
1081 tgt->sector_start = 0;
1082 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -07001083#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001084 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1085 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1086 }
1087 else {
1088 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1089 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001090#else
1091 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1092#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001093
1094 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1095 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1096 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1097 master_key_ascii, real_blk_name, extra_params);
1098 crypt_params += strlen(crypt_params) + 1;
1099 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1100 tgt->next = crypt_params - buffer;
1101
1102 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1103 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1104 break;
1105 }
1106 usleep(500000);
1107 }
1108
1109 if (i == TABLE_LOAD_RETRIES) {
1110 /* We failed to load the table, return an error */
1111 return -1;
1112 } else {
1113 return i + 1;
1114 }
1115}
1116
1117
1118static int get_dm_crypt_version(int fd, const char *name, int *version)
1119{
1120 char buffer[DM_CRYPT_BUF_SIZE];
1121 struct dm_ioctl *io;
1122 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001123
1124 io = (struct dm_ioctl *) buffer;
1125
1126 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1127
1128 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1129 return -1;
1130 }
1131
1132 /* Iterate over the returned versions, looking for name of "crypt".
1133 * When found, get and return the version.
1134 */
1135 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1136 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001137#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001138 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001139#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001140 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001141#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001142 /* We found the crypt driver, return the version, and get out */
1143 version[0] = v->version[0];
1144 version[1] = v->version[1];
1145 version[2] = v->version[2];
1146 return 0;
1147 }
1148 v = (struct dm_target_versions *)(((char *)v) + v->next);
1149 }
1150
1151 return -1;
1152}
1153
Jeff Sharkey9c484982015-03-31 10:35:33 -07001154static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
1155 const unsigned char *master_key, const char *real_blk_name,
1156 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001158 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001159 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001160 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -08001161 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001162 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001163 int version[3];
1164 char *extra_params;
1165 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001166
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001167 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001168 SLOGE("Cannot open device-mapper\n");
1169 goto errout;
1170 }
1171
1172 io = (struct dm_ioctl *) buffer;
1173
1174 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -08001175 err = ioctl(fd, DM_DEV_CREATE, io);
1176 if (err) {
1177 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001178 goto errout;
1179 }
1180
1181 /* Get the device status, in particular, the name of it's device file */
1182 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1183 if (ioctl(fd, DM_DEV_STATUS, io)) {
1184 SLOGE("Cannot retrieve dm-crypt device status\n");
1185 goto errout;
1186 }
1187 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1188 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1189
Ken Sumralldb5e0262013-02-05 17:39:48 -08001190 extra_params = "";
1191 if (! get_dm_crypt_version(fd, name, version)) {
1192 /* Support for allow_discards was added in version 1.11.0 */
1193 if ((version[0] >= 2) ||
1194 ((version[0] == 1) && (version[1] >= 11))) {
1195 extra_params = "1 allow_discards";
1196 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1197 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001198 }
1199
Ken Sumralldb5e0262013-02-05 17:39:48 -08001200 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1201 fd, extra_params);
1202 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001203 SLOGE("Cannot load dm-crypt mapping table.\n");
1204 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001205 } else if (load_count > 1) {
1206 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207 }
1208
1209 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001210 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001211
1212 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1213 SLOGE("Cannot resume the dm-crypt device\n");
1214 goto errout;
1215 }
1216
1217 /* We made it here with no errors. Woot! */
1218 retval = 0;
1219
1220errout:
1221 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1222
1223 return retval;
1224}
1225
Ken Sumrall29d8da82011-05-18 17:20:07 -07001226static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001227{
1228 int fd;
1229 char buffer[DM_CRYPT_BUF_SIZE];
1230 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001231 int retval = -1;
1232
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001233 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001234 SLOGE("Cannot open device-mapper\n");
1235 goto errout;
1236 }
1237
1238 io = (struct dm_ioctl *) buffer;
1239
1240 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1241 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1242 SLOGE("Cannot remove dm-crypt device\n");
1243 goto errout;
1244 }
1245
1246 /* We made it here with no errors. Woot! */
1247 retval = 0;
1248
1249errout:
1250 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1251
1252 return retval;
1253
1254}
1255
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001256static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001257 unsigned char *ikey, void *params UNUSED)
1258{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001259 SLOGI("Using pbkdf2 for cryptfs KDF");
1260
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001261 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001262 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1263 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1264 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001265}
1266
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001267static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001268 unsigned char *ikey, void *params)
1269{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001270 SLOGI("Using scrypt for cryptfs KDF");
1271
Kenny Rootc4c70f12013-06-14 12:11:38 -07001272 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1273
1274 int N = 1 << ftr->N_factor;
1275 int r = 1 << ftr->r_factor;
1276 int p = 1 << ftr->p_factor;
1277
1278 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001279 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001280 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1281 salt, SALT_LEN, N, r, p, ikey,
1282 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001283
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001284 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001285}
1286
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001287static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1288 unsigned char *ikey, void *params)
1289{
1290 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1291
1292 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001293 size_t signature_size;
1294 unsigned char* signature;
1295 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1296
1297 int N = 1 << ftr->N_factor;
1298 int r = 1 << ftr->r_factor;
1299 int p = 1 << ftr->p_factor;
1300
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001301 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1302 salt, SALT_LEN, N, r, p, ikey,
1303 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001304
1305 if (rc) {
1306 SLOGE("scrypt failed");
1307 return -1;
1308 }
1309
Shawn Willdene17a9c42014-09-08 13:04:08 -06001310 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1311 &signature, &signature_size)) {
1312 SLOGE("Signing failed");
1313 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001314 }
1315
1316 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1317 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1318 free(signature);
1319
1320 if (rc) {
1321 SLOGE("scrypt failed");
1322 return -1;
1323 }
1324
1325 return 0;
1326}
1327
1328static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1329 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001330 unsigned char *encrypted_master_key,
1331 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001332{
1333 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1334 EVP_CIPHER_CTX e_ctx;
1335 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001336 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001337
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001338 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001339 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001340
1341 switch (crypt_ftr->kdf_type) {
1342 case KDF_SCRYPT_KEYMASTER:
1343 if (keymaster_create_key(crypt_ftr)) {
1344 SLOGE("keymaster_create_key failed");
1345 return -1;
1346 }
1347
1348 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1349 SLOGE("scrypt failed");
1350 return -1;
1351 }
1352 break;
1353
1354 case KDF_SCRYPT:
1355 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1356 SLOGE("scrypt failed");
1357 return -1;
1358 }
1359 break;
1360
1361 default:
1362 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001363 return -1;
1364 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001365
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001366 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001367 EVP_CIPHER_CTX_init(&e_ctx);
1368 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001369 SLOGE("EVP_EncryptInit failed\n");
1370 return -1;
1371 }
1372 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001373
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001374 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001375 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001376 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001377 SLOGE("EVP_EncryptUpdate failed\n");
1378 return -1;
1379 }
Adam Langley889c4f12014-09-03 14:23:13 -07001380 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001381 SLOGE("EVP_EncryptFinal failed\n");
1382 return -1;
1383 }
1384
1385 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1386 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1387 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001388 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001389
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001390 /* Store the scrypt of the intermediate key, so we can validate if it's a
1391 password error or mount error when things go wrong.
1392 Note there's no need to check for errors, since if this is incorrect, we
1393 simply won't wipe userdata, which is the correct default behavior
1394 */
1395 int N = 1 << crypt_ftr->N_factor;
1396 int r = 1 << crypt_ftr->r_factor;
1397 int p = 1 << crypt_ftr->p_factor;
1398
1399 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1400 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1401 crypt_ftr->scrypted_intermediate_key,
1402 sizeof(crypt_ftr->scrypted_intermediate_key));
1403
1404 if (rc) {
1405 SLOGE("encrypt_master_key: crypto_scrypt failed");
1406 }
1407
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001408 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001409}
1410
Paul Lawrence731a7a22015-04-28 22:14:15 +00001411static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001412 unsigned char *encrypted_master_key,
1413 unsigned char *decrypted_master_key,
1414 kdf_func kdf, void *kdf_params,
1415 unsigned char** intermediate_key,
1416 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001417{
1418 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 -08001419 EVP_CIPHER_CTX d_ctx;
1420 int decrypted_len, final_len;
1421
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001422 /* Turn the password into an intermediate key and IV that can decrypt the
1423 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001424 if (kdf(passwd, salt, ikey, kdf_params)) {
1425 SLOGE("kdf failed");
1426 return -1;
1427 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428
1429 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001430 EVP_CIPHER_CTX_init(&d_ctx);
1431 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001432 return -1;
1433 }
1434 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1435 /* Decrypt the master key */
1436 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1437 encrypted_master_key, KEY_LEN_BYTES)) {
1438 return -1;
1439 }
Adam Langley889c4f12014-09-03 14:23:13 -07001440 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001441 return -1;
1442 }
1443
1444 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1445 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001446 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001447
1448 /* Copy intermediate key if needed by params */
1449 if (intermediate_key && intermediate_key_size) {
1450 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1451 if (intermediate_key) {
1452 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1453 *intermediate_key_size = KEY_LEN_BYTES;
1454 }
1455 }
1456
1457 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001458}
1459
Kenny Rootc4c70f12013-06-14 12:11:38 -07001460static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001461{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001462 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001463 *kdf = scrypt_keymaster;
1464 *kdf_params = ftr;
1465 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001466 *kdf = scrypt;
1467 *kdf_params = ftr;
1468 } else {
1469 *kdf = pbkdf2;
1470 *kdf_params = NULL;
1471 }
1472}
1473
Paul Lawrence731a7a22015-04-28 22:14:15 +00001474static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001475 struct crypt_mnt_ftr *crypt_ftr,
1476 unsigned char** intermediate_key,
1477 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001478{
1479 kdf_func kdf;
1480 void *kdf_params;
1481 int ret;
1482
1483 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001484 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1485 decrypted_master_key, kdf, kdf_params,
1486 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001487 if (ret != 0) {
1488 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001489 }
1490
1491 return ret;
1492}
1493
1494static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1495 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001496 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001497 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001498
1499 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001500 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001501 read(fd, key_buf, sizeof(key_buf));
1502 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001503 close(fd);
1504
1505 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001506 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001507}
1508
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001509int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001510{
Greg Hackmann955653e2014-09-24 14:55:20 -07001511 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001512#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001513
1514 /* Now umount the tmpfs filesystem */
1515 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001516 if (umount(mountpoint) == 0) {
1517 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001518 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001519
1520 if (errno == EINVAL) {
1521 /* EINVAL is returned if the directory is not a mountpoint,
1522 * i.e. there is no filesystem mounted there. So just get out.
1523 */
1524 break;
1525 }
1526
1527 err = errno;
1528
1529 /* If allowed, be increasingly aggressive before the last two retries */
1530 if (kill) {
1531 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1532 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001533 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001534 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1535 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001536 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001537 }
1538 }
1539
1540 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001541 }
1542
1543 if (i < WAIT_UNMOUNT_COUNT) {
1544 SLOGD("unmounting %s succeeded\n", mountpoint);
1545 rc = 0;
1546 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001547 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001548 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001549 rc = -1;
1550 }
1551
1552 return rc;
1553}
1554
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001555#define DATA_PREP_TIMEOUT 1000
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001556static int prep_data_fs(void)
1557{
1558 int i;
1559
Jeff Sharkey47695b22016-02-01 17:02:29 -07001560 // NOTE: post_fs_data results in init calling back around to vold, so all
1561 // callers to this method must be async
1562
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001563 /* Do the prep of the /data filesystem */
1564 property_set("vold.post_fs_data_done", "0");
1565 property_set("vold.decrypt", "trigger_post_fs_data");
1566 SLOGD("Just triggered post_fs_data\n");
1567
Ken Sumrallc5872692013-05-14 15:26:31 -07001568 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001569 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001570 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001571
1572 property_get("vold.post_fs_data_done", p, "0");
1573 if (*p == '1') {
1574 break;
1575 } else {
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001576 usleep(50000);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001577 }
1578 }
1579 if (i == DATA_PREP_TIMEOUT) {
1580 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001581 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001582 return -1;
1583 } else {
1584 SLOGD("post_fs_data done\n");
1585 return 0;
1586 }
1587}
1588
Paul Lawrence74f29f12014-08-28 15:54:10 -07001589static void cryptfs_set_corrupt()
1590{
1591 // Mark the footer as bad
1592 struct crypt_mnt_ftr crypt_ftr;
1593 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1594 SLOGE("Failed to get crypto footer - panic");
1595 return;
1596 }
1597
1598 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1599 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1600 SLOGE("Failed to set crypto footer - panic");
1601 return;
1602 }
1603}
1604
1605static void cryptfs_trigger_restart_min_framework()
1606{
1607 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1608 SLOGE("Failed to mount tmpfs on data - panic");
1609 return;
1610 }
1611
1612 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1613 SLOGE("Failed to trigger post fs data - panic");
1614 return;
1615 }
1616
1617 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1618 SLOGE("Failed to trigger restart min framework - panic");
1619 return;
1620 }
1621}
1622
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001623/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001624static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001625{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001626 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001627 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001628 static int restart_successful = 0;
1629
1630 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001631 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001632 SLOGE("Encrypted filesystem not validated, aborting");
1633 return -1;
1634 }
1635
1636 if (restart_successful) {
1637 SLOGE("System already restarted with encrypted disk, aborting");
1638 return -1;
1639 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001640
Paul Lawrencef4faa572014-01-29 13:31:03 -08001641 if (restart_main) {
1642 /* Here is where we shut down the framework. The init scripts
1643 * start all services in one of three classes: core, main or late_start.
1644 * On boot, we start core and main. Now, we stop main, but not core,
1645 * as core includes vold and a few other really important things that
1646 * we need to keep running. Once main has stopped, we should be able
1647 * to umount the tmpfs /data, then mount the encrypted /data.
1648 * We then restart the class main, and also the class late_start.
1649 * At the moment, I've only put a few things in late_start that I know
1650 * are not needed to bring up the framework, and that also cause problems
1651 * with unmounting the tmpfs /data, but I hope to add add more services
1652 * to the late_start class as we optimize this to decrease the delay
1653 * till the user is asked for the password to the filesystem.
1654 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001655
Paul Lawrencef4faa572014-01-29 13:31:03 -08001656 /* The init files are setup to stop the class main when vold.decrypt is
1657 * set to trigger_reset_main.
1658 */
1659 property_set("vold.decrypt", "trigger_reset_main");
1660 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001661
Paul Lawrencef4faa572014-01-29 13:31:03 -08001662 /* Ugh, shutting down the framework is not synchronous, so until it
1663 * can be fixed, this horrible hack will wait a moment for it all to
1664 * shut down before proceeding. Without it, some devices cannot
1665 * restart the graphics services.
1666 */
1667 sleep(2);
1668 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001669
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001670 /* Now that the framework is shutdown, we should be able to umount()
1671 * the tmpfs filesystem, and mount the real one.
1672 */
1673
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001674 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1675 if (strlen(crypto_blkdev) == 0) {
1676 SLOGE("fs_crypto_blkdev not set\n");
1677 return -1;
1678 }
1679
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001680 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001681 /* If ro.crypto.readonly is set to 1, mount the decrypted
1682 * filesystem readonly. This is used when /data is mounted by
1683 * recovery mode.
1684 */
1685 char ro_prop[PROPERTY_VALUE_MAX];
1686 property_get("ro.crypto.readonly", ro_prop, "");
1687 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1688 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1689 rec->flags |= MS_RDONLY;
1690 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001691
Ken Sumralle5032c42012-04-01 23:58:44 -07001692 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001693 int retries = RETRY_MOUNT_ATTEMPTS;
1694 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001695
1696 /*
1697 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1698 * partitions in the fsck domain.
1699 */
1700 if (setexeccon(secontextFsck())){
1701 SLOGE("Failed to setexeccon");
1702 return -1;
1703 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001704 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1705 crypto_blkdev, 0))
1706 != 0) {
1707 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1708 /* TODO: invoke something similar to
1709 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1710 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1711 SLOGI("Failed to mount %s because it is busy - waiting",
1712 crypto_blkdev);
1713 if (--retries) {
1714 sleep(RETRY_MOUNT_DELAY_SECONDS);
1715 } else {
1716 /* Let's hope that a reboot clears away whatever is keeping
1717 the mount busy */
1718 cryptfs_reboot(reboot);
1719 }
1720 } else {
1721 SLOGE("Failed to mount decrypted data");
1722 cryptfs_set_corrupt();
1723 cryptfs_trigger_restart_min_framework();
1724 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001725 if (setexeccon(NULL)) {
1726 SLOGE("Failed to setexeccon");
1727 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001728 return -1;
1729 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001730 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001731 if (setexeccon(NULL)) {
1732 SLOGE("Failed to setexeccon");
1733 return -1;
1734 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001735
Ken Sumralle5032c42012-04-01 23:58:44 -07001736 property_set("vold.decrypt", "trigger_load_persist_props");
1737 /* Create necessary paths on /data */
1738 if (prep_data_fs()) {
1739 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001740 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001741
1742 /* startup service classes main and late_start */
1743 property_set("vold.decrypt", "trigger_restart_framework");
1744 SLOGD("Just triggered restart_framework\n");
1745
1746 /* Give it a few moments to get started */
1747 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001748 }
1749
Ken Sumrall0cc16632011-01-18 20:32:26 -08001750 if (rc == 0) {
1751 restart_successful = 1;
1752 }
1753
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001754 return rc;
1755}
1756
Paul Lawrencef4faa572014-01-29 13:31:03 -08001757int cryptfs_restart(void)
1758{
Paul Lawrence05335c32015-03-05 09:46:23 -08001759 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001760 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001761 SLOGE("cryptfs_restart not valid for file encryption:");
1762 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001763 }
1764
Paul Lawrencef4faa572014-01-29 13:31:03 -08001765 /* Call internal implementation forcing a restart of main service group */
1766 return cryptfs_restart_internal(1);
1767}
1768
Paul Lawrence05335c32015-03-05 09:46:23 -08001769static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001770{
1771 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001772 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001773 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001774
1775 property_get("ro.crypto.state", encrypted_state, "");
1776 if (strcmp(encrypted_state, "encrypted") ) {
1777 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001778 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001779 }
1780
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001781 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001782 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001783 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001784 }
1785
Ken Sumrall160b4d62013-04-22 12:15:39 -07001786 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001787 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001788
Ken Sumralle1a45852011-12-14 21:24:27 -08001789 /*
1790 * Only report this error if key_loc is a file and it exists.
1791 * If the device was never encrypted, and /data is not mountable for
1792 * some reason, returning 1 should prevent the UI from presenting the
1793 * a "enter password" screen, or worse, a "press button to wipe the
1794 * device" screen.
1795 */
1796 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1797 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001798 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001799 } else {
1800 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001801 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001802 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001803 }
1804
Paul Lawrence74f29f12014-08-28 15:54:10 -07001805 // Test for possible error flags
1806 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1807 SLOGE("Encryption process is partway completed\n");
1808 return CRYPTO_COMPLETE_PARTIAL;
1809 }
1810
1811 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1812 SLOGE("Encryption process was interrupted but cannot continue\n");
1813 return CRYPTO_COMPLETE_INCONSISTENT;
1814 }
1815
1816 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1817 SLOGE("Encryption is successful but data is corrupt\n");
1818 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001819 }
1820
1821 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001822 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001823}
1824
Paul Lawrencef4faa572014-01-29 13:31:03 -08001825static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1826 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001827{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001828 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001829 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001830 char crypto_blkdev[MAXPATHLEN];
1831 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001832 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001833 unsigned int orig_failed_decrypt_count;
1834 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001835 int use_keymaster = 0;
1836 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001837 unsigned char* intermediate_key = 0;
1838 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001839
Paul Lawrencef4faa572014-01-29 13:31:03 -08001840 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1841 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001842
Paul Lawrencef4faa572014-01-29 13:31:03 -08001843 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001844 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1845 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001846 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001847 rc = -1;
1848 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001849 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001850 }
1851
Paul Lawrencef4faa572014-01-29 13:31:03 -08001852 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1853
Ajay Dudani87701e22014-09-17 21:02:52 -07001854#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001855 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1856 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1857 SLOGE("Hardware encryption key does not match");
1858 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001859 }
1860#endif
1861
Paul Lawrence74f29f12014-08-28 15:54:10 -07001862 // Create crypto block device - all (non fatal) code paths
1863 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001864 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1865 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001866 SLOGE("Error creating decrypted block device\n");
1867 rc = -1;
1868 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001869 }
1870
Paul Lawrence74f29f12014-08-28 15:54:10 -07001871 /* Work out if the problem is the password or the data */
1872 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1873 scrypted_intermediate_key)];
1874 int N = 1 << crypt_ftr->N_factor;
1875 int r = 1 << crypt_ftr->r_factor;
1876 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001877
Paul Lawrence74f29f12014-08-28 15:54:10 -07001878 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1879 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1880 N, r, p, scrypted_intermediate_key,
1881 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001882
Paul Lawrence74f29f12014-08-28 15:54:10 -07001883 // Does the key match the crypto footer?
1884 if (rc == 0 && memcmp(scrypted_intermediate_key,
1885 crypt_ftr->scrypted_intermediate_key,
1886 sizeof(scrypted_intermediate_key)) == 0) {
1887 SLOGI("Password matches");
1888 rc = 0;
1889 } else {
1890 /* Try mounting the file system anyway, just in case the problem's with
1891 * the footer, not the key. */
1892 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1893 mkdir(tmp_mount_point, 0755);
1894 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1895 SLOGE("Error temp mounting decrypted block device\n");
1896 delete_crypto_blk_dev(label);
1897
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001898 rc = ++crypt_ftr->failed_decrypt_count;
1899 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001900 } else {
1901 /* Success! */
1902 SLOGI("Password did not match but decrypted drive mounted - continue");
1903 umount(tmp_mount_point);
1904 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001905 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001906 }
1907
1908 if (rc == 0) {
1909 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001910 if (orig_failed_decrypt_count != 0) {
1911 put_crypt_ftr_and_key(crypt_ftr);
1912 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001913
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001914 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001915 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001916 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001917
1918 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001919 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001920 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001921 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001922 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001923 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001924 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001925
Paul Lawrence74f29f12014-08-28 15:54:10 -07001926 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001927 use_keymaster = keymaster_check_compatibility();
1928 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001929 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001930 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1931 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1932 upgrade = 1;
1933 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001934 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001935 upgrade = 1;
1936 }
1937
1938 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001939 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1940 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001941 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001942 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001943 }
1944 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001945
1946 // Do not fail even if upgrade failed - machine is bootable
1947 // Note that if this code is ever hit, there is a *serious* problem
1948 // since KDFs should never fail. You *must* fix the kdf before
1949 // proceeding!
1950 if (rc) {
1951 SLOGW("Upgrade failed with error %d,"
1952 " but continuing with previous state",
1953 rc);
1954 rc = 0;
1955 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001956 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001957 }
1958
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001959 errout:
1960 if (intermediate_key) {
1961 memset(intermediate_key, 0, intermediate_key_size);
1962 free(intermediate_key);
1963 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001964 return rc;
1965}
1966
Ken Sumrall29d8da82011-05-18 17:20:07 -07001967/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001968 * Called by vold when it's asked to mount an encrypted external
1969 * storage volume. The incoming partition has no crypto header/footer,
1970 * as any metadata is been stored in a separate, small partition.
1971 *
1972 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001973 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001974int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1975 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001976 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001977 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001978 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001979 return -1;
1980 }
1981
1982 unsigned long nr_sec = 0;
1983 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001984 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001985
Ken Sumrall29d8da82011-05-18 17:20:07 -07001986 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001987 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001988 return -1;
1989 }
1990
Jeff Sharkey9c484982015-03-31 10:35:33 -07001991 struct crypt_mnt_ftr ext_crypt_ftr;
1992 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1993 ext_crypt_ftr.fs_size = nr_sec;
1994 ext_crypt_ftr.keysize = keysize;
1995 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001996
Jeff Sharkey9c484982015-03-31 10:35:33 -07001997 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1998 out_crypto_blkdev, label);
1999}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002000
Jeff Sharkey9c484982015-03-31 10:35:33 -07002001/*
2002 * Called by vold when it's asked to unmount an encrypted external
2003 * storage volume.
2004 */
2005int cryptfs_revert_ext_volume(const char* label) {
2006 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002007}
2008
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002009int cryptfs_crypto_complete(void)
2010{
2011 return do_crypto_complete("/data");
2012}
2013
Paul Lawrencef4faa572014-01-29 13:31:03 -08002014int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2015{
2016 char encrypted_state[PROPERTY_VALUE_MAX];
2017 property_get("ro.crypto.state", encrypted_state, "");
2018 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2019 SLOGE("encrypted fs already validated or not running with encryption,"
2020 " aborting");
2021 return -1;
2022 }
2023
2024 if (get_crypt_ftr_and_key(crypt_ftr)) {
2025 SLOGE("Error getting crypt footer and key");
2026 return -1;
2027 }
2028
2029 return 0;
2030}
2031
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002032int cryptfs_check_passwd(char *passwd)
2033{
Paul Lawrence05335c32015-03-05 09:46:23 -08002034 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00002035 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002036 SLOGE("cryptfs_check_passwd not valid for file encryption");
2037 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002038 }
2039
Paul Lawrencef4faa572014-01-29 13:31:03 -08002040 struct crypt_mnt_ftr crypt_ftr;
2041 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002042
Paul Lawrencef4faa572014-01-29 13:31:03 -08002043 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002044 if (rc) {
2045 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002046 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002047 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002048
Paul Lawrence3bd36d52015-06-09 13:37:44 -07002049 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002050 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2051 if (rc) {
2052 SLOGE("Password did not match");
2053 return rc;
2054 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002055
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002056 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2057 // Here we have a default actual password but a real password
2058 // we must test against the scrypted value
2059 // First, we must delete the crypto block device that
2060 // test_mount_encrypted_fs leaves behind as a side effect
2061 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2062 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2063 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2064 if (rc) {
2065 SLOGE("Default password did not match on reboot encryption");
2066 return rc;
2067 }
2068
2069 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2070 put_crypt_ftr_and_key(&crypt_ftr);
2071 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2072 if (rc) {
2073 SLOGE("Could not change password on reboot encryption");
2074 return rc;
2075 }
2076 }
2077
2078 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002079 cryptfs_clear_password();
2080 password = strdup(passwd);
2081 struct timespec now;
2082 clock_gettime(CLOCK_BOOTTIME, &now);
2083 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002084 }
2085
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002086 return rc;
2087}
2088
Ken Sumrall3ad90722011-10-04 20:38:29 -07002089int cryptfs_verify_passwd(char *passwd)
2090{
2091 struct crypt_mnt_ftr crypt_ftr;
2092 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002093 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002094 char encrypted_state[PROPERTY_VALUE_MAX];
2095 int rc;
2096
2097 property_get("ro.crypto.state", encrypted_state, "");
2098 if (strcmp(encrypted_state, "encrypted") ) {
2099 SLOGE("device not encrypted, aborting");
2100 return -2;
2101 }
2102
2103 if (!master_key_saved) {
2104 SLOGE("encrypted fs not yet mounted, aborting");
2105 return -1;
2106 }
2107
2108 if (!saved_mount_point) {
2109 SLOGE("encrypted fs failed to save mount point, aborting");
2110 return -1;
2111 }
2112
Ken Sumrall160b4d62013-04-22 12:15:39 -07002113 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002114 SLOGE("Error getting crypt footer and key\n");
2115 return -1;
2116 }
2117
2118 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2119 /* If the device has no password, then just say the password is valid */
2120 rc = 0;
2121 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002122 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002123 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2124 /* They match, the password is correct */
2125 rc = 0;
2126 } else {
2127 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2128 sleep(1);
2129 rc = 1;
2130 }
2131 }
2132
2133 return rc;
2134}
2135
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002136/* Initialize a crypt_mnt_ftr structure. The keysize is
2137 * defaulted to 16 bytes, and the filesystem size to 0.
2138 * Presumably, at a minimum, the caller will update the
2139 * filesystem size and crypto_type_name after calling this function.
2140 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002141static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002142{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002143 off64_t off;
2144
2145 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002146 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002147 ftr->major_version = CURRENT_MAJOR_VERSION;
2148 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002149 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002150 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002151
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002152 switch (keymaster_check_compatibility()) {
2153 case 1:
2154 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2155 break;
2156
2157 case 0:
2158 ftr->kdf_type = KDF_SCRYPT;
2159 break;
2160
2161 default:
2162 SLOGE("keymaster_check_compatibility failed");
2163 return -1;
2164 }
2165
Kenny Rootc4c70f12013-06-14 12:11:38 -07002166 get_device_scrypt_params(ftr);
2167
Ken Sumrall160b4d62013-04-22 12:15:39 -07002168 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2169 if (get_crypt_ftr_info(NULL, &off) == 0) {
2170 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2171 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2172 ftr->persist_data_size;
2173 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002174
2175 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002176}
2177
Ken Sumrall29d8da82011-05-18 17:20:07 -07002178static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002179{
Ken Sumralle550f782013-08-20 13:48:23 -07002180 const char *args[10];
2181 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2182 int num_args;
2183 int status;
2184 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002185 int rc = -1;
2186
Ken Sumrall29d8da82011-05-18 17:20:07 -07002187 if (type == EXT4_FS) {
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08002188#ifdef TARGET_USES_MKE2FS
2189 args[0] = "/system/bin/mke2fs";
2190 args[1] = "-M";
2191 args[2] = "/data";
2192 args[3] = "-b";
2193 args[4] = "4096";
2194 args[5] = "-t";
2195 args[6] = "ext4";
2196 args[7] = crypto_blkdev;
2197 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
2198 args[8] = size_str;
2199 num_args = 9;
2200#else
Ken Sumralle550f782013-08-20 13:48:23 -07002201 args[0] = "/system/bin/make_ext4fs";
2202 args[1] = "-a";
2203 args[2] = "/data";
2204 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002205 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002206 args[4] = size_str;
2207 args[5] = crypto_blkdev;
2208 num_args = 6;
Adrien Schildknechte0f409c2016-11-21 15:14:37 -08002209#endif
Ken Sumralle550f782013-08-20 13:48:23 -07002210 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2211 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002212 } else if (type == F2FS_FS) {
2213 args[0] = "/system/bin/mkfs.f2fs";
2214 args[1] = "-t";
2215 args[2] = "-d1";
2216 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002217 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002218 args[4] = size_str;
2219 num_args = 5;
2220 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2221 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002222 } else {
2223 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2224 return -1;
2225 }
2226
Ken Sumralle550f782013-08-20 13:48:23 -07002227 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2228
2229 if (tmp != 0) {
2230 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002231 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002232 if (WIFEXITED(status)) {
2233 if (WEXITSTATUS(status)) {
2234 SLOGE("Error creating filesystem on %s, exit status %d ",
2235 crypto_blkdev, WEXITSTATUS(status));
2236 } else {
2237 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2238 rc = 0;
2239 }
2240 } else {
2241 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2242 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002243 }
2244
2245 return rc;
2246}
2247
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002248#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002249#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2250#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002251
2252/* aligned 32K writes tends to make flash happy.
2253 * SD card association recommends it.
2254 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002255#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002256#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002257#else
2258#define BLOCKS_AT_A_TIME 1024
2259#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002260
2261struct encryptGroupsData
2262{
2263 int realfd;
2264 int cryptofd;
2265 off64_t numblocks;
2266 off64_t one_pct, cur_pct, new_pct;
2267 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002268 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002269 char* real_blkdev, * crypto_blkdev;
2270 int count;
2271 off64_t offset;
2272 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002273 off64_t last_written_sector;
2274 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002275 time_t time_started;
2276 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002277};
2278
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002279static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002280{
2281 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002282
2283 if (is_used) {
2284 data->used_blocks_already_done++;
2285 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002286 if (data->tot_used_blocks) {
2287 data->new_pct = data->used_blocks_already_done / data->one_pct;
2288 } else {
2289 data->new_pct = data->blocks_already_done / data->one_pct;
2290 }
2291
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002292 if (data->new_pct > data->cur_pct) {
2293 char buf[8];
2294 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002295 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002296 property_set("vold.encrypt_progress", buf);
2297 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002298
2299 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002300 struct timespec time_now;
2301 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2302 SLOGW("Error getting time");
2303 } else {
2304 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2305 off64_t remaining_blocks = data->tot_used_blocks
2306 - data->used_blocks_already_done;
2307 int remaining_time = (int)(elapsed_time * remaining_blocks
2308 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002309
Paul Lawrence9c58a872014-09-30 09:12:51 -07002310 // Change time only if not yet set, lower, or a lot higher for
2311 // best user experience
2312 if (data->remaining_time == -1
2313 || remaining_time < data->remaining_time
2314 || remaining_time > data->remaining_time + 60) {
2315 char buf[8];
2316 snprintf(buf, sizeof(buf), "%d", remaining_time);
2317 property_set("vold.encrypt_time_remaining", buf);
2318 data->remaining_time = remaining_time;
2319 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002320 }
2321 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002322}
2323
Paul Lawrence3846be12014-09-22 11:33:54 -07002324static void log_progress(struct encryptGroupsData const* data, bool completed)
2325{
2326 // Precondition - if completed data = 0 else data != 0
2327
2328 // Track progress so we can skip logging blocks
2329 static off64_t offset = -1;
2330
2331 // Need to close existing 'Encrypting from' log?
2332 if (completed || (offset != -1 && data->offset != offset)) {
2333 SLOGI("Encrypted to sector %" PRId64,
2334 offset / info.block_size * CRYPT_SECTOR_SIZE);
2335 offset = -1;
2336 }
2337
2338 // Need to start new 'Encrypting from' log?
2339 if (!completed && offset != data->offset) {
2340 SLOGI("Encrypting from sector %" PRId64,
2341 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2342 }
2343
2344 // Update offset
2345 if (!completed) {
2346 offset = data->offset + (off64_t)data->count * info.block_size;
2347 }
2348}
2349
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002350static int flush_outstanding_data(struct encryptGroupsData* data)
2351{
2352 if (data->count == 0) {
2353 return 0;
2354 }
2355
Elliott Hughes231bdba2014-06-25 18:36:19 -07002356 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002357
2358 if (pread64(data->realfd, data->buffer,
2359 info.block_size * data->count, data->offset)
2360 <= 0) {
2361 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2362 data->real_blkdev);
2363 return -1;
2364 }
2365
2366 if (pwrite64(data->cryptofd, data->buffer,
2367 info.block_size * data->count, data->offset)
2368 <= 0) {
2369 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2370 data->crypto_blkdev);
2371 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002372 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002373 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002374 }
2375
2376 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002377 data->last_written_sector = (data->offset + data->count)
2378 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002379 return 0;
2380}
2381
2382static int encrypt_groups(struct encryptGroupsData* data)
2383{
2384 unsigned int i;
2385 u8 *block_bitmap = 0;
2386 unsigned int block;
2387 off64_t ret;
2388 int rc = -1;
2389
2390 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2391 if (!data->buffer) {
2392 SLOGE("Failed to allocate crypto buffer");
2393 goto errout;
2394 }
2395
2396 block_bitmap = malloc(info.block_size);
2397 if (!block_bitmap) {
2398 SLOGE("failed to allocate block bitmap");
2399 goto errout;
2400 }
2401
2402 for (i = 0; i < aux_info.groups; ++i) {
2403 SLOGI("Encrypting group %d", i);
2404
2405 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2406 u32 block_count = min(info.blocks_per_group,
2407 aux_info.len_blocks - first_block);
2408
2409 off64_t offset = (u64)info.block_size
2410 * aux_info.bg_desc[i].bg_block_bitmap;
2411
2412 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2413 if (ret != (int)info.block_size) {
2414 SLOGE("failed to read all of block group bitmap %d", i);
2415 goto errout;
2416 }
2417
2418 offset = (u64)info.block_size * first_block;
2419
2420 data->count = 0;
2421
2422 for (block = 0; block < block_count; block++) {
liminghaoaa08e582016-01-06 10:30:49 +08002423 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
2424 0 : bitmap_get_bit(block_bitmap, block);
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002425 update_progress(data, used);
2426 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002427 if (data->count == 0) {
2428 data->offset = offset;
2429 }
2430 data->count++;
2431 } else {
2432 if (flush_outstanding_data(data)) {
2433 goto errout;
2434 }
2435 }
2436
2437 offset += info.block_size;
2438
2439 /* Write data if we are aligned or buffer size reached */
2440 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2441 || data->count == BLOCKS_AT_A_TIME) {
2442 if (flush_outstanding_data(data)) {
2443 goto errout;
2444 }
2445 }
Paul Lawrence87999172014-02-20 12:21:31 -08002446
Paul Lawrence73d7a022014-06-09 14:10:09 -07002447 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002448 SLOGE("Stopping encryption due to low battery");
2449 rc = 0;
2450 goto errout;
2451 }
2452
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002453 }
2454 if (flush_outstanding_data(data)) {
2455 goto errout;
2456 }
2457 }
2458
Paul Lawrence87999172014-02-20 12:21:31 -08002459 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002460 rc = 0;
2461
2462errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002463 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002464 free(data->buffer);
2465 free(block_bitmap);
2466 return rc;
2467}
2468
2469static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2470 char *real_blkdev,
2471 off64_t size,
2472 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002473 off64_t tot_size,
2474 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002475{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002476 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002477 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002478 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002479
Paul Lawrence87999172014-02-20 12:21:31 -08002480 if (previously_encrypted_upto > *size_already_done) {
2481 SLOGD("Not fast encrypting since resuming part way through");
2482 return -1;
2483 }
2484
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002485 memset(&data, 0, sizeof(data));
2486 data.real_blkdev = real_blkdev;
2487 data.crypto_blkdev = crypto_blkdev;
2488
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002489 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002490 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2491 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002492 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002493 goto errout;
2494 }
2495
David Ng82fd8042015-01-21 13:55:21 -08002496 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2497 int retries = RETRY_MOUNT_ATTEMPTS;
2498 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2499 if (--retries) {
2500 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2501 crypto_blkdev, errno, strerror(errno));
2502 sleep(RETRY_MOUNT_DELAY_SECONDS);
2503 } else {
2504 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2505 crypto_blkdev, errno, strerror(errno));
2506 rc = ENABLE_INPLACE_ERR_DEV;
2507 goto errout;
2508 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002509 }
2510
2511 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002512 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002513 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002514 goto errout;
2515 }
2516
2517 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002518 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002519 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002520 goto errout;
2521 }
2522
2523 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2524 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2525 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2526
JP Abgrall7fc1de82014-10-10 18:43:41 -07002527 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002528
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002529 data.tot_used_blocks = data.numblocks;
2530 for (i = 0; i < aux_info.groups; ++i) {
2531 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2532 }
2533
2534 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002535 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002536
2537 struct timespec time_started = {0};
2538 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2539 SLOGW("Error getting time at start");
2540 // Note - continue anyway - we'll run with 0
2541 }
2542 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002543 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002544
2545 rc = encrypt_groups(&data);
2546 if (rc) {
2547 SLOGE("Error encrypting groups");
2548 goto errout;
2549 }
2550
Paul Lawrence87999172014-02-20 12:21:31 -08002551 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002552 rc = 0;
2553
2554errout:
2555 close(data.realfd);
2556 close(data.cryptofd);
2557
2558 return rc;
2559}
2560
Paul Lawrence3846be12014-09-22 11:33:54 -07002561static void log_progress_f2fs(u64 block, bool completed)
2562{
2563 // Precondition - if completed data = 0 else data != 0
2564
2565 // Track progress so we can skip logging blocks
2566 static u64 last_block = (u64)-1;
2567
2568 // Need to close existing 'Encrypting from' log?
2569 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2570 SLOGI("Encrypted to block %" PRId64, last_block);
2571 last_block = -1;
2572 }
2573
2574 // Need to start new 'Encrypting from' log?
2575 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2576 SLOGI("Encrypting from block %" PRId64, block);
2577 }
2578
2579 // Update offset
2580 if (!completed) {
2581 last_block = block;
2582 }
2583}
2584
Daniel Rosenberge82df162014-08-15 22:19:23 +00002585static int encrypt_one_block_f2fs(u64 pos, void *data)
2586{
2587 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2588
2589 priv_dat->blocks_already_done = pos - 1;
2590 update_progress(priv_dat, 1);
2591
2592 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2593
2594 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002595 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002596 return -1;
2597 }
2598
2599 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002600 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002601 return -1;
2602 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002603 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002604 }
2605
2606 return 0;
2607}
2608
2609static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2610 char *real_blkdev,
2611 off64_t size,
2612 off64_t *size_already_done,
2613 off64_t tot_size,
2614 off64_t previously_encrypted_upto)
2615{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002616 struct encryptGroupsData data;
2617 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002618 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002619 if (previously_encrypted_upto > *size_already_done) {
2620 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002621 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002622 }
2623 memset(&data, 0, sizeof(data));
2624 data.real_blkdev = real_blkdev;
2625 data.crypto_blkdev = crypto_blkdev;
2626 data.realfd = -1;
2627 data.cryptofd = -1;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002628 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002629 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002630 real_blkdev);
2631 goto errout;
2632 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002633 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002634 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002635 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002636 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002637 goto errout;
2638 }
2639
2640 f2fs_info = generate_f2fs_info(data.realfd);
2641 if (!f2fs_info)
2642 goto errout;
2643
2644 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2645 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2646 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2647
2648 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2649
2650 data.one_pct = data.tot_used_blocks / 100;
2651 data.cur_pct = 0;
2652 data.time_started = time(NULL);
2653 data.remaining_time = -1;
2654
2655 data.buffer = malloc(f2fs_info->block_size);
2656 if (!data.buffer) {
2657 SLOGE("Failed to allocate crypto buffer");
2658 goto errout;
2659 }
2660
2661 data.count = 0;
2662
2663 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2664 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2665
2666 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002667 SLOGE("Error in running over f2fs blocks");
2668 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002669 goto errout;
2670 }
2671
2672 *size_already_done += size;
2673 rc = 0;
2674
2675errout:
2676 if (rc)
2677 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2678
Paul Lawrence3846be12014-09-22 11:33:54 -07002679 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002680 free(f2fs_info);
2681 free(data.buffer);
2682 close(data.realfd);
2683 close(data.cryptofd);
2684
2685 return rc;
2686}
2687
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002688static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2689 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002690 off64_t tot_size,
2691 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002692{
2693 int realfd, cryptofd;
2694 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002695 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002696 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002697 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002698 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002699
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002700 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002701 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002702 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002703 }
2704
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002705 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002706 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2707 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002708 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002709 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002710 }
2711
2712 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2713 * The size passed in is the number of 512 byte sectors in the filesystem.
2714 * So compute the number of whole 4K blocks we should read/write,
2715 * and the remainder.
2716 */
2717 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2718 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002719 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2720 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002721
2722 SLOGE("Encrypting filesystem in place...");
2723
Paul Lawrence87999172014-02-20 12:21:31 -08002724 i = previously_encrypted_upto + 1 - *size_already_done;
2725
2726 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2727 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2728 goto errout;
2729 }
2730
2731 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2732 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2733 goto errout;
2734 }
2735
2736 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2737 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2738 SLOGE("Error reading initial sectors from real_blkdev %s for "
2739 "inplace encrypt\n", crypto_blkdev);
2740 goto errout;
2741 }
2742 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2743 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2744 "inplace encrypt\n", crypto_blkdev);
2745 goto errout;
2746 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002747 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002748 }
2749 }
2750
Ken Sumrall29d8da82011-05-18 17:20:07 -07002751 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002752 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002753 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002754 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002755 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002756 if (new_pct > cur_pct) {
2757 char buf[8];
2758
2759 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002760 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002761 property_set("vold.encrypt_progress", buf);
2762 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002763 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002764 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002765 goto errout;
2766 }
2767 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002768 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2769 goto errout;
2770 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002771 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002772 CRYPT_SECTORS_PER_BUFSIZE,
2773 i * CRYPT_SECTORS_PER_BUFSIZE);
2774 }
2775
Paul Lawrence73d7a022014-06-09 14:10:09 -07002776 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002777 SLOGE("Stopping encryption due to low battery");
2778 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2779 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002780 goto errout;
2781 }
2782 }
2783
2784 /* Do any remaining sectors */
2785 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002786 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2787 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002788 goto errout;
2789 }
Paul Lawrence87999172014-02-20 12:21:31 -08002790 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2791 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002792 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002793 } else {
2794 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002795 }
2796 }
2797
Ken Sumrall29d8da82011-05-18 17:20:07 -07002798 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002799 rc = 0;
2800
2801errout:
2802 close(realfd);
2803 close(cryptofd);
2804
2805 return rc;
2806}
2807
JP Abgrall7fc1de82014-10-10 18:43:41 -07002808/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002809static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2810 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002811 off64_t tot_size,
2812 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002813{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002814 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002815 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002816 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002817 }
2818
2819 if (*size_already_done + size < previously_encrypted_upto) {
2820 *size_already_done += size;
2821 return 0;
2822 }
2823
Daniel Rosenberge82df162014-08-15 22:19:23 +00002824 /* TODO: identify filesystem type.
2825 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2826 * then we will drop down to cryptfs_enable_inplace_f2fs.
2827 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002828 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002829 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002830 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002831 return 0;
2832 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002833 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002834
JP Abgrall7fc1de82014-10-10 18:43:41 -07002835 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002836 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002837 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002838 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002839 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002840 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002841
JP Abgrall7fc1de82014-10-10 18:43:41 -07002842 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002843 size, size_already_done, tot_size,
2844 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002845 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2846
2847 /* Hack for b/17898962, the following is the symptom... */
2848 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2849 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2850 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2851 return ENABLE_INPLACE_ERR_DEV;
2852 }
2853 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002854}
2855
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002856#define CRYPTO_ENABLE_WIPE 1
2857#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002858
2859#define FRAMEWORK_BOOT_WAIT 60
2860
Paul Lawrence87999172014-02-20 12:21:31 -08002861static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2862{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002863 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002864 if (fd == -1) {
2865 SLOGE("Error opening file %s", filename);
2866 return -1;
2867 }
2868
2869 char block[CRYPT_INPLACE_BUFSIZE];
2870 memset(block, 0, sizeof(block));
2871 if (unix_read(fd, block, sizeof(block)) < 0) {
2872 SLOGE("Error reading file %s", filename);
2873 close(fd);
2874 return -1;
2875 }
2876
2877 close(fd);
2878
2879 SHA256_CTX c;
2880 SHA256_Init(&c);
2881 SHA256_Update(&c, block, sizeof(block));
2882 SHA256_Final(buf, &c);
2883
2884 return 0;
2885}
2886
JP Abgrall62c7af32014-06-16 13:01:23 -07002887static int get_fs_type(struct fstab_rec *rec)
2888{
2889 if (!strcmp(rec->fs_type, "ext4")) {
2890 return EXT4_FS;
2891 } else if (!strcmp(rec->fs_type, "f2fs")) {
2892 return F2FS_FS;
2893 } else {
2894 return -1;
2895 }
2896}
2897
Paul Lawrence87999172014-02-20 12:21:31 -08002898static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2899 char *crypto_blkdev, char *real_blkdev,
2900 int previously_encrypted_upto)
2901{
2902 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002903 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002904
Paul Lawrence73d7a022014-06-09 14:10:09 -07002905 if (!is_battery_ok_to_start()) {
2906 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002907 return 0;
2908 }
2909
2910 /* The size of the userdata partition, and add in the vold volumes below */
2911 tot_encryption_size = crypt_ftr->fs_size;
2912
2913 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002914 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2915 int fs_type = get_fs_type(rec);
2916 if (fs_type < 0) {
2917 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2918 return -1;
2919 }
2920 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002921 } else if (how == CRYPTO_ENABLE_INPLACE) {
2922 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2923 crypt_ftr->fs_size, &cur_encryption_done,
2924 tot_encryption_size,
2925 previously_encrypted_upto);
2926
JP Abgrall7fc1de82014-10-10 18:43:41 -07002927 if (rc == ENABLE_INPLACE_ERR_DEV) {
2928 /* Hack for b/17898962 */
2929 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2930 cryptfs_reboot(reboot);
2931 }
2932
Paul Lawrence73d7a022014-06-09 14:10:09 -07002933 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002934 crypt_ftr->encrypted_upto = cur_encryption_done;
2935 }
2936
Paul Lawrence73d7a022014-06-09 14:10:09 -07002937 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002938 /* The inplace routine never actually sets the progress to 100% due
2939 * to the round down nature of integer division, so set it here */
2940 property_set("vold.encrypt_progress", "100");
2941 }
2942 } else {
2943 /* Shouldn't happen */
2944 SLOGE("cryptfs_enable: internal error, unknown option\n");
2945 rc = -1;
2946 }
2947
2948 return rc;
2949}
2950
Paul Lawrence13486032014-02-03 13:28:11 -08002951int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002952 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002953{
2954 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002955 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002956 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002957 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002958 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002959 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002960 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002961 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002962 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002963 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002964 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002965 bool rebootEncryption = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002966
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002967 if (!strcmp(howarg, "wipe")) {
2968 how = CRYPTO_ENABLE_WIPE;
2969 } else if (! strcmp(howarg, "inplace")) {
2970 how = CRYPTO_ENABLE_INPLACE;
2971 } else {
2972 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002973 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002974 }
2975
Paul Lawrence87999172014-02-20 12:21:31 -08002976 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002977 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2978 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2979 /* An encryption was underway and was interrupted */
2980 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2981 crypt_ftr.encrypted_upto = 0;
2982 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002983
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002984 /* At this point, we are in an inconsistent state. Until we successfully
2985 complete encryption, a reboot will leave us broken. So mark the
2986 encryption failed in case that happens.
2987 On successfully completing encryption, remove this flag */
2988 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002989
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002990 put_crypt_ftr_and_key(&crypt_ftr);
2991 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2992 if (!check_ftr_sha(&crypt_ftr)) {
2993 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2994 put_crypt_ftr_and_key(&crypt_ftr);
2995 goto error_unencrypted;
2996 }
2997
2998 /* Doing a reboot-encryption*/
2999 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
3000 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
3001 rebootEncryption = true;
3002 }
Paul Lawrence87999172014-02-20 12:21:31 -08003003 }
3004
3005 property_get("ro.crypto.state", encrypted_state, "");
3006 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
3007 SLOGE("Device is already running encrypted, aborting");
3008 goto error_unencrypted;
3009 }
3010
3011 // TODO refactor fs_mgr_get_crypt_info to get both in one call
3012 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08003013 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003014
Ken Sumrall3ed82362011-01-28 23:31:16 -08003015 /* Get the size of the real block device */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003016 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09003017 if (fd == -1) {
3018 SLOGE("Cannot open block device %s\n", real_blkdev);
3019 goto error_unencrypted;
3020 }
3021 unsigned long nr_sec;
3022 get_blkdev_size(fd, &nr_sec);
3023 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003024 SLOGE("Cannot get size of block device %s\n", real_blkdev);
3025 goto error_unencrypted;
3026 }
3027 close(fd);
3028
3029 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003030 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003031 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00003032 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00003033 if (fs_size_sec == 0)
3034 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3035
Paul Lawrence87999172014-02-20 12:21:31 -08003036 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003037
3038 if (fs_size_sec > max_fs_size_sec) {
3039 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3040 goto error_unencrypted;
3041 }
3042 }
3043
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003044 /* Get a wakelock as this may take a while, and we don't want the
3045 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3046 * wants to keep the screen on, it can grab a full wakelock.
3047 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003048 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003049 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3050
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003051 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003052 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003053 */
3054 property_set("vold.decrypt", "trigger_shutdown_framework");
3055 SLOGD("Just asked init to shut down class main\n");
3056
Jeff Sharkey9c484982015-03-31 10:35:33 -07003057 /* Ask vold to unmount all devices that it manages */
3058 if (vold_unmountAll()) {
3059 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003060 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003061
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003062 /* no_ui means we are being called from init, not settings.
3063 Now we always reboot from settings, so !no_ui means reboot
3064 */
3065 bool onlyCreateHeader = false;
3066 if (!no_ui) {
3067 /* Try fallback, which is to reboot and try there */
3068 onlyCreateHeader = true;
3069 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
3070 if (breadcrumb == 0) {
3071 SLOGE("Failed to create breadcrumb file");
3072 goto error_shutting_down;
3073 }
3074 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003075 }
3076
3077 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003078 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003079 /* Now that /data is unmounted, we need to mount a tmpfs
3080 * /data, set a property saying we're doing inplace encryption,
3081 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003082 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003083 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003084 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003085 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003086 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003087 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003088
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003089 /* restart the framework. */
3090 /* Create necessary paths on /data */
3091 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003092 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003093 }
3094
Ken Sumrall92736ef2012-10-17 20:57:14 -07003095 /* Ugh, shutting down the framework is not synchronous, so until it
3096 * can be fixed, this horrible hack will wait a moment for it all to
3097 * shut down before proceeding. Without it, some devices cannot
3098 * restart the graphics services.
3099 */
3100 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003101 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003102
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003103 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003104 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003105 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003106 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3107 goto error_shutting_down;
3108 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003109
Paul Lawrence87999172014-02-20 12:21:31 -08003110 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3111 crypt_ftr.fs_size = nr_sec
3112 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3113 } else {
3114 crypt_ftr.fs_size = nr_sec;
3115 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003116 /* At this point, we are in an inconsistent state. Until we successfully
3117 complete encryption, a reboot will leave us broken. So mark the
3118 encryption failed in case that happens.
3119 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003120 if (onlyCreateHeader) {
3121 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
3122 } else {
3123 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3124 }
Paul Lawrence87999172014-02-20 12:21:31 -08003125 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003126#ifndef CONFIG_HW_DISK_ENCRYPTION
3127 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3128#else
3129 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3130
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003131 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003132 if (!rc) {
3133 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3134 }
3135
3136 rc = set_hw_device_encryption_key(passwd,
3137 (char*) crypt_ftr.crypto_type_name);
3138 if (!rc) {
3139 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3140 goto error_shutting_down;
3141 }
3142#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003143
Paul Lawrence87999172014-02-20 12:21:31 -08003144 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003145 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
3146 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08003147 SLOGE("Cannot create encrypted master key\n");
3148 goto error_shutting_down;
3149 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003150
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003151 /* Replace scrypted intermediate key if we are preparing for a reboot */
3152 if (onlyCreateHeader) {
3153 unsigned char fake_master_key[KEY_LEN_BYTES];
3154 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
3155 memset(fake_master_key, 0, sizeof(fake_master_key));
3156 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
3157 encrypted_fake_master_key, &crypt_ftr);
3158 }
3159
Paul Lawrence87999172014-02-20 12:21:31 -08003160 /* Write the key to the end of the partition */
3161 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003162
Paul Lawrence87999172014-02-20 12:21:31 -08003163 /* If any persistent data has been remembered, save it.
3164 * If none, create a valid empty table and save that.
3165 */
3166 if (!persist_data) {
3167 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3168 if (pdata) {
3169 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3170 persist_data = pdata;
3171 }
3172 }
3173 if (persist_data) {
3174 save_persistent_data();
3175 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003176 }
3177
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003178 if (onlyCreateHeader) {
3179 sleep(2);
3180 cryptfs_reboot(reboot);
3181 }
3182
3183 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07003184 /* startup service classes main and late_start */
3185 property_set("vold.decrypt", "trigger_restart_min_framework");
3186 SLOGD("Just triggered restart_min_framework\n");
3187
3188 /* OK, the framework is restarted and will soon be showing a
3189 * progress bar. Time to setup an encrypted mapping, and
3190 * either write a new filesystem, or encrypt in place updating
3191 * the progress bar as we work.
3192 */
3193 }
3194
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003195 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003196 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003197 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003198
Paul Lawrence87999172014-02-20 12:21:31 -08003199 /* If we are continuing, check checksums match */
3200 rc = 0;
3201 if (previously_encrypted_upto) {
3202 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3203 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003204
Paul Lawrence87999172014-02-20 12:21:31 -08003205 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3206 sizeof(hash_first_block)) != 0) {
3207 SLOGE("Checksums do not match - trigger wipe");
3208 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003209 }
3210 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003211
Paul Lawrence87999172014-02-20 12:21:31 -08003212 if (!rc) {
3213 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3214 crypto_blkdev, real_blkdev,
3215 previously_encrypted_upto);
3216 }
3217
3218 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003219 if (!rc && how == CRYPTO_ENABLE_INPLACE
3220 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003221 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3222 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003223 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003224 SLOGE("Error calculating checksum for continuing encryption");
3225 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003226 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003227 }
3228
3229 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003230 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003231
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003232 if (! rc) {
3233 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003234 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003235
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003236 if (how == CRYPTO_ENABLE_INPLACE
3237 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003238 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3239 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003240 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003241 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003242
Paul Lawrence6bfed202014-07-28 12:47:22 -07003243 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003244
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003245 if (how == CRYPTO_ENABLE_WIPE
3246 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003247 char value[PROPERTY_VALUE_MAX];
3248 property_get("ro.crypto.state", value, "");
3249 if (!strcmp(value, "")) {
3250 /* default encryption - continue first boot sequence */
3251 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08003252 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003253 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003254 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
3255 // Bring up cryptkeeper that will check the password and set it
3256 property_set("vold.decrypt", "trigger_shutdown_framework");
3257 sleep(2);
3258 property_set("vold.encrypt_progress", "");
3259 cryptfs_trigger_restart_min_framework();
3260 } else {
3261 cryptfs_check_passwd(DEFAULT_PASSWORD);
3262 cryptfs_restart_internal(1);
3263 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003264 return 0;
3265 } else {
3266 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003267 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003268 }
Paul Lawrence87999172014-02-20 12:21:31 -08003269 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003270 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003271 cryptfs_reboot(shutdown);
3272 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003273 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003274 char value[PROPERTY_VALUE_MAX];
3275
Ken Sumrall319369a2012-06-27 16:30:18 -07003276 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003277 if (!strcmp(value, "1")) {
3278 /* wipe data if encryption failed */
3279 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Yabin Cuiffa2e092016-04-06 17:21:38 -07003280 if (!write_bootloader_message("--wipe_data\n--reason=cryptfs_enable_internal\n")) {
3281 SLOGE("could not write bootloader message\n");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003282 }
Paul Lawrence87999172014-02-20 12:21:31 -08003283 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003284 } else {
3285 /* set property to trigger dialog */
3286 property_set("vold.encrypt_progress", "error_partially_encrypted");
3287 release_wake_lock(lockid);
3288 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003289 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003290 }
3291
Ken Sumrall3ed82362011-01-28 23:31:16 -08003292 /* hrm, the encrypt step claims success, but the reboot failed.
3293 * This should not happen.
3294 * Set the property and return. Hope the framework can deal with it.
3295 */
3296 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003297 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003298 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003299
3300error_unencrypted:
3301 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003302 if (lockid[0]) {
3303 release_wake_lock(lockid);
3304 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003305 return -1;
3306
3307error_shutting_down:
3308 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3309 * but the framework is stopped and not restarted to show the error, so it's up to
3310 * vold to restart the system.
3311 */
3312 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003313 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003314
3315 /* shouldn't get here */
3316 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003317 if (lockid[0]) {
3318 release_wake_lock(lockid);
3319 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003320 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003321}
3322
Paul Lawrence569649f2015-09-09 12:13:00 -07003323int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003324{
Paul Lawrence569649f2015-09-09 12:13:00 -07003325 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003326}
3327
Paul Lawrence569649f2015-09-09 12:13:00 -07003328int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003329{
3330 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07003331 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003332}
3333
3334int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003335{
Paul Crowley38132a12016-02-09 09:50:32 +00003336 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003337 SLOGE("cryptfs_changepw not valid for file encryption");
3338 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003339 }
3340
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003341 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003342 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003343
3344 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003345 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003346 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003347 return -1;
3348 }
3349
Paul Lawrencef4faa572014-01-29 13:31:03 -08003350 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3351 SLOGE("Invalid crypt_type %d", crypt_type);
3352 return -1;
3353 }
3354
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003355 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003356 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003357 SLOGE("Error getting crypt footer and key");
3358 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003359 }
3360
Paul Lawrencef4faa572014-01-29 13:31:03 -08003361 crypt_ftr.crypt_type = crypt_type;
3362
JP Abgrall933216c2015-02-11 13:44:32 -08003363 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003364 : newpw,
3365 crypt_ftr.salt,
3366 saved_master_key,
3367 crypt_ftr.master_key,
3368 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003369 if (rc) {
3370 SLOGE("Encrypt master key failed: %d", rc);
3371 return -1;
3372 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003373 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003374 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003375
Ajay Dudani87701e22014-09-17 21:02:52 -07003376#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003377 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3378 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3379 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3380 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3381 if (!rc)
3382 return -1;
3383 } else {
3384 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3385 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3386 if (!rc)
3387 return -1;
3388 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003389 }
3390#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003391 return 0;
3392}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003393
Rubin Xu85c01f92014-10-13 12:49:54 +01003394static unsigned int persist_get_max_entries(int encrypted) {
3395 struct crypt_mnt_ftr crypt_ftr;
3396 unsigned int dsize;
3397 unsigned int max_persistent_entries;
3398
3399 /* If encrypted, use the values from the crypt_ftr, otherwise
3400 * use the values for the current spec.
3401 */
3402 if (encrypted) {
3403 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3404 return -1;
3405 }
3406 dsize = crypt_ftr.persist_data_size;
3407 } else {
3408 dsize = CRYPT_PERSIST_DATA_SIZE;
3409 }
3410
3411 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3412 sizeof(struct crypt_persist_entry);
3413
3414 return max_persistent_entries;
3415}
3416
3417static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003418{
3419 unsigned int i;
3420
3421 if (persist_data == NULL) {
3422 return -1;
3423 }
3424 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3425 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3426 /* We found it! */
3427 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3428 return 0;
3429 }
3430 }
3431
3432 return -1;
3433}
3434
Rubin Xu85c01f92014-10-13 12:49:54 +01003435static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003436{
3437 unsigned int i;
3438 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003439 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003440
3441 if (persist_data == NULL) {
3442 return -1;
3443 }
3444
Rubin Xu85c01f92014-10-13 12:49:54 +01003445 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003446
3447 num = persist_data->persist_valid_entries;
3448
3449 for (i = 0; i < num; i++) {
3450 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3451 /* We found an existing entry, update it! */
3452 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3453 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3454 return 0;
3455 }
3456 }
3457
3458 /* We didn't find it, add it to the end, if there is room */
3459 if (persist_data->persist_valid_entries < max_persistent_entries) {
3460 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3461 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3462 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3463 persist_data->persist_valid_entries++;
3464 return 0;
3465 }
3466
3467 return -1;
3468}
3469
Rubin Xu85c01f92014-10-13 12:49:54 +01003470/**
3471 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3472 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3473 */
3474static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003475 unsigned int field_len;
3476 unsigned int key_index;
3477 field_len = strlen(field);
3478
3479 if (index == 0) {
3480 // The first key in a multi-entry field is just the filedname itself.
3481 if (!strcmp(key, field)) {
3482 return 1;
3483 }
3484 }
3485 // Match key against "%s_%d" % (field, index)
3486 if (strlen(key) < field_len + 1 + 1) {
3487 // Need at least a '_' and a digit.
3488 return 0;
3489 }
3490 if (strncmp(key, field, field_len)) {
3491 // If the key does not begin with field, it's not a match.
3492 return 0;
3493 }
3494 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3495 return 0;
3496 }
3497 return key_index >= index;
3498}
3499
3500/*
3501 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3502 * remaining entries starting from index will be deleted.
3503 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3504 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3505 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3506 *
3507 */
3508static int persist_del_keys(const char *fieldname, unsigned index)
3509{
3510 unsigned int i;
3511 unsigned int j;
3512 unsigned int num;
3513
3514 if (persist_data == NULL) {
3515 return PERSIST_DEL_KEY_ERROR_OTHER;
3516 }
3517
3518 num = persist_data->persist_valid_entries;
3519
3520 j = 0; // points to the end of non-deleted entries.
3521 // Filter out to-be-deleted entries in place.
3522 for (i = 0; i < num; i++) {
3523 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3524 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3525 j++;
3526 }
3527 }
3528
3529 if (j < num) {
3530 persist_data->persist_valid_entries = j;
3531 // Zeroise the remaining entries
3532 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3533 return PERSIST_DEL_KEY_OK;
3534 } else {
3535 // Did not find an entry matching the given fieldname
3536 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3537 }
3538}
3539
3540static int persist_count_keys(const char *fieldname)
3541{
3542 unsigned int i;
3543 unsigned int count;
3544
3545 if (persist_data == NULL) {
3546 return -1;
3547 }
3548
3549 count = 0;
3550 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3551 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3552 count++;
3553 }
3554 }
3555
3556 return count;
3557}
3558
Ken Sumrall160b4d62013-04-22 12:15:39 -07003559/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003560int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003561{
Paul Crowley38132a12016-02-09 09:50:32 +00003562 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003563 SLOGE("Cannot get field when file encrypted");
3564 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003565 }
3566
Ken Sumrall160b4d62013-04-22 12:15:39 -07003567 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003568 /* CRYPTO_GETFIELD_OK is success,
3569 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3570 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3571 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003572 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003573 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3574 int i;
3575 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003576
3577 if (persist_data == NULL) {
3578 load_persistent_data();
3579 if (persist_data == NULL) {
3580 SLOGE("Getfield error, cannot load persistent data");
3581 goto out;
3582 }
3583 }
3584
Rubin Xu85c01f92014-10-13 12:49:54 +01003585 // Read value from persistent entries. If the original value is split into multiple entries,
3586 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003587 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003588 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3589 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3590 // value too small
3591 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3592 goto out;
3593 }
3594 rc = CRYPTO_GETFIELD_OK;
3595
3596 for (i = 1; /* break explicitly */; i++) {
3597 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3598 (int) sizeof(temp_field)) {
3599 // If the fieldname is very long, we stop as soon as it begins to overflow the
3600 // maximum field length. At this point we have in fact fully read out the original
3601 // value because cryptfs_setfield would not allow fields with longer names to be
3602 // written in the first place.
3603 break;
3604 }
3605 if (!persist_get_key(temp_field, temp_value)) {
3606 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3607 // value too small.
3608 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3609 goto out;
3610 }
3611 } else {
3612 // Exhaust all entries.
3613 break;
3614 }
3615 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003616 } else {
3617 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003618 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003619 }
3620
3621out:
3622 return rc;
3623}
3624
3625/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003626int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003627{
Paul Crowley38132a12016-02-09 09:50:32 +00003628 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003629 SLOGE("Cannot set field when file encrypted");
3630 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003631 }
3632
Ken Sumrall160b4d62013-04-22 12:15:39 -07003633 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003634 /* 0 is success, negative values are error */
3635 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003636 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003637 unsigned int field_id;
3638 char temp_field[PROPERTY_KEY_MAX];
3639 unsigned int num_entries;
3640 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003641
3642 if (persist_data == NULL) {
3643 load_persistent_data();
3644 if (persist_data == NULL) {
3645 SLOGE("Setfield error, cannot load persistent data");
3646 goto out;
3647 }
3648 }
3649
3650 property_get("ro.crypto.state", encrypted_state, "");
3651 if (!strcmp(encrypted_state, "encrypted") ) {
3652 encrypted = 1;
3653 }
3654
Rubin Xu85c01f92014-10-13 12:49:54 +01003655 // Compute the number of entries required to store value, each entry can store up to
3656 // (PROPERTY_VALUE_MAX - 1) chars
3657 if (strlen(value) == 0) {
3658 // Empty value also needs one entry to store.
3659 num_entries = 1;
3660 } else {
3661 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3662 }
3663
3664 max_keylen = strlen(fieldname);
3665 if (num_entries > 1) {
3666 // Need an extra "_%d" suffix.
3667 max_keylen += 1 + log10(num_entries);
3668 }
3669 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3670 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003671 goto out;
3672 }
3673
Rubin Xu85c01f92014-10-13 12:49:54 +01003674 // Make sure we have enough space to write the new value
3675 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3676 persist_get_max_entries(encrypted)) {
3677 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3678 goto out;
3679 }
3680
3681 // Now that we know persist_data has enough space for value, let's delete the old field first
3682 // to make up space.
3683 persist_del_keys(fieldname, 0);
3684
3685 if (persist_set_key(fieldname, value, encrypted)) {
3686 // fail to set key, should not happen as we have already checked the available space
3687 SLOGE("persist_set_key() error during setfield()");
3688 goto out;
3689 }
3690
3691 for (field_id = 1; field_id < num_entries; field_id++) {
3692 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3693
3694 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3695 // fail to set key, should not happen as we have already checked the available space.
3696 SLOGE("persist_set_key() error during setfield()");
3697 goto out;
3698 }
3699 }
3700
Ken Sumrall160b4d62013-04-22 12:15:39 -07003701 /* If we are running encrypted, save the persistent data now */
3702 if (encrypted) {
3703 if (save_persistent_data()) {
3704 SLOGE("Setfield error, cannot save persistent data");
3705 goto out;
3706 }
3707 }
3708
Rubin Xu85c01f92014-10-13 12:49:54 +01003709 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003710
3711out:
3712 return rc;
3713}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003714
3715/* Checks userdata. Attempt to mount the volume if default-
3716 * encrypted.
3717 * On success trigger next init phase and return 0.
3718 * Currently do not handle failure - see TODO below.
3719 */
3720int cryptfs_mount_default_encrypted(void)
3721{
Paul Lawrence84274cc2016-04-15 15:41:33 -07003722 int crypt_type = cryptfs_get_password_type();
3723 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3724 SLOGE("Bad crypt type - error");
3725 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3726 SLOGD("Password is not default - "
3727 "starting min framework to prompt");
3728 property_set("vold.decrypt", "trigger_restart_min_framework");
3729 return 0;
3730 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3731 SLOGD("Password is default - restarting filesystem");
3732 cryptfs_restart_internal(0);
3733 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003734 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003735 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003736 }
3737
Paul Lawrence6bfed202014-07-28 12:47:22 -07003738 /** Corrupt. Allow us to boot into framework, which will detect bad
3739 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003740 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003741 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003742 return 0;
3743}
3744
3745/* Returns type of the password, default, pattern, pin or password.
3746 */
3747int cryptfs_get_password_type(void)
3748{
Paul Crowley38132a12016-02-09 09:50:32 +00003749 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003750 SLOGE("cryptfs_get_password_type not valid for file encryption");
3751 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003752 }
3753
Paul Lawrencef4faa572014-01-29 13:31:03 -08003754 struct crypt_mnt_ftr crypt_ftr;
3755
3756 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3757 SLOGE("Error getting crypt footer and key\n");
3758 return -1;
3759 }
3760
Paul Lawrence6bfed202014-07-28 12:47:22 -07003761 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3762 return -1;
3763 }
3764
Paul Lawrencef4faa572014-01-29 13:31:03 -08003765 return crypt_ftr.crypt_type;
3766}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003767
Paul Lawrence05335c32015-03-05 09:46:23 -08003768const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003769{
Paul Crowley38132a12016-02-09 09:50:32 +00003770 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003771 SLOGE("cryptfs_get_password not valid for file encryption");
3772 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003773 }
3774
Paul Lawrence399317e2014-03-10 13:20:50 -07003775 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003776 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003777 if (now.tv_sec < password_expiry_time) {
3778 return password;
3779 } else {
3780 cryptfs_clear_password();
3781 return 0;
3782 }
3783}
3784
3785void cryptfs_clear_password()
3786{
3787 if (password) {
3788 size_t len = strlen(password);
3789 memset(password, 0, len);
3790 free(password);
3791 password = 0;
3792 password_expiry_time = 0;
3793 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003794}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003795
3796int cryptfs_enable_file()
3797{
Paul Crowley38132a12016-02-09 09:50:32 +00003798 return e4crypt_initialize_global_de();
Paul Lawrence731a7a22015-04-28 22:14:15 +00003799}
3800
Paul Lawrence0c247462015-10-29 10:30:57 -07003801int cryptfs_isConvertibleToFBE()
3802{
3803 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3804 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
3805}
3806
Paul Lawrence731a7a22015-04-28 22:14:15 +00003807int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3808{
3809 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3810 SLOGE("Failed to initialize crypt_ftr");
3811 return -1;
3812 }
3813
3814 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3815 crypt_ftr->salt, crypt_ftr)) {
3816 SLOGE("Cannot create encrypted master key\n");
3817 return -1;
3818 }
3819
3820 //crypt_ftr->keysize = key_length / 8;
3821 return 0;
3822}
3823
3824int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3825 unsigned char* master_key)
3826{
3827 int rc;
3828
Paul Lawrence731a7a22015-04-28 22:14:15 +00003829 unsigned char* intermediate_key = 0;
3830 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003831
3832 if (password == 0 || *password == 0) {
3833 password = DEFAULT_PASSWORD;
3834 }
3835
Paul Lawrence731a7a22015-04-28 22:14:15 +00003836 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3837 &intermediate_key_size);
3838
Paul Lawrence300dae72016-03-11 11:02:52 -08003839 if (rc) {
3840 SLOGE("Can't calculate intermediate key");
3841 return rc;
3842 }
3843
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003844 int N = 1 << ftr->N_factor;
3845 int r = 1 << ftr->r_factor;
3846 int p = 1 << ftr->p_factor;
3847
3848 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3849
3850 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3851 ftr->salt, sizeof(ftr->salt), N, r, p,
3852 scrypted_intermediate_key,
3853 sizeof(scrypted_intermediate_key));
3854
3855 free(intermediate_key);
3856
3857 if (rc) {
Paul Lawrence300dae72016-03-11 11:02:52 -08003858 SLOGE("Can't scrypt intermediate key");
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003859 return rc;
3860 }
3861
3862 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3863 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00003864}
3865
3866int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3867 const unsigned char* master_key)
3868{
3869 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3870 ftr);
3871}
Paul Lawrence6e410592016-05-24 14:20:38 -07003872
3873const char* cryptfs_get_file_encryption_mode()
3874{
3875 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3876 return fs_mgr_get_file_encryption_mode(rec);
3877}