blob: fcc9724b7571f34f8db1c69f87761ef69ec7bdfc [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080041#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080046#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080047#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080048#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080049#define LOG_TAG "Cryptfs"
50#include "cutils/log.h"
51#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070052#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080053#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070054#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000055#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070056#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070057#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070058#include "crypto_scrypt.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000059#include "Ext4Crypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080060#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000061#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080062#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080063#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080064
Shawn Willden8af33352015-02-24 09:51:34 -070065#include <hardware/keymaster0.h>
Shawn Willdenda6e8992015-06-03 09:40:45 -060066#include <hardware/keymaster1.h>
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070067
Mark Salyzyn3e971272014-01-21 13:27:04 -080068#define UNUSED __attribute__((unused))
69
Mark Salyzyn5eecc442014-02-12 14:16:14 -080070#define UNUSED __attribute__((unused))
71
Ajay Dudani87701e22014-09-17 21:02:52 -070072#ifdef CONFIG_HW_DISK_ENCRYPTION
73#include "cryptfs_hw.h"
74#endif
75
Ken Sumrall8f869aa2010-12-03 03:47:09 -080076#define DM_CRYPT_BUF_SIZE 4096
77
Jason parks70a4b3f2011-01-28 10:10:47 -060078#define HASH_COUNT 2000
79#define KEY_LEN_BYTES 16
80#define IV_LEN_BYTES 16
81
Ken Sumrall29d8da82011-05-18 17:20:07 -070082#define KEY_IN_FOOTER "footer"
83
Paul Lawrence3bd36d52015-06-09 13:37:44 -070084#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080085
Paul Lawrence3d99eba2015-11-20 07:07:19 -080086#define CRYPTO_BLOCK_DEVICE "userdata"
87
88#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
89
Ken Sumrall29d8da82011-05-18 17:20:07 -070090#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070091#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070092
Ken Sumralle919efe2012-09-29 17:07:41 -070093#define TABLE_LOAD_RETRIES 10
94
Shawn Willden47ba10d2014-09-03 17:07:06 -060095#define RSA_KEY_SIZE 2048
96#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
97#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060098#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070099
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700100#define RETRY_MOUNT_ATTEMPTS 10
101#define RETRY_MOUNT_DELAY_SECONDS 1
102
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800103char *me = "cryptfs";
104
Jason parks70a4b3f2011-01-28 10:10:47 -0600105static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700106static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600107static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700108static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800109
Shawn Willdenda6e8992015-06-03 09:40:45 -0600110static int keymaster_init(keymaster0_device_t **keymaster0_dev,
111 keymaster1_device_t **keymaster1_dev)
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700112{
113 int rc;
114
115 const hw_module_t* mod;
116 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
117 if (rc) {
118 ALOGE("could not find any keystore module");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600119 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700120 }
121
Shawn Willdenda6e8992015-06-03 09:40:45 -0600122 SLOGI("keymaster module name is %s", mod->name);
123 SLOGI("keymaster version is %d", mod->module_api_version);
124
125 *keymaster0_dev = NULL;
126 *keymaster1_dev = NULL;
127 if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
128 SLOGI("Found keymaster1 module, using keymaster1 API.");
129 rc = keymaster1_open(mod, keymaster1_dev);
130 } else {
131 SLOGI("Found keymaster0 module, using keymaster0 API.");
132 rc = keymaster0_open(mod, keymaster0_dev);
133 }
134
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700135 if (rc) {
136 ALOGE("could not open keymaster device in %s (%s)",
Shawn Willdenda6e8992015-06-03 09:40:45 -0600137 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
138 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700139 }
140
141 return 0;
142
Shawn Willdenda6e8992015-06-03 09:40:45 -0600143err:
144 *keymaster0_dev = NULL;
145 *keymaster1_dev = NULL;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700146 return rc;
147}
148
149/* Should we use keymaster? */
150static int keymaster_check_compatibility()
151{
Shawn Willdenda6e8992015-06-03 09:40:45 -0600152 keymaster0_device_t *keymaster0_dev = 0;
153 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700154 int rc = 0;
155
Shawn Willdenda6e8992015-06-03 09:40:45 -0600156 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700157 SLOGE("Failed to init keymaster");
158 rc = -1;
159 goto out;
160 }
161
Shawn Willdenda6e8992015-06-03 09:40:45 -0600162 if (keymaster1_dev) {
163 rc = 1;
164 goto out;
165 }
Paul Lawrence8c008392014-05-06 14:02:48 -0700166
Shawn Willdenda6e8992015-06-03 09:40:45 -0600167 // TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
168 // should work.
169 if (keymaster0_dev->common.module->module_api_version
Paul Lawrence8c008392014-05-06 14:02:48 -0700170 < KEYMASTER_MODULE_API_VERSION_0_3) {
171 rc = 0;
172 goto out;
173 }
174
Shawn Willdenda6e8992015-06-03 09:40:45 -0600175 if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
176 (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700177 rc = 1;
178 }
179
180out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600181 if (keymaster1_dev) {
182 keymaster1_close(keymaster1_dev);
183 }
184 if (keymaster0_dev) {
185 keymaster0_close(keymaster0_dev);
186 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700187 return rc;
188}
189
190/* Create a new keymaster key and store it in this footer */
191static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
192{
193 uint8_t* key = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600194 keymaster0_device_t *keymaster0_dev = 0;
195 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700196
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800197 if (ftr->keymaster_blob_size) {
198 SLOGI("Already have key");
199 return 0;
200 }
201
Shawn Willdenda6e8992015-06-03 09:40:45 -0600202 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700203 SLOGE("Failed to init keymaster");
204 return -1;
205 }
206
207 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600208 size_t key_size = 0;
209 if (keymaster1_dev) {
210 keymaster_key_param_t params[] = {
211 /* Algorithm & size specifications. Stick with RSA for now. Switch to AES later. */
212 keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
213 keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
214 keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700215
Shawn Willden86af3552015-06-24 07:21:54 -0700216 /* The only allowed purpose for this key is signing. */
217 keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
218
219 /* Padding & digest specifications. */
Shawn Willdenda6e8992015-06-03 09:40:45 -0600220 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
Shawn Willdenda6e8992015-06-03 09:40:45 -0600221 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700222
Shawn Willdenda6e8992015-06-03 09:40:45 -0600223 /* Require that the key be usable in standalone mode. File system isn't available. */
224 keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
225
226 /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
227 keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
228
Shawn Willdenda6e8992015-06-03 09:40:45 -0600229 /* Rate-limit key usage attempts, to rate-limit brute force */
230 keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
231 };
232 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
233 keymaster_key_blob_t key_blob;
234 keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, &param_set,
235 &key_blob,
236 NULL /* characteristics */);
237 if (error != KM_ERROR_OK) {
238 SLOGE("Failed to generate keymaster1 key, error %d", error);
239 rc = -1;
240 goto out;
241 }
242
243 key = (uint8_t*)key_blob.key_material;
244 key_size = key_blob.key_material_size;
245 }
246 else if (keymaster0_dev) {
247 keymaster_rsa_keygen_params_t params;
248 memset(&params, '\0', sizeof(params));
249 params.public_exponent = RSA_EXPONENT;
250 params.modulus_size = RSA_KEY_SIZE;
251
252 if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, &params,
253 &key, &key_size)) {
254 SLOGE("Failed to generate keypair");
255 rc = -1;
256 goto out;
257 }
258 } else {
259 SLOGE("Cryptfs bug: keymaster_init succeeded but didn't initialize a device");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700260 rc = -1;
261 goto out;
262 }
263
264 if (key_size > KEYMASTER_BLOB_SIZE) {
265 SLOGE("Keymaster key too large for crypto footer");
266 rc = -1;
267 goto out;
268 }
269
270 memcpy(ftr->keymaster_blob, key, key_size);
271 ftr->keymaster_blob_size = key_size;
272
273out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600274 if (keymaster0_dev)
275 keymaster0_close(keymaster0_dev);
276 if (keymaster1_dev)
277 keymaster1_close(keymaster1_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700278 free(key);
279 return rc;
280}
281
Shawn Willdene17a9c42014-09-08 13:04:08 -0600282/* This signs the given object using the keymaster key. */
283static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600284 const unsigned char *object,
285 const size_t object_size,
286 unsigned char **signature,
287 size_t *signature_size)
288{
289 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600290 keymaster0_device_t *keymaster0_dev = 0;
291 keymaster1_device_t *keymaster1_dev = 0;
292 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600293 SLOGE("Failed to init keymaster");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600294 rc = -1;
295 goto out;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600296 }
297
Shawn Willden47ba10d2014-09-03 17:07:06 -0600298 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600299 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600300 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600301
Shawn Willdene17a9c42014-09-08 13:04:08 -0600302 // To sign a message with RSA, the message must satisfy two
303 // constraints:
304 //
305 // 1. The message, when interpreted as a big-endian numeric value, must
306 // be strictly less than the public modulus of the RSA key. Note
307 // that because the most significant bit of the public modulus is
308 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
309 // key), an n-bit message with most significant bit 0 always
310 // satisfies this requirement.
311 //
312 // 2. The message must have the same length in bits as the public
313 // modulus of the RSA key. This requirement isn't mathematically
314 // necessary, but is necessary to ensure consistency in
315 // implementations.
316 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600317 case KDF_SCRYPT_KEYMASTER:
318 // This ensures the most significant byte of the signed message
319 // is zero. We could have zero-padded to the left instead, but
320 // this approach is slightly more robust against changes in
321 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600322 // so) because we really should be using a proper deterministic
323 // RSA padding function, such as PKCS1.
Shawn Willdene17a9c42014-09-08 13:04:08 -0600324 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
325 SLOGI("Signing safely-padded object");
326 break;
327 default:
328 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Shawn Willdenda6e8992015-06-03 09:40:45 -0600329 rc = -1;
330 goto out;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600331 }
332
Shawn Willdenda6e8992015-06-03 09:40:45 -0600333 if (keymaster0_dev) {
334 keymaster_rsa_sign_params_t params;
335 params.digest_type = DIGEST_NONE;
336 params.padding_type = PADDING_NONE;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600337
Shawn Willdenda6e8992015-06-03 09:40:45 -0600338 rc = keymaster0_dev->sign_data(keymaster0_dev,
339 &params,
340 ftr->keymaster_blob,
341 ftr->keymaster_blob_size,
342 to_sign,
343 to_sign_size,
344 signature,
345 signature_size);
346 goto out;
347 } else if (keymaster1_dev) {
348 keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
349 keymaster_key_param_t params[] = {
350 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
351 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
352 };
353 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
354 keymaster_operation_handle_t op_handle;
355 keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
356 &param_set, NULL /* out_params */,
357 &op_handle);
Shawn Willden04170602015-06-18 12:26:59 -0600358 if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
Shawn Willdenda6e8992015-06-03 09:40:45 -0600359 // Key usage has been rate-limited. Wait a bit and try again.
360 sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
361 error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
362 &param_set, NULL /* out_params */,
363 &op_handle);
364 }
365 if (error != KM_ERROR_OK) {
366 SLOGE("Error starting keymaster signature transaction: %d", error);
367 rc = -1;
368 goto out;
369 }
370
371 keymaster_blob_t input = { to_sign, to_sign_size };
372 size_t input_consumed;
373 error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
374 &input, &input_consumed, NULL /* out_params */,
375 NULL /* output */);
376 if (error != KM_ERROR_OK) {
377 SLOGE("Error sending data to keymaster signature transaction: %d", error);
378 rc = -1;
379 goto out;
380 }
381 if (input_consumed != to_sign_size) {
382 // This should never happen. If it does, it's a bug in the keymaster implementation.
383 SLOGE("Keymaster update() did not consume all data.");
384 keymaster1_dev->abort(keymaster1_dev, op_handle);
385 rc = -1;
386 goto out;
387 }
388
389 keymaster_blob_t tmp_sig;
390 error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
391 NULL /* verify signature */, NULL /* out_params */,
392 &tmp_sig);
393 if (error != KM_ERROR_OK) {
394 SLOGE("Error finishing keymaster signature transaction: %d", error);
395 rc = -1;
396 goto out;
397 }
398
399 *signature = (uint8_t*)tmp_sig.data;
400 *signature_size = tmp_sig.data_length;
401 } else {
402 SLOGE("Cryptfs bug: keymaster_init succeded but didn't initialize a device.");
403 rc = -1;
404 goto out;
405 }
406
407 out:
408 if (keymaster1_dev)
409 keymaster1_close(keymaster1_dev);
410 if (keymaster0_dev)
411 keymaster0_close(keymaster0_dev);
412
413 return rc;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600414}
415
Paul Lawrence399317e2014-03-10 13:20:50 -0700416/* Store password when userdata is successfully decrypted and mounted.
417 * Cleared by cryptfs_clear_password
418 *
419 * To avoid a double prompt at boot, we need to store the CryptKeeper
420 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
421 * Since the entire framework is torn down and rebuilt after encryption,
422 * we have to use a daemon or similar to store the password. Since vold
423 * is secured against IPC except from system processes, it seems a reasonable
424 * place to store this.
425 *
426 * password should be cleared once it has been used.
427 *
428 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800429 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700430static char* password = 0;
431static int password_expiry_time = 0;
432static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800433
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800434extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800435
Paul Lawrence87999172014-02-20 12:21:31 -0800436enum RebootType {reboot, recovery, shutdown};
437static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700438{
Paul Lawrence87999172014-02-20 12:21:31 -0800439 switch(rt) {
440 case reboot:
441 property_set(ANDROID_RB_PROPERTY, "reboot");
442 break;
443
444 case recovery:
445 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
446 break;
447
448 case shutdown:
449 property_set(ANDROID_RB_PROPERTY, "shutdown");
450 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700451 }
Paul Lawrence87999172014-02-20 12:21:31 -0800452
Ken Sumralladfba362013-06-04 16:37:52 -0700453 sleep(20);
454
455 /* Shouldn't get here, reboot should happen before sleep times out */
456 return;
457}
458
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800459static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
460{
461 memset(io, 0, dataSize);
462 io->data_size = dataSize;
463 io->data_start = sizeof(struct dm_ioctl);
464 io->version[0] = 4;
465 io->version[1] = 0;
466 io->version[2] = 0;
467 io->flags = flags;
468 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100469 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800470 }
471}
472
Kenny Rootc4c70f12013-06-14 12:11:38 -0700473/**
474 * Gets the default device scrypt parameters for key derivation time tuning.
475 * The parameters should lead to about one second derivation time for the
476 * given device.
477 */
478static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700479 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000480 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700481
Paul Crowley63c18d32016-02-10 14:02:47 +0000482 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
483 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
484 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
485 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700486 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000487 ftr->N_factor = Nf;
488 ftr->r_factor = rf;
489 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700490}
491
Ken Sumrall3ed82362011-01-28 23:31:16 -0800492static unsigned int get_fs_size(char *dev)
493{
494 int fd, block_size;
495 struct ext4_super_block sb;
496 off64_t len;
497
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700498 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800499 SLOGE("Cannot open device to get filesystem size ");
500 return 0;
501 }
502
503 if (lseek64(fd, 1024, SEEK_SET) < 0) {
504 SLOGE("Cannot seek to superblock");
505 return 0;
506 }
507
508 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
509 SLOGE("Cannot read superblock");
510 return 0;
511 }
512
513 close(fd);
514
Daniel Rosenberge82df162014-08-15 22:19:23 +0000515 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
516 SLOGE("Not a valid ext4 superblock");
517 return 0;
518 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800519 block_size = 1024 << sb.s_log_block_size;
520 /* compute length in bytes */
521 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
522
523 /* return length in sectors */
524 return (unsigned int) (len / 512);
525}
526
Ken Sumrall160b4d62013-04-22 12:15:39 -0700527static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
528{
529 static int cached_data = 0;
530 static off64_t cached_off = 0;
531 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
532 int fd;
533 char key_loc[PROPERTY_VALUE_MAX];
534 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700535 int rc = -1;
536
537 if (!cached_data) {
538 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
539
540 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700541 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700542 SLOGE("Cannot open real block device %s\n", real_blkdev);
543 return -1;
544 }
545
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900546 unsigned long nr_sec = 0;
547 get_blkdev_size(fd, &nr_sec);
548 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700549 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
550 * encryption info footer and key, and plenty of bytes to spare for future
551 * growth.
552 */
553 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
554 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
555 cached_data = 1;
556 } else {
557 SLOGE("Cannot get size of block device %s\n", real_blkdev);
558 }
559 close(fd);
560 } else {
561 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
562 cached_off = 0;
563 cached_data = 1;
564 }
565 }
566
567 if (cached_data) {
568 if (metadata_fname) {
569 *metadata_fname = cached_metadata_fname;
570 }
571 if (off) {
572 *off = cached_off;
573 }
574 rc = 0;
575 }
576
577 return rc;
578}
579
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800580/* Set sha256 checksum in structure */
581static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
582{
583 SHA256_CTX c;
584 SHA256_Init(&c);
585 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
586 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
587 SHA256_Final(crypt_ftr->sha256, &c);
588}
589
Ken Sumralle8744072011-01-18 22:01:55 -0800590/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800591 * update the failed mount count but not change the key.
592 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700593static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800594{
595 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800596 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700597 /* starting_off is set to the SEEK_SET offset
598 * where the crypto structure starts
599 */
600 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800601 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700602 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700603 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800604
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800605 set_ftr_sha(crypt_ftr);
606
Ken Sumrall160b4d62013-04-22 12:15:39 -0700607 if (get_crypt_ftr_info(&fname, &starting_off)) {
608 SLOGE("Unable to get crypt_ftr_info\n");
609 return -1;
610 }
611 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700612 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700613 return -1;
614 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700615 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700616 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700617 return -1;
618 }
619
620 /* Seek to the start of the crypt footer */
621 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
622 SLOGE("Cannot seek to real block device footer\n");
623 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800624 }
625
626 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
627 SLOGE("Cannot write real block device footer\n");
628 goto errout;
629 }
630
Ken Sumrall3be890f2011-09-14 16:53:46 -0700631 fstat(fd, &statbuf);
632 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700633 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700634 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800635 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800636 goto errout;
637 }
638 }
639
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800640 /* Success! */
641 rc = 0;
642
643errout:
644 close(fd);
645 return rc;
646
647}
648
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800649static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
650{
651 struct crypt_mnt_ftr copy;
652 memcpy(&copy, crypt_ftr, sizeof(copy));
653 set_ftr_sha(&copy);
654 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
655}
656
Ken Sumrall160b4d62013-04-22 12:15:39 -0700657static inline int unix_read(int fd, void* buff, int len)
658{
659 return TEMP_FAILURE_RETRY(read(fd, buff, len));
660}
661
662static inline int unix_write(int fd, const void* buff, int len)
663{
664 return TEMP_FAILURE_RETRY(write(fd, buff, len));
665}
666
667static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
668{
669 memset(pdata, 0, len);
670 pdata->persist_magic = PERSIST_DATA_MAGIC;
671 pdata->persist_valid_entries = 0;
672}
673
674/* A routine to update the passed in crypt_ftr to the lastest version.
675 * fd is open read/write on the device that holds the crypto footer and persistent
676 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
677 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
678 */
679static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
680{
Kenny Root7434b312013-06-14 11:29:53 -0700681 int orig_major = crypt_ftr->major_version;
682 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700683
Kenny Root7434b312013-06-14 11:29:53 -0700684 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
685 struct crypt_persist_data *pdata;
686 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700687
Kenny Rootc4c70f12013-06-14 12:11:38 -0700688 SLOGW("upgrading crypto footer to 1.1");
689
Kenny Root7434b312013-06-14 11:29:53 -0700690 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
691 if (pdata == NULL) {
692 SLOGE("Cannot allocate persisent data\n");
693 return;
694 }
695 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
696
697 /* Need to initialize the persistent data area */
698 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
699 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100700 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700701 return;
702 }
703 /* Write all zeros to the first copy, making it invalid */
704 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
705
706 /* Write a valid but empty structure to the second copy */
707 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
708 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
709
710 /* Update the footer */
711 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
712 crypt_ftr->persist_data_offset[0] = pdata_offset;
713 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
714 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100715 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700716 }
717
Paul Lawrencef4faa572014-01-29 13:31:03 -0800718 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700719 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800720 /* But keep the old kdf_type.
721 * It will get updated later to KDF_SCRYPT after the password has been verified.
722 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700723 crypt_ftr->kdf_type = KDF_PBKDF2;
724 get_device_scrypt_params(crypt_ftr);
725 crypt_ftr->minor_version = 2;
726 }
727
Paul Lawrencef4faa572014-01-29 13:31:03 -0800728 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
729 SLOGW("upgrading crypto footer to 1.3");
730 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
731 crypt_ftr->minor_version = 3;
732 }
733
Kenny Root7434b312013-06-14 11:29:53 -0700734 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
735 if (lseek64(fd, offset, SEEK_SET) == -1) {
736 SLOGE("Cannot seek to crypt footer\n");
737 return;
738 }
739 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700740 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700741}
742
743
744static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800745{
746 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800747 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700748 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800749 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700750 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700751 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800752
Ken Sumrall160b4d62013-04-22 12:15:39 -0700753 if (get_crypt_ftr_info(&fname, &starting_off)) {
754 SLOGE("Unable to get crypt_ftr_info\n");
755 return -1;
756 }
757 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700758 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700759 return -1;
760 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700761 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700762 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700763 return -1;
764 }
765
766 /* Make sure it's 16 Kbytes in length */
767 fstat(fd, &statbuf);
768 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
769 SLOGE("footer file %s is not the expected size!\n", fname);
770 goto errout;
771 }
772
773 /* Seek to the start of the crypt footer */
774 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
775 SLOGE("Cannot seek to real block device footer\n");
776 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800777 }
778
779 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
780 SLOGE("Cannot read real block device footer\n");
781 goto errout;
782 }
783
784 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700785 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800786 goto errout;
787 }
788
Kenny Rootc96a5f82013-06-14 12:08:28 -0700789 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
790 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
791 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800792 goto errout;
793 }
794
Kenny Rootc96a5f82013-06-14 12:08:28 -0700795 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
796 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
797 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800798 }
799
Ken Sumrall160b4d62013-04-22 12:15:39 -0700800 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
801 * copy on disk before returning.
802 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700803 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700804 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800805 }
806
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800807 /* Success! */
808 rc = 0;
809
810errout:
811 close(fd);
812 return rc;
813}
814
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
816{
817 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
818 crypt_ftr->persist_data_offset[1]) {
819 SLOGE("Crypt_ftr persist data regions overlap");
820 return -1;
821 }
822
823 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
824 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
825 return -1;
826 }
827
828 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
829 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
830 CRYPT_FOOTER_OFFSET) {
831 SLOGE("Persistent data extends past crypto footer");
832 return -1;
833 }
834
835 return 0;
836}
837
838static int load_persistent_data(void)
839{
840 struct crypt_mnt_ftr crypt_ftr;
841 struct crypt_persist_data *pdata = NULL;
842 char encrypted_state[PROPERTY_VALUE_MAX];
843 char *fname;
844 int found = 0;
845 int fd;
846 int ret;
847 int i;
848
849 if (persist_data) {
850 /* Nothing to do, we've already loaded or initialized it */
851 return 0;
852 }
853
854
855 /* If not encrypted, just allocate an empty table and initialize it */
856 property_get("ro.crypto.state", encrypted_state, "");
857 if (strcmp(encrypted_state, "encrypted") ) {
858 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
859 if (pdata) {
860 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
861 persist_data = pdata;
862 return 0;
863 }
864 return -1;
865 }
866
867 if(get_crypt_ftr_and_key(&crypt_ftr)) {
868 return -1;
869 }
870
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700871 if ((crypt_ftr.major_version < 1)
872 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700873 SLOGE("Crypt_ftr version doesn't support persistent data");
874 return -1;
875 }
876
877 if (get_crypt_ftr_info(&fname, NULL)) {
878 return -1;
879 }
880
881 ret = validate_persistent_data_storage(&crypt_ftr);
882 if (ret) {
883 return -1;
884 }
885
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700886 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700887 if (fd < 0) {
888 SLOGE("Cannot open %s metadata file", fname);
889 return -1;
890 }
891
892 if (persist_data == NULL) {
893 pdata = malloc(crypt_ftr.persist_data_size);
894 if (pdata == NULL) {
895 SLOGE("Cannot allocate memory for persistent data");
896 goto err;
897 }
898 }
899
900 for (i = 0; i < 2; i++) {
901 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
902 SLOGE("Cannot seek to read persistent data on %s", fname);
903 goto err2;
904 }
905 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
906 SLOGE("Error reading persistent data on iteration %d", i);
907 goto err2;
908 }
909 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
910 found = 1;
911 break;
912 }
913 }
914
915 if (!found) {
916 SLOGI("Could not find valid persistent data, creating");
917 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
918 }
919
920 /* Success */
921 persist_data = pdata;
922 close(fd);
923 return 0;
924
925err2:
926 free(pdata);
927
928err:
929 close(fd);
930 return -1;
931}
932
933static int save_persistent_data(void)
934{
935 struct crypt_mnt_ftr crypt_ftr;
936 struct crypt_persist_data *pdata;
937 char *fname;
938 off64_t write_offset;
939 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700940 int fd;
941 int ret;
942
943 if (persist_data == NULL) {
944 SLOGE("No persistent data to save");
945 return -1;
946 }
947
948 if(get_crypt_ftr_and_key(&crypt_ftr)) {
949 return -1;
950 }
951
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700952 if ((crypt_ftr.major_version < 1)
953 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700954 SLOGE("Crypt_ftr version doesn't support persistent data");
955 return -1;
956 }
957
958 ret = validate_persistent_data_storage(&crypt_ftr);
959 if (ret) {
960 return -1;
961 }
962
963 if (get_crypt_ftr_info(&fname, NULL)) {
964 return -1;
965 }
966
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700967 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700968 if (fd < 0) {
969 SLOGE("Cannot open %s metadata file", fname);
970 return -1;
971 }
972
973 pdata = malloc(crypt_ftr.persist_data_size);
974 if (pdata == NULL) {
975 SLOGE("Cannot allocate persistant data");
976 goto err;
977 }
978
979 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
980 SLOGE("Cannot seek to read persistent data on %s", fname);
981 goto err2;
982 }
983
984 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
985 SLOGE("Error reading persistent data before save");
986 goto err2;
987 }
988
989 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
990 /* The first copy is the curent valid copy, so write to
991 * the second copy and erase this one */
992 write_offset = crypt_ftr.persist_data_offset[1];
993 erase_offset = crypt_ftr.persist_data_offset[0];
994 } else {
995 /* The second copy must be the valid copy, so write to
996 * the first copy, and erase the second */
997 write_offset = crypt_ftr.persist_data_offset[0];
998 erase_offset = crypt_ftr.persist_data_offset[1];
999 }
1000
1001 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001002 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001003 SLOGE("Cannot seek to write persistent data");
1004 goto err2;
1005 }
1006 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1007 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001008 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001009 SLOGE("Cannot seek to erase previous persistent data");
1010 goto err2;
1011 }
1012 fsync(fd);
1013 memset(pdata, 0, crypt_ftr.persist_data_size);
1014 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
1015 (int) crypt_ftr.persist_data_size) {
1016 SLOGE("Cannot write to erase previous persistent data");
1017 goto err2;
1018 }
1019 fsync(fd);
1020 } else {
1021 SLOGE("Cannot write to save persistent data");
1022 goto err2;
1023 }
1024
1025 /* Success */
1026 free(pdata);
1027 close(fd);
1028 return 0;
1029
1030err2:
1031 free(pdata);
1032err:
1033 close(fd);
1034 return -1;
1035}
1036
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001037/* Convert a binary key of specified length into an ascii hex string equivalent,
1038 * without the leading 0x and with null termination
1039 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001040static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001041 unsigned int keysize, char *master_key_ascii) {
1042 unsigned int i, a;
1043 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001044
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001045 for (i=0, a=0; i<keysize; i++, a+=2) {
1046 /* For each byte, write out two ascii hex digits */
1047 nibble = (master_key[i] >> 4) & 0xf;
1048 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001049
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001050 nibble = master_key[i] & 0xf;
1051 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1052 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001053
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001054 /* Add the null termination */
1055 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001056
1057}
1058
Jeff Sharkey9c484982015-03-31 10:35:33 -07001059static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
1060 const unsigned char *master_key, const char *real_blk_name,
1061 const char *name, int fd, const char *extra_params) {
Dan Albertc07fa3f2014-12-18 10:00:55 -08001062 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001063 struct dm_ioctl *io;
1064 struct dm_target_spec *tgt;
1065 char *crypt_params;
1066 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1067 int i;
1068
1069 io = (struct dm_ioctl *) buffer;
1070
1071 /* Load the mapping table for this device */
1072 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1073
1074 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1075 io->target_count = 1;
1076 tgt->status = 0;
1077 tgt->sector_start = 0;
1078 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -07001079#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001080 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1081 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1082 }
1083 else {
1084 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1085 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001086#else
1087 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1088#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001089
1090 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1091 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1092 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1093 master_key_ascii, real_blk_name, extra_params);
1094 crypt_params += strlen(crypt_params) + 1;
1095 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1096 tgt->next = crypt_params - buffer;
1097
1098 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1099 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1100 break;
1101 }
1102 usleep(500000);
1103 }
1104
1105 if (i == TABLE_LOAD_RETRIES) {
1106 /* We failed to load the table, return an error */
1107 return -1;
1108 } else {
1109 return i + 1;
1110 }
1111}
1112
1113
1114static int get_dm_crypt_version(int fd, const char *name, int *version)
1115{
1116 char buffer[DM_CRYPT_BUF_SIZE];
1117 struct dm_ioctl *io;
1118 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001119
1120 io = (struct dm_ioctl *) buffer;
1121
1122 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1123
1124 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1125 return -1;
1126 }
1127
1128 /* Iterate over the returned versions, looking for name of "crypt".
1129 * When found, get and return the version.
1130 */
1131 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1132 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001133#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001134 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001135#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001136 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001137#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001138 /* We found the crypt driver, return the version, and get out */
1139 version[0] = v->version[0];
1140 version[1] = v->version[1];
1141 version[2] = v->version[2];
1142 return 0;
1143 }
1144 v = (struct dm_target_versions *)(((char *)v) + v->next);
1145 }
1146
1147 return -1;
1148}
1149
Jeff Sharkey9c484982015-03-31 10:35:33 -07001150static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
1151 const unsigned char *master_key, const char *real_blk_name,
1152 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001153 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001154 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001155 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001156 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -08001157 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001158 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001159 int version[3];
1160 char *extra_params;
1161 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001162
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001163 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001164 SLOGE("Cannot open device-mapper\n");
1165 goto errout;
1166 }
1167
1168 io = (struct dm_ioctl *) buffer;
1169
1170 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -08001171 err = ioctl(fd, DM_DEV_CREATE, io);
1172 if (err) {
1173 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001174 goto errout;
1175 }
1176
1177 /* Get the device status, in particular, the name of it's device file */
1178 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1179 if (ioctl(fd, DM_DEV_STATUS, io)) {
1180 SLOGE("Cannot retrieve dm-crypt device status\n");
1181 goto errout;
1182 }
1183 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1184 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1185
Ken Sumralldb5e0262013-02-05 17:39:48 -08001186 extra_params = "";
1187 if (! get_dm_crypt_version(fd, name, version)) {
1188 /* Support for allow_discards was added in version 1.11.0 */
1189 if ((version[0] >= 2) ||
1190 ((version[0] == 1) && (version[1] >= 11))) {
1191 extra_params = "1 allow_discards";
1192 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1193 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001194 }
1195
Ken Sumralldb5e0262013-02-05 17:39:48 -08001196 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1197 fd, extra_params);
1198 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001199 SLOGE("Cannot load dm-crypt mapping table.\n");
1200 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001201 } else if (load_count > 1) {
1202 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001203 }
1204
1205 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001206 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207
1208 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1209 SLOGE("Cannot resume the dm-crypt device\n");
1210 goto errout;
1211 }
1212
1213 /* We made it here with no errors. Woot! */
1214 retval = 0;
1215
1216errout:
1217 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1218
1219 return retval;
1220}
1221
Ken Sumrall29d8da82011-05-18 17:20:07 -07001222static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223{
1224 int fd;
1225 char buffer[DM_CRYPT_BUF_SIZE];
1226 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001227 int retval = -1;
1228
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001229 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230 SLOGE("Cannot open device-mapper\n");
1231 goto errout;
1232 }
1233
1234 io = (struct dm_ioctl *) buffer;
1235
1236 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1237 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1238 SLOGE("Cannot remove dm-crypt device\n");
1239 goto errout;
1240 }
1241
1242 /* We made it here with no errors. Woot! */
1243 retval = 0;
1244
1245errout:
1246 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1247
1248 return retval;
1249
1250}
1251
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001252static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001253 unsigned char *ikey, void *params UNUSED)
1254{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001255 SLOGI("Using pbkdf2 for cryptfs KDF");
1256
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001257 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001258 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1259 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1260 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001261}
1262
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001263static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001264 unsigned char *ikey, void *params)
1265{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001266 SLOGI("Using scrypt for cryptfs KDF");
1267
Kenny Rootc4c70f12013-06-14 12:11:38 -07001268 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1269
1270 int N = 1 << ftr->N_factor;
1271 int r = 1 << ftr->r_factor;
1272 int p = 1 << ftr->p_factor;
1273
1274 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001275 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001276 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1277 salt, SALT_LEN, N, r, p, ikey,
1278 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001279
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001280 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001281}
1282
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001283static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1284 unsigned char *ikey, void *params)
1285{
1286 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1287
1288 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001289 size_t signature_size;
1290 unsigned char* signature;
1291 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1292
1293 int N = 1 << ftr->N_factor;
1294 int r = 1 << ftr->r_factor;
1295 int p = 1 << ftr->p_factor;
1296
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001297 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1298 salt, SALT_LEN, N, r, p, ikey,
1299 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001300
1301 if (rc) {
1302 SLOGE("scrypt failed");
1303 return -1;
1304 }
1305
Shawn Willdene17a9c42014-09-08 13:04:08 -06001306 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1307 &signature, &signature_size)) {
1308 SLOGE("Signing failed");
1309 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001310 }
1311
1312 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1313 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1314 free(signature);
1315
1316 if (rc) {
1317 SLOGE("scrypt failed");
1318 return -1;
1319 }
1320
1321 return 0;
1322}
1323
1324static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1325 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001326 unsigned char *encrypted_master_key,
1327 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001328{
1329 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1330 EVP_CIPHER_CTX e_ctx;
1331 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001332 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001333
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001334 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001335 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001336
1337 switch (crypt_ftr->kdf_type) {
1338 case KDF_SCRYPT_KEYMASTER:
1339 if (keymaster_create_key(crypt_ftr)) {
1340 SLOGE("keymaster_create_key failed");
1341 return -1;
1342 }
1343
1344 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1345 SLOGE("scrypt failed");
1346 return -1;
1347 }
1348 break;
1349
1350 case KDF_SCRYPT:
1351 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1352 SLOGE("scrypt failed");
1353 return -1;
1354 }
1355 break;
1356
1357 default:
1358 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001359 return -1;
1360 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001361
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001362 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001363 EVP_CIPHER_CTX_init(&e_ctx);
1364 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001365 SLOGE("EVP_EncryptInit failed\n");
1366 return -1;
1367 }
1368 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001369
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001370 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001371 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001372 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373 SLOGE("EVP_EncryptUpdate failed\n");
1374 return -1;
1375 }
Adam Langley889c4f12014-09-03 14:23:13 -07001376 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001377 SLOGE("EVP_EncryptFinal failed\n");
1378 return -1;
1379 }
1380
1381 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1382 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1383 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001384 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001385
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001386 /* Store the scrypt of the intermediate key, so we can validate if it's a
1387 password error or mount error when things go wrong.
1388 Note there's no need to check for errors, since if this is incorrect, we
1389 simply won't wipe userdata, which is the correct default behavior
1390 */
1391 int N = 1 << crypt_ftr->N_factor;
1392 int r = 1 << crypt_ftr->r_factor;
1393 int p = 1 << crypt_ftr->p_factor;
1394
1395 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1396 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1397 crypt_ftr->scrypted_intermediate_key,
1398 sizeof(crypt_ftr->scrypted_intermediate_key));
1399
1400 if (rc) {
1401 SLOGE("encrypt_master_key: crypto_scrypt failed");
1402 }
1403
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001404 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001405}
1406
Paul Lawrence731a7a22015-04-28 22:14:15 +00001407static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001408 unsigned char *encrypted_master_key,
1409 unsigned char *decrypted_master_key,
1410 kdf_func kdf, void *kdf_params,
1411 unsigned char** intermediate_key,
1412 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413{
1414 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 -08001415 EVP_CIPHER_CTX d_ctx;
1416 int decrypted_len, final_len;
1417
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001418 /* Turn the password into an intermediate key and IV that can decrypt the
1419 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001420 if (kdf(passwd, salt, ikey, kdf_params)) {
1421 SLOGE("kdf failed");
1422 return -1;
1423 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001424
1425 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001426 EVP_CIPHER_CTX_init(&d_ctx);
1427 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428 return -1;
1429 }
1430 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1431 /* Decrypt the master key */
1432 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1433 encrypted_master_key, KEY_LEN_BYTES)) {
1434 return -1;
1435 }
Adam Langley889c4f12014-09-03 14:23:13 -07001436 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001437 return -1;
1438 }
1439
1440 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1441 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001442 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001443
1444 /* Copy intermediate key if needed by params */
1445 if (intermediate_key && intermediate_key_size) {
1446 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1447 if (intermediate_key) {
1448 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1449 *intermediate_key_size = KEY_LEN_BYTES;
1450 }
1451 }
1452
1453 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001454}
1455
Kenny Rootc4c70f12013-06-14 12:11:38 -07001456static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001457{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001458 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001459 *kdf = scrypt_keymaster;
1460 *kdf_params = ftr;
1461 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001462 *kdf = scrypt;
1463 *kdf_params = ftr;
1464 } else {
1465 *kdf = pbkdf2;
1466 *kdf_params = NULL;
1467 }
1468}
1469
Paul Lawrence731a7a22015-04-28 22:14:15 +00001470static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001471 struct crypt_mnt_ftr *crypt_ftr,
1472 unsigned char** intermediate_key,
1473 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001474{
1475 kdf_func kdf;
1476 void *kdf_params;
1477 int ret;
1478
1479 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001480 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1481 decrypted_master_key, kdf, kdf_params,
1482 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001483 if (ret != 0) {
1484 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001485 }
1486
1487 return ret;
1488}
1489
1490static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1491 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001492 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001493 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001494
1495 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001496 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001497 read(fd, key_buf, sizeof(key_buf));
1498 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001499 close(fd);
1500
1501 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001502 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001503}
1504
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001505int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001506{
Greg Hackmann955653e2014-09-24 14:55:20 -07001507 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001508#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001509
1510 /* Now umount the tmpfs filesystem */
1511 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001512 if (umount(mountpoint) == 0) {
1513 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001514 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001515
1516 if (errno == EINVAL) {
1517 /* EINVAL is returned if the directory is not a mountpoint,
1518 * i.e. there is no filesystem mounted there. So just get out.
1519 */
1520 break;
1521 }
1522
1523 err = errno;
1524
1525 /* If allowed, be increasingly aggressive before the last two retries */
1526 if (kill) {
1527 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1528 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001529 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001530 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1531 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001532 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001533 }
1534 }
1535
1536 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001537 }
1538
1539 if (i < WAIT_UNMOUNT_COUNT) {
1540 SLOGD("unmounting %s succeeded\n", mountpoint);
1541 rc = 0;
1542 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001543 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001544 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001545 rc = -1;
1546 }
1547
1548 return rc;
1549}
1550
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001551#define DATA_PREP_TIMEOUT 1000
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001552static int prep_data_fs(void)
1553{
1554 int i;
1555
Jeff Sharkey47695b22016-02-01 17:02:29 -07001556 // NOTE: post_fs_data results in init calling back around to vold, so all
1557 // callers to this method must be async
1558
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001559 /* Do the prep of the /data filesystem */
1560 property_set("vold.post_fs_data_done", "0");
1561 property_set("vold.decrypt", "trigger_post_fs_data");
1562 SLOGD("Just triggered post_fs_data\n");
1563
Ken Sumrallc5872692013-05-14 15:26:31 -07001564 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001565 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001566 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001567
1568 property_get("vold.post_fs_data_done", p, "0");
1569 if (*p == '1') {
1570 break;
1571 } else {
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001572 usleep(50000);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001573 }
1574 }
1575 if (i == DATA_PREP_TIMEOUT) {
1576 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001577 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001578 return -1;
1579 } else {
1580 SLOGD("post_fs_data done\n");
1581 return 0;
1582 }
1583}
1584
Paul Lawrence74f29f12014-08-28 15:54:10 -07001585static void cryptfs_set_corrupt()
1586{
1587 // Mark the footer as bad
1588 struct crypt_mnt_ftr crypt_ftr;
1589 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1590 SLOGE("Failed to get crypto footer - panic");
1591 return;
1592 }
1593
1594 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1595 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1596 SLOGE("Failed to set crypto footer - panic");
1597 return;
1598 }
1599}
1600
1601static void cryptfs_trigger_restart_min_framework()
1602{
1603 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1604 SLOGE("Failed to mount tmpfs on data - panic");
1605 return;
1606 }
1607
1608 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1609 SLOGE("Failed to trigger post fs data - panic");
1610 return;
1611 }
1612
1613 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1614 SLOGE("Failed to trigger restart min framework - panic");
1615 return;
1616 }
1617}
1618
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001619/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001620static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001621{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001622 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001623 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001624 static int restart_successful = 0;
1625
1626 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001627 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001628 SLOGE("Encrypted filesystem not validated, aborting");
1629 return -1;
1630 }
1631
1632 if (restart_successful) {
1633 SLOGE("System already restarted with encrypted disk, aborting");
1634 return -1;
1635 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001636
Paul Lawrencef4faa572014-01-29 13:31:03 -08001637 if (restart_main) {
1638 /* Here is where we shut down the framework. The init scripts
1639 * start all services in one of three classes: core, main or late_start.
1640 * On boot, we start core and main. Now, we stop main, but not core,
1641 * as core includes vold and a few other really important things that
1642 * we need to keep running. Once main has stopped, we should be able
1643 * to umount the tmpfs /data, then mount the encrypted /data.
1644 * We then restart the class main, and also the class late_start.
1645 * At the moment, I've only put a few things in late_start that I know
1646 * are not needed to bring up the framework, and that also cause problems
1647 * with unmounting the tmpfs /data, but I hope to add add more services
1648 * to the late_start class as we optimize this to decrease the delay
1649 * till the user is asked for the password to the filesystem.
1650 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001651
Paul Lawrencef4faa572014-01-29 13:31:03 -08001652 /* The init files are setup to stop the class main when vold.decrypt is
1653 * set to trigger_reset_main.
1654 */
1655 property_set("vold.decrypt", "trigger_reset_main");
1656 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001657
Paul Lawrencef4faa572014-01-29 13:31:03 -08001658 /* Ugh, shutting down the framework is not synchronous, so until it
1659 * can be fixed, this horrible hack will wait a moment for it all to
1660 * shut down before proceeding. Without it, some devices cannot
1661 * restart the graphics services.
1662 */
1663 sleep(2);
1664 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001665
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001666 /* Now that the framework is shutdown, we should be able to umount()
1667 * the tmpfs filesystem, and mount the real one.
1668 */
1669
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001670 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1671 if (strlen(crypto_blkdev) == 0) {
1672 SLOGE("fs_crypto_blkdev not set\n");
1673 return -1;
1674 }
1675
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001676 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001677 /* If ro.crypto.readonly is set to 1, mount the decrypted
1678 * filesystem readonly. This is used when /data is mounted by
1679 * recovery mode.
1680 */
1681 char ro_prop[PROPERTY_VALUE_MAX];
1682 property_get("ro.crypto.readonly", ro_prop, "");
1683 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1684 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1685 rec->flags |= MS_RDONLY;
1686 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001687
Ken Sumralle5032c42012-04-01 23:58:44 -07001688 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001689 int retries = RETRY_MOUNT_ATTEMPTS;
1690 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001691
1692 /*
1693 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1694 * partitions in the fsck domain.
1695 */
1696 if (setexeccon(secontextFsck())){
1697 SLOGE("Failed to setexeccon");
1698 return -1;
1699 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001700 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1701 crypto_blkdev, 0))
1702 != 0) {
1703 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1704 /* TODO: invoke something similar to
1705 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1706 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1707 SLOGI("Failed to mount %s because it is busy - waiting",
1708 crypto_blkdev);
1709 if (--retries) {
1710 sleep(RETRY_MOUNT_DELAY_SECONDS);
1711 } else {
1712 /* Let's hope that a reboot clears away whatever is keeping
1713 the mount busy */
1714 cryptfs_reboot(reboot);
1715 }
1716 } else {
1717 SLOGE("Failed to mount decrypted data");
1718 cryptfs_set_corrupt();
1719 cryptfs_trigger_restart_min_framework();
1720 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001721 if (setexeccon(NULL)) {
1722 SLOGE("Failed to setexeccon");
1723 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001724 return -1;
1725 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001726 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001727 if (setexeccon(NULL)) {
1728 SLOGE("Failed to setexeccon");
1729 return -1;
1730 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001731
Ken Sumralle5032c42012-04-01 23:58:44 -07001732 property_set("vold.decrypt", "trigger_load_persist_props");
1733 /* Create necessary paths on /data */
1734 if (prep_data_fs()) {
1735 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001736 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001737
1738 /* startup service classes main and late_start */
1739 property_set("vold.decrypt", "trigger_restart_framework");
1740 SLOGD("Just triggered restart_framework\n");
1741
1742 /* Give it a few moments to get started */
1743 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001744 }
1745
Ken Sumrall0cc16632011-01-18 20:32:26 -08001746 if (rc == 0) {
1747 restart_successful = 1;
1748 }
1749
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001750 return rc;
1751}
1752
Paul Lawrencef4faa572014-01-29 13:31:03 -08001753int cryptfs_restart(void)
1754{
Paul Lawrence05335c32015-03-05 09:46:23 -08001755 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001756 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001757 SLOGE("cryptfs_restart not valid for file encryption:");
1758 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001759 }
1760
Paul Lawrencef4faa572014-01-29 13:31:03 -08001761 /* Call internal implementation forcing a restart of main service group */
1762 return cryptfs_restart_internal(1);
1763}
1764
Paul Lawrence05335c32015-03-05 09:46:23 -08001765static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001766{
1767 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001768 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001769 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001770
1771 property_get("ro.crypto.state", encrypted_state, "");
1772 if (strcmp(encrypted_state, "encrypted") ) {
1773 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001774 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001775 }
1776
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001777 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001778 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001779 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001780 }
1781
Ken Sumrall160b4d62013-04-22 12:15:39 -07001782 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001783 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001784
Ken Sumralle1a45852011-12-14 21:24:27 -08001785 /*
1786 * Only report this error if key_loc is a file and it exists.
1787 * If the device was never encrypted, and /data is not mountable for
1788 * some reason, returning 1 should prevent the UI from presenting the
1789 * a "enter password" screen, or worse, a "press button to wipe the
1790 * device" screen.
1791 */
1792 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1793 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001794 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001795 } else {
1796 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001797 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001798 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001799 }
1800
Paul Lawrence74f29f12014-08-28 15:54:10 -07001801 // Test for possible error flags
1802 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1803 SLOGE("Encryption process is partway completed\n");
1804 return CRYPTO_COMPLETE_PARTIAL;
1805 }
1806
1807 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1808 SLOGE("Encryption process was interrupted but cannot continue\n");
1809 return CRYPTO_COMPLETE_INCONSISTENT;
1810 }
1811
1812 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1813 SLOGE("Encryption is successful but data is corrupt\n");
1814 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001815 }
1816
1817 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001818 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001819}
1820
Paul Lawrencef4faa572014-01-29 13:31:03 -08001821static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1822 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001823{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001824 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001825 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001826 char crypto_blkdev[MAXPATHLEN];
1827 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001828 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001829 unsigned int orig_failed_decrypt_count;
1830 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001831 int use_keymaster = 0;
1832 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001833 unsigned char* intermediate_key = 0;
1834 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001835
Paul Lawrencef4faa572014-01-29 13:31:03 -08001836 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1837 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001838
Paul Lawrencef4faa572014-01-29 13:31:03 -08001839 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001840 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1841 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001842 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001843 rc = -1;
1844 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001845 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001846 }
1847
Paul Lawrencef4faa572014-01-29 13:31:03 -08001848 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1849
Ajay Dudani87701e22014-09-17 21:02:52 -07001850#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001851 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1852 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1853 SLOGE("Hardware encryption key does not match");
1854 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001855 }
1856#endif
1857
Paul Lawrence74f29f12014-08-28 15:54:10 -07001858 // Create crypto block device - all (non fatal) code paths
1859 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001860 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1861 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001862 SLOGE("Error creating decrypted block device\n");
1863 rc = -1;
1864 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001865 }
1866
Paul Lawrence74f29f12014-08-28 15:54:10 -07001867 /* Work out if the problem is the password or the data */
1868 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1869 scrypted_intermediate_key)];
1870 int N = 1 << crypt_ftr->N_factor;
1871 int r = 1 << crypt_ftr->r_factor;
1872 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001873
Paul Lawrence74f29f12014-08-28 15:54:10 -07001874 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1875 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1876 N, r, p, scrypted_intermediate_key,
1877 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001878
Paul Lawrence74f29f12014-08-28 15:54:10 -07001879 // Does the key match the crypto footer?
1880 if (rc == 0 && memcmp(scrypted_intermediate_key,
1881 crypt_ftr->scrypted_intermediate_key,
1882 sizeof(scrypted_intermediate_key)) == 0) {
1883 SLOGI("Password matches");
1884 rc = 0;
1885 } else {
1886 /* Try mounting the file system anyway, just in case the problem's with
1887 * the footer, not the key. */
1888 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1889 mkdir(tmp_mount_point, 0755);
1890 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1891 SLOGE("Error temp mounting decrypted block device\n");
1892 delete_crypto_blk_dev(label);
1893
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001894 rc = ++crypt_ftr->failed_decrypt_count;
1895 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001896 } else {
1897 /* Success! */
1898 SLOGI("Password did not match but decrypted drive mounted - continue");
1899 umount(tmp_mount_point);
1900 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001901 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001902 }
1903
1904 if (rc == 0) {
1905 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001906 if (orig_failed_decrypt_count != 0) {
1907 put_crypt_ftr_and_key(crypt_ftr);
1908 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001909
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001910 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001911 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001912 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001913
1914 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001915 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001916 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001917 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001918 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001919 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001920 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001921
Paul Lawrence74f29f12014-08-28 15:54:10 -07001922 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001923 use_keymaster = keymaster_check_compatibility();
1924 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001925 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001926 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1927 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1928 upgrade = 1;
1929 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001930 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001931 upgrade = 1;
1932 }
1933
1934 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001935 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1936 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001937 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001938 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001939 }
1940 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001941
1942 // Do not fail even if upgrade failed - machine is bootable
1943 // Note that if this code is ever hit, there is a *serious* problem
1944 // since KDFs should never fail. You *must* fix the kdf before
1945 // proceeding!
1946 if (rc) {
1947 SLOGW("Upgrade failed with error %d,"
1948 " but continuing with previous state",
1949 rc);
1950 rc = 0;
1951 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001952 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001953 }
1954
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001955 errout:
1956 if (intermediate_key) {
1957 memset(intermediate_key, 0, intermediate_key_size);
1958 free(intermediate_key);
1959 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001960 return rc;
1961}
1962
Ken Sumrall29d8da82011-05-18 17:20:07 -07001963/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001964 * Called by vold when it's asked to mount an encrypted external
1965 * storage volume. The incoming partition has no crypto header/footer,
1966 * as any metadata is been stored in a separate, small partition.
1967 *
1968 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001969 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001970int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1971 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001972 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001973 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001974 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001975 return -1;
1976 }
1977
1978 unsigned long nr_sec = 0;
1979 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001980 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001981
Ken Sumrall29d8da82011-05-18 17:20:07 -07001982 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001983 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001984 return -1;
1985 }
1986
Jeff Sharkey9c484982015-03-31 10:35:33 -07001987 struct crypt_mnt_ftr ext_crypt_ftr;
1988 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1989 ext_crypt_ftr.fs_size = nr_sec;
1990 ext_crypt_ftr.keysize = keysize;
1991 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001992
Jeff Sharkey9c484982015-03-31 10:35:33 -07001993 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1994 out_crypto_blkdev, label);
1995}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001996
Jeff Sharkey9c484982015-03-31 10:35:33 -07001997/*
1998 * Called by vold when it's asked to unmount an encrypted external
1999 * storage volume.
2000 */
2001int cryptfs_revert_ext_volume(const char* label) {
2002 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002003}
2004
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002005int cryptfs_crypto_complete(void)
2006{
2007 return do_crypto_complete("/data");
2008}
2009
Paul Lawrencef4faa572014-01-29 13:31:03 -08002010int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2011{
2012 char encrypted_state[PROPERTY_VALUE_MAX];
2013 property_get("ro.crypto.state", encrypted_state, "");
2014 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2015 SLOGE("encrypted fs already validated or not running with encryption,"
2016 " aborting");
2017 return -1;
2018 }
2019
2020 if (get_crypt_ftr_and_key(crypt_ftr)) {
2021 SLOGE("Error getting crypt footer and key");
2022 return -1;
2023 }
2024
2025 return 0;
2026}
2027
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002028int cryptfs_check_passwd(char *passwd)
2029{
Paul Lawrence05335c32015-03-05 09:46:23 -08002030 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00002031 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002032 SLOGE("cryptfs_check_passwd not valid for file encryption");
2033 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002034 }
2035
Paul Lawrencef4faa572014-01-29 13:31:03 -08002036 struct crypt_mnt_ftr crypt_ftr;
2037 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002038
Paul Lawrencef4faa572014-01-29 13:31:03 -08002039 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002040 if (rc) {
2041 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002042 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002043 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002044
Paul Lawrence3bd36d52015-06-09 13:37:44 -07002045 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002046 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2047 if (rc) {
2048 SLOGE("Password did not match");
2049 return rc;
2050 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002051
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002052 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2053 // Here we have a default actual password but a real password
2054 // we must test against the scrypted value
2055 // First, we must delete the crypto block device that
2056 // test_mount_encrypted_fs leaves behind as a side effect
2057 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2058 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2059 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2060 if (rc) {
2061 SLOGE("Default password did not match on reboot encryption");
2062 return rc;
2063 }
2064
2065 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2066 put_crypt_ftr_and_key(&crypt_ftr);
2067 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2068 if (rc) {
2069 SLOGE("Could not change password on reboot encryption");
2070 return rc;
2071 }
2072 }
2073
2074 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002075 cryptfs_clear_password();
2076 password = strdup(passwd);
2077 struct timespec now;
2078 clock_gettime(CLOCK_BOOTTIME, &now);
2079 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002080 }
2081
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002082 return rc;
2083}
2084
Ken Sumrall3ad90722011-10-04 20:38:29 -07002085int cryptfs_verify_passwd(char *passwd)
2086{
2087 struct crypt_mnt_ftr crypt_ftr;
2088 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002089 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002090 char encrypted_state[PROPERTY_VALUE_MAX];
2091 int rc;
2092
2093 property_get("ro.crypto.state", encrypted_state, "");
2094 if (strcmp(encrypted_state, "encrypted") ) {
2095 SLOGE("device not encrypted, aborting");
2096 return -2;
2097 }
2098
2099 if (!master_key_saved) {
2100 SLOGE("encrypted fs not yet mounted, aborting");
2101 return -1;
2102 }
2103
2104 if (!saved_mount_point) {
2105 SLOGE("encrypted fs failed to save mount point, aborting");
2106 return -1;
2107 }
2108
Ken Sumrall160b4d62013-04-22 12:15:39 -07002109 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002110 SLOGE("Error getting crypt footer and key\n");
2111 return -1;
2112 }
2113
2114 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2115 /* If the device has no password, then just say the password is valid */
2116 rc = 0;
2117 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002118 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002119 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2120 /* They match, the password is correct */
2121 rc = 0;
2122 } else {
2123 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2124 sleep(1);
2125 rc = 1;
2126 }
2127 }
2128
2129 return rc;
2130}
2131
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002132/* Initialize a crypt_mnt_ftr structure. The keysize is
2133 * defaulted to 16 bytes, and the filesystem size to 0.
2134 * Presumably, at a minimum, the caller will update the
2135 * filesystem size and crypto_type_name after calling this function.
2136 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002137static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002138{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002139 off64_t off;
2140
2141 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002142 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002143 ftr->major_version = CURRENT_MAJOR_VERSION;
2144 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002145 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002146 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002147
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002148 switch (keymaster_check_compatibility()) {
2149 case 1:
2150 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2151 break;
2152
2153 case 0:
2154 ftr->kdf_type = KDF_SCRYPT;
2155 break;
2156
2157 default:
2158 SLOGE("keymaster_check_compatibility failed");
2159 return -1;
2160 }
2161
Kenny Rootc4c70f12013-06-14 12:11:38 -07002162 get_device_scrypt_params(ftr);
2163
Ken Sumrall160b4d62013-04-22 12:15:39 -07002164 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2165 if (get_crypt_ftr_info(NULL, &off) == 0) {
2166 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2167 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2168 ftr->persist_data_size;
2169 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002170
2171 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002172}
2173
Ken Sumrall29d8da82011-05-18 17:20:07 -07002174static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002175{
Ken Sumralle550f782013-08-20 13:48:23 -07002176 const char *args[10];
2177 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2178 int num_args;
2179 int status;
2180 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002181 int rc = -1;
2182
Ken Sumrall29d8da82011-05-18 17:20:07 -07002183 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002184 args[0] = "/system/bin/make_ext4fs";
2185 args[1] = "-a";
2186 args[2] = "/data";
2187 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002188 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002189 args[4] = size_str;
2190 args[5] = crypto_blkdev;
2191 num_args = 6;
2192 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2193 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002194 } else if (type == F2FS_FS) {
2195 args[0] = "/system/bin/mkfs.f2fs";
2196 args[1] = "-t";
2197 args[2] = "-d1";
2198 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002199 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002200 args[4] = size_str;
2201 num_args = 5;
2202 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2203 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002204 } else {
2205 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2206 return -1;
2207 }
2208
Ken Sumralle550f782013-08-20 13:48:23 -07002209 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2210
2211 if (tmp != 0) {
2212 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002213 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002214 if (WIFEXITED(status)) {
2215 if (WEXITSTATUS(status)) {
2216 SLOGE("Error creating filesystem on %s, exit status %d ",
2217 crypto_blkdev, WEXITSTATUS(status));
2218 } else {
2219 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2220 rc = 0;
2221 }
2222 } else {
2223 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2224 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002225 }
2226
2227 return rc;
2228}
2229
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002230#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002231#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2232#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002233
2234/* aligned 32K writes tends to make flash happy.
2235 * SD card association recommends it.
2236 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002237#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002238#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002239#else
2240#define BLOCKS_AT_A_TIME 1024
2241#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002242
2243struct encryptGroupsData
2244{
2245 int realfd;
2246 int cryptofd;
2247 off64_t numblocks;
2248 off64_t one_pct, cur_pct, new_pct;
2249 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002250 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002251 char* real_blkdev, * crypto_blkdev;
2252 int count;
2253 off64_t offset;
2254 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002255 off64_t last_written_sector;
2256 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002257 time_t time_started;
2258 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002259};
2260
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002261static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002262{
2263 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002264
2265 if (is_used) {
2266 data->used_blocks_already_done++;
2267 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002268 if (data->tot_used_blocks) {
2269 data->new_pct = data->used_blocks_already_done / data->one_pct;
2270 } else {
2271 data->new_pct = data->blocks_already_done / data->one_pct;
2272 }
2273
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002274 if (data->new_pct > data->cur_pct) {
2275 char buf[8];
2276 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002277 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002278 property_set("vold.encrypt_progress", buf);
2279 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002280
2281 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002282 struct timespec time_now;
2283 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2284 SLOGW("Error getting time");
2285 } else {
2286 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2287 off64_t remaining_blocks = data->tot_used_blocks
2288 - data->used_blocks_already_done;
2289 int remaining_time = (int)(elapsed_time * remaining_blocks
2290 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002291
Paul Lawrence9c58a872014-09-30 09:12:51 -07002292 // Change time only if not yet set, lower, or a lot higher for
2293 // best user experience
2294 if (data->remaining_time == -1
2295 || remaining_time < data->remaining_time
2296 || remaining_time > data->remaining_time + 60) {
2297 char buf[8];
2298 snprintf(buf, sizeof(buf), "%d", remaining_time);
2299 property_set("vold.encrypt_time_remaining", buf);
2300 data->remaining_time = remaining_time;
2301 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002302 }
2303 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002304}
2305
Paul Lawrence3846be12014-09-22 11:33:54 -07002306static void log_progress(struct encryptGroupsData const* data, bool completed)
2307{
2308 // Precondition - if completed data = 0 else data != 0
2309
2310 // Track progress so we can skip logging blocks
2311 static off64_t offset = -1;
2312
2313 // Need to close existing 'Encrypting from' log?
2314 if (completed || (offset != -1 && data->offset != offset)) {
2315 SLOGI("Encrypted to sector %" PRId64,
2316 offset / info.block_size * CRYPT_SECTOR_SIZE);
2317 offset = -1;
2318 }
2319
2320 // Need to start new 'Encrypting from' log?
2321 if (!completed && offset != data->offset) {
2322 SLOGI("Encrypting from sector %" PRId64,
2323 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2324 }
2325
2326 // Update offset
2327 if (!completed) {
2328 offset = data->offset + (off64_t)data->count * info.block_size;
2329 }
2330}
2331
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002332static int flush_outstanding_data(struct encryptGroupsData* data)
2333{
2334 if (data->count == 0) {
2335 return 0;
2336 }
2337
Elliott Hughes231bdba2014-06-25 18:36:19 -07002338 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002339
2340 if (pread64(data->realfd, data->buffer,
2341 info.block_size * data->count, data->offset)
2342 <= 0) {
2343 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2344 data->real_blkdev);
2345 return -1;
2346 }
2347
2348 if (pwrite64(data->cryptofd, data->buffer,
2349 info.block_size * data->count, data->offset)
2350 <= 0) {
2351 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2352 data->crypto_blkdev);
2353 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002354 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002355 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002356 }
2357
2358 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002359 data->last_written_sector = (data->offset + data->count)
2360 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002361 return 0;
2362}
2363
2364static int encrypt_groups(struct encryptGroupsData* data)
2365{
2366 unsigned int i;
2367 u8 *block_bitmap = 0;
2368 unsigned int block;
2369 off64_t ret;
2370 int rc = -1;
2371
2372 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2373 if (!data->buffer) {
2374 SLOGE("Failed to allocate crypto buffer");
2375 goto errout;
2376 }
2377
2378 block_bitmap = malloc(info.block_size);
2379 if (!block_bitmap) {
2380 SLOGE("failed to allocate block bitmap");
2381 goto errout;
2382 }
2383
2384 for (i = 0; i < aux_info.groups; ++i) {
2385 SLOGI("Encrypting group %d", i);
2386
2387 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2388 u32 block_count = min(info.blocks_per_group,
2389 aux_info.len_blocks - first_block);
2390
2391 off64_t offset = (u64)info.block_size
2392 * aux_info.bg_desc[i].bg_block_bitmap;
2393
2394 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2395 if (ret != (int)info.block_size) {
2396 SLOGE("failed to read all of block group bitmap %d", i);
2397 goto errout;
2398 }
2399
2400 offset = (u64)info.block_size * first_block;
2401
2402 data->count = 0;
2403
2404 for (block = 0; block < block_count; block++) {
liminghaoaa08e582016-01-06 10:30:49 +08002405 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
2406 0 : bitmap_get_bit(block_bitmap, block);
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002407 update_progress(data, used);
2408 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002409 if (data->count == 0) {
2410 data->offset = offset;
2411 }
2412 data->count++;
2413 } else {
2414 if (flush_outstanding_data(data)) {
2415 goto errout;
2416 }
2417 }
2418
2419 offset += info.block_size;
2420
2421 /* Write data if we are aligned or buffer size reached */
2422 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2423 || data->count == BLOCKS_AT_A_TIME) {
2424 if (flush_outstanding_data(data)) {
2425 goto errout;
2426 }
2427 }
Paul Lawrence87999172014-02-20 12:21:31 -08002428
Paul Lawrence73d7a022014-06-09 14:10:09 -07002429 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002430 SLOGE("Stopping encryption due to low battery");
2431 rc = 0;
2432 goto errout;
2433 }
2434
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002435 }
2436 if (flush_outstanding_data(data)) {
2437 goto errout;
2438 }
2439 }
2440
Paul Lawrence87999172014-02-20 12:21:31 -08002441 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002442 rc = 0;
2443
2444errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002445 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002446 free(data->buffer);
2447 free(block_bitmap);
2448 return rc;
2449}
2450
2451static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2452 char *real_blkdev,
2453 off64_t size,
2454 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002455 off64_t tot_size,
2456 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002457{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002458 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002459 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002460 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002461
Paul Lawrence87999172014-02-20 12:21:31 -08002462 if (previously_encrypted_upto > *size_already_done) {
2463 SLOGD("Not fast encrypting since resuming part way through");
2464 return -1;
2465 }
2466
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002467 memset(&data, 0, sizeof(data));
2468 data.real_blkdev = real_blkdev;
2469 data.crypto_blkdev = crypto_blkdev;
2470
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002471 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002472 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2473 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002474 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002475 goto errout;
2476 }
2477
David Ng82fd8042015-01-21 13:55:21 -08002478 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2479 int retries = RETRY_MOUNT_ATTEMPTS;
2480 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2481 if (--retries) {
2482 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2483 crypto_blkdev, errno, strerror(errno));
2484 sleep(RETRY_MOUNT_DELAY_SECONDS);
2485 } else {
2486 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2487 crypto_blkdev, errno, strerror(errno));
2488 rc = ENABLE_INPLACE_ERR_DEV;
2489 goto errout;
2490 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002491 }
2492
2493 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002494 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002495 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002496 goto errout;
2497 }
2498
2499 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002500 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002501 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002502 goto errout;
2503 }
2504
2505 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2506 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2507 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2508
JP Abgrall7fc1de82014-10-10 18:43:41 -07002509 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002510
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002511 data.tot_used_blocks = data.numblocks;
2512 for (i = 0; i < aux_info.groups; ++i) {
2513 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2514 }
2515
2516 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002517 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002518
2519 struct timespec time_started = {0};
2520 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2521 SLOGW("Error getting time at start");
2522 // Note - continue anyway - we'll run with 0
2523 }
2524 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002525 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002526
2527 rc = encrypt_groups(&data);
2528 if (rc) {
2529 SLOGE("Error encrypting groups");
2530 goto errout;
2531 }
2532
Paul Lawrence87999172014-02-20 12:21:31 -08002533 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002534 rc = 0;
2535
2536errout:
2537 close(data.realfd);
2538 close(data.cryptofd);
2539
2540 return rc;
2541}
2542
Paul Lawrence3846be12014-09-22 11:33:54 -07002543static void log_progress_f2fs(u64 block, bool completed)
2544{
2545 // Precondition - if completed data = 0 else data != 0
2546
2547 // Track progress so we can skip logging blocks
2548 static u64 last_block = (u64)-1;
2549
2550 // Need to close existing 'Encrypting from' log?
2551 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2552 SLOGI("Encrypted to block %" PRId64, last_block);
2553 last_block = -1;
2554 }
2555
2556 // Need to start new 'Encrypting from' log?
2557 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2558 SLOGI("Encrypting from block %" PRId64, block);
2559 }
2560
2561 // Update offset
2562 if (!completed) {
2563 last_block = block;
2564 }
2565}
2566
Daniel Rosenberge82df162014-08-15 22:19:23 +00002567static int encrypt_one_block_f2fs(u64 pos, void *data)
2568{
2569 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2570
2571 priv_dat->blocks_already_done = pos - 1;
2572 update_progress(priv_dat, 1);
2573
2574 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2575
2576 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002577 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002578 return -1;
2579 }
2580
2581 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002582 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002583 return -1;
2584 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002585 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002586 }
2587
2588 return 0;
2589}
2590
2591static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2592 char *real_blkdev,
2593 off64_t size,
2594 off64_t *size_already_done,
2595 off64_t tot_size,
2596 off64_t previously_encrypted_upto)
2597{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002598 struct encryptGroupsData data;
2599 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002600 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002601 if (previously_encrypted_upto > *size_already_done) {
2602 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002603 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002604 }
2605 memset(&data, 0, sizeof(data));
2606 data.real_blkdev = real_blkdev;
2607 data.crypto_blkdev = crypto_blkdev;
2608 data.realfd = -1;
2609 data.cryptofd = -1;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002610 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002611 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002612 real_blkdev);
2613 goto errout;
2614 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002615 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002616 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002617 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002618 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002619 goto errout;
2620 }
2621
2622 f2fs_info = generate_f2fs_info(data.realfd);
2623 if (!f2fs_info)
2624 goto errout;
2625
2626 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2627 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2628 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2629
2630 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2631
2632 data.one_pct = data.tot_used_blocks / 100;
2633 data.cur_pct = 0;
2634 data.time_started = time(NULL);
2635 data.remaining_time = -1;
2636
2637 data.buffer = malloc(f2fs_info->block_size);
2638 if (!data.buffer) {
2639 SLOGE("Failed to allocate crypto buffer");
2640 goto errout;
2641 }
2642
2643 data.count = 0;
2644
2645 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2646 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2647
2648 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002649 SLOGE("Error in running over f2fs blocks");
2650 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002651 goto errout;
2652 }
2653
2654 *size_already_done += size;
2655 rc = 0;
2656
2657errout:
2658 if (rc)
2659 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2660
Paul Lawrence3846be12014-09-22 11:33:54 -07002661 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002662 free(f2fs_info);
2663 free(data.buffer);
2664 close(data.realfd);
2665 close(data.cryptofd);
2666
2667 return rc;
2668}
2669
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002670static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2671 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002672 off64_t tot_size,
2673 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002674{
2675 int realfd, cryptofd;
2676 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002677 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002678 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002679 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002680 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002681
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002682 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002683 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002684 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002685 }
2686
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002687 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002688 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2689 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002690 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002691 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002692 }
2693
2694 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2695 * The size passed in is the number of 512 byte sectors in the filesystem.
2696 * So compute the number of whole 4K blocks we should read/write,
2697 * and the remainder.
2698 */
2699 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2700 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002701 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2702 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002703
2704 SLOGE("Encrypting filesystem in place...");
2705
Paul Lawrence87999172014-02-20 12:21:31 -08002706 i = previously_encrypted_upto + 1 - *size_already_done;
2707
2708 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2709 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2710 goto errout;
2711 }
2712
2713 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2714 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2715 goto errout;
2716 }
2717
2718 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2719 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2720 SLOGE("Error reading initial sectors from real_blkdev %s for "
2721 "inplace encrypt\n", crypto_blkdev);
2722 goto errout;
2723 }
2724 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2725 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2726 "inplace encrypt\n", crypto_blkdev);
2727 goto errout;
2728 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002729 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002730 }
2731 }
2732
Ken Sumrall29d8da82011-05-18 17:20:07 -07002733 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002734 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002735 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002736 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002737 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002738 if (new_pct > cur_pct) {
2739 char buf[8];
2740
2741 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002742 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002743 property_set("vold.encrypt_progress", buf);
2744 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002745 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002746 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002747 goto errout;
2748 }
2749 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002750 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2751 goto errout;
2752 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002753 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002754 CRYPT_SECTORS_PER_BUFSIZE,
2755 i * CRYPT_SECTORS_PER_BUFSIZE);
2756 }
2757
Paul Lawrence73d7a022014-06-09 14:10:09 -07002758 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002759 SLOGE("Stopping encryption due to low battery");
2760 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2761 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002762 goto errout;
2763 }
2764 }
2765
2766 /* Do any remaining sectors */
2767 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002768 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2769 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002770 goto errout;
2771 }
Paul Lawrence87999172014-02-20 12:21:31 -08002772 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2773 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002774 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002775 } else {
2776 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002777 }
2778 }
2779
Ken Sumrall29d8da82011-05-18 17:20:07 -07002780 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002781 rc = 0;
2782
2783errout:
2784 close(realfd);
2785 close(cryptofd);
2786
2787 return rc;
2788}
2789
JP Abgrall7fc1de82014-10-10 18:43:41 -07002790/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002791static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2792 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002793 off64_t tot_size,
2794 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002795{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002796 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002797 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002798 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002799 }
2800
2801 if (*size_already_done + size < previously_encrypted_upto) {
2802 *size_already_done += size;
2803 return 0;
2804 }
2805
Daniel Rosenberge82df162014-08-15 22:19:23 +00002806 /* TODO: identify filesystem type.
2807 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2808 * then we will drop down to cryptfs_enable_inplace_f2fs.
2809 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002810 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002811 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002812 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002813 return 0;
2814 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002815 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002816
JP Abgrall7fc1de82014-10-10 18:43:41 -07002817 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002818 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002819 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002820 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002821 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002822 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002823
JP Abgrall7fc1de82014-10-10 18:43:41 -07002824 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002825 size, size_already_done, tot_size,
2826 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002827 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2828
2829 /* Hack for b/17898962, the following is the symptom... */
2830 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2831 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2832 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2833 return ENABLE_INPLACE_ERR_DEV;
2834 }
2835 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002836}
2837
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002838#define CRYPTO_ENABLE_WIPE 1
2839#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002840
2841#define FRAMEWORK_BOOT_WAIT 60
2842
Paul Lawrence87999172014-02-20 12:21:31 -08002843static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2844{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002845 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002846 if (fd == -1) {
2847 SLOGE("Error opening file %s", filename);
2848 return -1;
2849 }
2850
2851 char block[CRYPT_INPLACE_BUFSIZE];
2852 memset(block, 0, sizeof(block));
2853 if (unix_read(fd, block, sizeof(block)) < 0) {
2854 SLOGE("Error reading file %s", filename);
2855 close(fd);
2856 return -1;
2857 }
2858
2859 close(fd);
2860
2861 SHA256_CTX c;
2862 SHA256_Init(&c);
2863 SHA256_Update(&c, block, sizeof(block));
2864 SHA256_Final(buf, &c);
2865
2866 return 0;
2867}
2868
JP Abgrall62c7af32014-06-16 13:01:23 -07002869static int get_fs_type(struct fstab_rec *rec)
2870{
2871 if (!strcmp(rec->fs_type, "ext4")) {
2872 return EXT4_FS;
2873 } else if (!strcmp(rec->fs_type, "f2fs")) {
2874 return F2FS_FS;
2875 } else {
2876 return -1;
2877 }
2878}
2879
Paul Lawrence87999172014-02-20 12:21:31 -08002880static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2881 char *crypto_blkdev, char *real_blkdev,
2882 int previously_encrypted_upto)
2883{
2884 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002885 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002886
Paul Lawrence73d7a022014-06-09 14:10:09 -07002887 if (!is_battery_ok_to_start()) {
2888 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002889 return 0;
2890 }
2891
2892 /* The size of the userdata partition, and add in the vold volumes below */
2893 tot_encryption_size = crypt_ftr->fs_size;
2894
2895 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002896 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2897 int fs_type = get_fs_type(rec);
2898 if (fs_type < 0) {
2899 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2900 return -1;
2901 }
2902 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002903 } else if (how == CRYPTO_ENABLE_INPLACE) {
2904 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2905 crypt_ftr->fs_size, &cur_encryption_done,
2906 tot_encryption_size,
2907 previously_encrypted_upto);
2908
JP Abgrall7fc1de82014-10-10 18:43:41 -07002909 if (rc == ENABLE_INPLACE_ERR_DEV) {
2910 /* Hack for b/17898962 */
2911 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2912 cryptfs_reboot(reboot);
2913 }
2914
Paul Lawrence73d7a022014-06-09 14:10:09 -07002915 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002916 crypt_ftr->encrypted_upto = cur_encryption_done;
2917 }
2918
Paul Lawrence73d7a022014-06-09 14:10:09 -07002919 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002920 /* The inplace routine never actually sets the progress to 100% due
2921 * to the round down nature of integer division, so set it here */
2922 property_set("vold.encrypt_progress", "100");
2923 }
2924 } else {
2925 /* Shouldn't happen */
2926 SLOGE("cryptfs_enable: internal error, unknown option\n");
2927 rc = -1;
2928 }
2929
2930 return rc;
2931}
2932
Paul Lawrence13486032014-02-03 13:28:11 -08002933int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002934 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002935{
2936 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002937 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002938 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002939 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002940 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002941 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002942 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002943 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002944 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002945 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002946 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002947 bool rebootEncryption = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002948
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002949 if (!strcmp(howarg, "wipe")) {
2950 how = CRYPTO_ENABLE_WIPE;
2951 } else if (! strcmp(howarg, "inplace")) {
2952 how = CRYPTO_ENABLE_INPLACE;
2953 } else {
2954 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002955 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002956 }
2957
Paul Lawrence87999172014-02-20 12:21:31 -08002958 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002959 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2960 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2961 /* An encryption was underway and was interrupted */
2962 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2963 crypt_ftr.encrypted_upto = 0;
2964 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002965
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002966 /* At this point, we are in an inconsistent state. Until we successfully
2967 complete encryption, a reboot will leave us broken. So mark the
2968 encryption failed in case that happens.
2969 On successfully completing encryption, remove this flag */
2970 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002971
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002972 put_crypt_ftr_and_key(&crypt_ftr);
2973 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2974 if (!check_ftr_sha(&crypt_ftr)) {
2975 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2976 put_crypt_ftr_and_key(&crypt_ftr);
2977 goto error_unencrypted;
2978 }
2979
2980 /* Doing a reboot-encryption*/
2981 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2982 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2983 rebootEncryption = true;
2984 }
Paul Lawrence87999172014-02-20 12:21:31 -08002985 }
2986
2987 property_get("ro.crypto.state", encrypted_state, "");
2988 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2989 SLOGE("Device is already running encrypted, aborting");
2990 goto error_unencrypted;
2991 }
2992
2993 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2994 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002995 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002996
Ken Sumrall3ed82362011-01-28 23:31:16 -08002997 /* Get the size of the real block device */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002998 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002999 if (fd == -1) {
3000 SLOGE("Cannot open block device %s\n", real_blkdev);
3001 goto error_unencrypted;
3002 }
3003 unsigned long nr_sec;
3004 get_blkdev_size(fd, &nr_sec);
3005 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003006 SLOGE("Cannot get size of block device %s\n", real_blkdev);
3007 goto error_unencrypted;
3008 }
3009 close(fd);
3010
3011 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003012 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003013 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00003014 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00003015 if (fs_size_sec == 0)
3016 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3017
Paul Lawrence87999172014-02-20 12:21:31 -08003018 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003019
3020 if (fs_size_sec > max_fs_size_sec) {
3021 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3022 goto error_unencrypted;
3023 }
3024 }
3025
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003026 /* Get a wakelock as this may take a while, and we don't want the
3027 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3028 * wants to keep the screen on, it can grab a full wakelock.
3029 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003030 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003031 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3032
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003033 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003034 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003035 */
3036 property_set("vold.decrypt", "trigger_shutdown_framework");
3037 SLOGD("Just asked init to shut down class main\n");
3038
Jeff Sharkey9c484982015-03-31 10:35:33 -07003039 /* Ask vold to unmount all devices that it manages */
3040 if (vold_unmountAll()) {
3041 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003042 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003043
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003044 /* no_ui means we are being called from init, not settings.
3045 Now we always reboot from settings, so !no_ui means reboot
3046 */
3047 bool onlyCreateHeader = false;
3048 if (!no_ui) {
3049 /* Try fallback, which is to reboot and try there */
3050 onlyCreateHeader = true;
3051 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
3052 if (breadcrumb == 0) {
3053 SLOGE("Failed to create breadcrumb file");
3054 goto error_shutting_down;
3055 }
3056 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003057 }
3058
3059 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003060 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003061 /* Now that /data is unmounted, we need to mount a tmpfs
3062 * /data, set a property saying we're doing inplace encryption,
3063 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003064 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003065 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003066 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003067 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003068 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003069 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003070
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003071 /* restart the framework. */
3072 /* Create necessary paths on /data */
3073 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003074 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003075 }
3076
Ken Sumrall92736ef2012-10-17 20:57:14 -07003077 /* Ugh, shutting down the framework is not synchronous, so until it
3078 * can be fixed, this horrible hack will wait a moment for it all to
3079 * shut down before proceeding. Without it, some devices cannot
3080 * restart the graphics services.
3081 */
3082 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003083 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003084
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003085 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003086 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003087 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003088 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3089 goto error_shutting_down;
3090 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003091
Paul Lawrence87999172014-02-20 12:21:31 -08003092 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3093 crypt_ftr.fs_size = nr_sec
3094 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3095 } else {
3096 crypt_ftr.fs_size = nr_sec;
3097 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003098 /* At this point, we are in an inconsistent state. Until we successfully
3099 complete encryption, a reboot will leave us broken. So mark the
3100 encryption failed in case that happens.
3101 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003102 if (onlyCreateHeader) {
3103 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
3104 } else {
3105 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3106 }
Paul Lawrence87999172014-02-20 12:21:31 -08003107 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003108#ifndef CONFIG_HW_DISK_ENCRYPTION
3109 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3110#else
3111 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3112
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003113 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003114 if (!rc) {
3115 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3116 }
3117
3118 rc = set_hw_device_encryption_key(passwd,
3119 (char*) crypt_ftr.crypto_type_name);
3120 if (!rc) {
3121 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3122 goto error_shutting_down;
3123 }
3124#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003125
Paul Lawrence87999172014-02-20 12:21:31 -08003126 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003127 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
3128 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08003129 SLOGE("Cannot create encrypted master key\n");
3130 goto error_shutting_down;
3131 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003132
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003133 /* Replace scrypted intermediate key if we are preparing for a reboot */
3134 if (onlyCreateHeader) {
3135 unsigned char fake_master_key[KEY_LEN_BYTES];
3136 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
3137 memset(fake_master_key, 0, sizeof(fake_master_key));
3138 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
3139 encrypted_fake_master_key, &crypt_ftr);
3140 }
3141
Paul Lawrence87999172014-02-20 12:21:31 -08003142 /* Write the key to the end of the partition */
3143 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003144
Paul Lawrence87999172014-02-20 12:21:31 -08003145 /* If any persistent data has been remembered, save it.
3146 * If none, create a valid empty table and save that.
3147 */
3148 if (!persist_data) {
3149 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3150 if (pdata) {
3151 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3152 persist_data = pdata;
3153 }
3154 }
3155 if (persist_data) {
3156 save_persistent_data();
3157 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003158 }
3159
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003160 if (onlyCreateHeader) {
3161 sleep(2);
3162 cryptfs_reboot(reboot);
3163 }
3164
3165 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07003166 /* startup service classes main and late_start */
3167 property_set("vold.decrypt", "trigger_restart_min_framework");
3168 SLOGD("Just triggered restart_min_framework\n");
3169
3170 /* OK, the framework is restarted and will soon be showing a
3171 * progress bar. Time to setup an encrypted mapping, and
3172 * either write a new filesystem, or encrypt in place updating
3173 * the progress bar as we work.
3174 */
3175 }
3176
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003177 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003178 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003179 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003180
Paul Lawrence87999172014-02-20 12:21:31 -08003181 /* If we are continuing, check checksums match */
3182 rc = 0;
3183 if (previously_encrypted_upto) {
3184 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3185 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003186
Paul Lawrence87999172014-02-20 12:21:31 -08003187 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3188 sizeof(hash_first_block)) != 0) {
3189 SLOGE("Checksums do not match - trigger wipe");
3190 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003191 }
3192 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003193
Paul Lawrence87999172014-02-20 12:21:31 -08003194 if (!rc) {
3195 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3196 crypto_blkdev, real_blkdev,
3197 previously_encrypted_upto);
3198 }
3199
3200 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003201 if (!rc && how == CRYPTO_ENABLE_INPLACE
3202 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003203 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3204 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003205 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003206 SLOGE("Error calculating checksum for continuing encryption");
3207 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003208 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003209 }
3210
3211 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003212 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003213
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003214 if (! rc) {
3215 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003216 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003217
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003218 if (how == CRYPTO_ENABLE_INPLACE
3219 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003220 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3221 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003222 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003223 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003224
Paul Lawrence6bfed202014-07-28 12:47:22 -07003225 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003226
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003227 if (how == CRYPTO_ENABLE_WIPE
3228 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003229 char value[PROPERTY_VALUE_MAX];
3230 property_get("ro.crypto.state", value, "");
3231 if (!strcmp(value, "")) {
3232 /* default encryption - continue first boot sequence */
3233 property_set("ro.crypto.state", "encrypted");
3234 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003235 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
3236 // Bring up cryptkeeper that will check the password and set it
3237 property_set("vold.decrypt", "trigger_shutdown_framework");
3238 sleep(2);
3239 property_set("vold.encrypt_progress", "");
3240 cryptfs_trigger_restart_min_framework();
3241 } else {
3242 cryptfs_check_passwd(DEFAULT_PASSWORD);
3243 cryptfs_restart_internal(1);
3244 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003245 return 0;
3246 } else {
3247 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003248 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003249 }
Paul Lawrence87999172014-02-20 12:21:31 -08003250 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003251 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003252 cryptfs_reboot(shutdown);
3253 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003254 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003255 char value[PROPERTY_VALUE_MAX];
3256
Ken Sumrall319369a2012-06-27 16:30:18 -07003257 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003258 if (!strcmp(value, "1")) {
3259 /* wipe data if encryption failed */
3260 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3261 mkdir("/cache/recovery", 0700);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003262 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003263 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003264 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3265 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003266 close(fd);
3267 } else {
3268 SLOGE("could not open /cache/recovery/command\n");
3269 }
Paul Lawrence87999172014-02-20 12:21:31 -08003270 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003271 } else {
3272 /* set property to trigger dialog */
3273 property_set("vold.encrypt_progress", "error_partially_encrypted");
3274 release_wake_lock(lockid);
3275 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003276 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003277 }
3278
Ken Sumrall3ed82362011-01-28 23:31:16 -08003279 /* hrm, the encrypt step claims success, but the reboot failed.
3280 * This should not happen.
3281 * Set the property and return. Hope the framework can deal with it.
3282 */
3283 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003284 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003285 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003286
3287error_unencrypted:
3288 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003289 if (lockid[0]) {
3290 release_wake_lock(lockid);
3291 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003292 return -1;
3293
3294error_shutting_down:
3295 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3296 * but the framework is stopped and not restarted to show the error, so it's up to
3297 * vold to restart the system.
3298 */
3299 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003300 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003301
3302 /* shouldn't get here */
3303 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003304 if (lockid[0]) {
3305 release_wake_lock(lockid);
3306 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003307 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003308}
3309
Paul Lawrence569649f2015-09-09 12:13:00 -07003310int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003311{
Paul Lawrence569649f2015-09-09 12:13:00 -07003312 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003313}
3314
Paul Lawrence569649f2015-09-09 12:13:00 -07003315int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003316{
3317 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07003318 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003319}
3320
3321int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003322{
Paul Crowley38132a12016-02-09 09:50:32 +00003323 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003324 SLOGE("cryptfs_changepw not valid for file encryption");
3325 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003326 }
3327
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003328 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003329 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003330
3331 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003332 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003333 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003334 return -1;
3335 }
3336
Paul Lawrencef4faa572014-01-29 13:31:03 -08003337 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3338 SLOGE("Invalid crypt_type %d", crypt_type);
3339 return -1;
3340 }
3341
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003342 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003343 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003344 SLOGE("Error getting crypt footer and key");
3345 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003346 }
3347
Paul Lawrencef4faa572014-01-29 13:31:03 -08003348 crypt_ftr.crypt_type = crypt_type;
3349
JP Abgrall933216c2015-02-11 13:44:32 -08003350 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003351 : newpw,
3352 crypt_ftr.salt,
3353 saved_master_key,
3354 crypt_ftr.master_key,
3355 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003356 if (rc) {
3357 SLOGE("Encrypt master key failed: %d", rc);
3358 return -1;
3359 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003360 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003361 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003362
Ajay Dudani87701e22014-09-17 21:02:52 -07003363#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003364 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3365 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3366 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3367 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3368 if (!rc)
3369 return -1;
3370 } else {
3371 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3372 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3373 if (!rc)
3374 return -1;
3375 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003376 }
3377#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003378 return 0;
3379}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003380
Rubin Xu85c01f92014-10-13 12:49:54 +01003381static unsigned int persist_get_max_entries(int encrypted) {
3382 struct crypt_mnt_ftr crypt_ftr;
3383 unsigned int dsize;
3384 unsigned int max_persistent_entries;
3385
3386 /* If encrypted, use the values from the crypt_ftr, otherwise
3387 * use the values for the current spec.
3388 */
3389 if (encrypted) {
3390 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3391 return -1;
3392 }
3393 dsize = crypt_ftr.persist_data_size;
3394 } else {
3395 dsize = CRYPT_PERSIST_DATA_SIZE;
3396 }
3397
3398 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3399 sizeof(struct crypt_persist_entry);
3400
3401 return max_persistent_entries;
3402}
3403
3404static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003405{
3406 unsigned int i;
3407
3408 if (persist_data == NULL) {
3409 return -1;
3410 }
3411 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3412 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3413 /* We found it! */
3414 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3415 return 0;
3416 }
3417 }
3418
3419 return -1;
3420}
3421
Rubin Xu85c01f92014-10-13 12:49:54 +01003422static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003423{
3424 unsigned int i;
3425 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003426 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003427
3428 if (persist_data == NULL) {
3429 return -1;
3430 }
3431
Rubin Xu85c01f92014-10-13 12:49:54 +01003432 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003433
3434 num = persist_data->persist_valid_entries;
3435
3436 for (i = 0; i < num; i++) {
3437 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3438 /* We found an existing entry, update it! */
3439 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3440 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3441 return 0;
3442 }
3443 }
3444
3445 /* We didn't find it, add it to the end, if there is room */
3446 if (persist_data->persist_valid_entries < max_persistent_entries) {
3447 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3448 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3449 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3450 persist_data->persist_valid_entries++;
3451 return 0;
3452 }
3453
3454 return -1;
3455}
3456
Rubin Xu85c01f92014-10-13 12:49:54 +01003457/**
3458 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3459 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3460 */
3461static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003462 unsigned int field_len;
3463 unsigned int key_index;
3464 field_len = strlen(field);
3465
3466 if (index == 0) {
3467 // The first key in a multi-entry field is just the filedname itself.
3468 if (!strcmp(key, field)) {
3469 return 1;
3470 }
3471 }
3472 // Match key against "%s_%d" % (field, index)
3473 if (strlen(key) < field_len + 1 + 1) {
3474 // Need at least a '_' and a digit.
3475 return 0;
3476 }
3477 if (strncmp(key, field, field_len)) {
3478 // If the key does not begin with field, it's not a match.
3479 return 0;
3480 }
3481 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3482 return 0;
3483 }
3484 return key_index >= index;
3485}
3486
3487/*
3488 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3489 * remaining entries starting from index will be deleted.
3490 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3491 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3492 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3493 *
3494 */
3495static int persist_del_keys(const char *fieldname, unsigned index)
3496{
3497 unsigned int i;
3498 unsigned int j;
3499 unsigned int num;
3500
3501 if (persist_data == NULL) {
3502 return PERSIST_DEL_KEY_ERROR_OTHER;
3503 }
3504
3505 num = persist_data->persist_valid_entries;
3506
3507 j = 0; // points to the end of non-deleted entries.
3508 // Filter out to-be-deleted entries in place.
3509 for (i = 0; i < num; i++) {
3510 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3511 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3512 j++;
3513 }
3514 }
3515
3516 if (j < num) {
3517 persist_data->persist_valid_entries = j;
3518 // Zeroise the remaining entries
3519 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3520 return PERSIST_DEL_KEY_OK;
3521 } else {
3522 // Did not find an entry matching the given fieldname
3523 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3524 }
3525}
3526
3527static int persist_count_keys(const char *fieldname)
3528{
3529 unsigned int i;
3530 unsigned int count;
3531
3532 if (persist_data == NULL) {
3533 return -1;
3534 }
3535
3536 count = 0;
3537 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3538 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3539 count++;
3540 }
3541 }
3542
3543 return count;
3544}
3545
Ken Sumrall160b4d62013-04-22 12:15:39 -07003546/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003547int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003548{
Paul Crowley38132a12016-02-09 09:50:32 +00003549 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003550 SLOGE("Cannot get field when file encrypted");
3551 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003552 }
3553
Ken Sumrall160b4d62013-04-22 12:15:39 -07003554 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003555 /* CRYPTO_GETFIELD_OK is success,
3556 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3557 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3558 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003559 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003560 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3561 int i;
3562 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003563
3564 if (persist_data == NULL) {
3565 load_persistent_data();
3566 if (persist_data == NULL) {
3567 SLOGE("Getfield error, cannot load persistent data");
3568 goto out;
3569 }
3570 }
3571
Rubin Xu85c01f92014-10-13 12:49:54 +01003572 // Read value from persistent entries. If the original value is split into multiple entries,
3573 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003574 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003575 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3576 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3577 // value too small
3578 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3579 goto out;
3580 }
3581 rc = CRYPTO_GETFIELD_OK;
3582
3583 for (i = 1; /* break explicitly */; i++) {
3584 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3585 (int) sizeof(temp_field)) {
3586 // If the fieldname is very long, we stop as soon as it begins to overflow the
3587 // maximum field length. At this point we have in fact fully read out the original
3588 // value because cryptfs_setfield would not allow fields with longer names to be
3589 // written in the first place.
3590 break;
3591 }
3592 if (!persist_get_key(temp_field, temp_value)) {
3593 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3594 // value too small.
3595 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3596 goto out;
3597 }
3598 } else {
3599 // Exhaust all entries.
3600 break;
3601 }
3602 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003603 } else {
3604 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003605 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003606 }
3607
3608out:
3609 return rc;
3610}
3611
3612/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003613int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003614{
Paul Crowley38132a12016-02-09 09:50:32 +00003615 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003616 SLOGE("Cannot set field when file encrypted");
3617 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003618 }
3619
Ken Sumrall160b4d62013-04-22 12:15:39 -07003620 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003621 /* 0 is success, negative values are error */
3622 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003623 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003624 unsigned int field_id;
3625 char temp_field[PROPERTY_KEY_MAX];
3626 unsigned int num_entries;
3627 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003628
3629 if (persist_data == NULL) {
3630 load_persistent_data();
3631 if (persist_data == NULL) {
3632 SLOGE("Setfield error, cannot load persistent data");
3633 goto out;
3634 }
3635 }
3636
3637 property_get("ro.crypto.state", encrypted_state, "");
3638 if (!strcmp(encrypted_state, "encrypted") ) {
3639 encrypted = 1;
3640 }
3641
Rubin Xu85c01f92014-10-13 12:49:54 +01003642 // Compute the number of entries required to store value, each entry can store up to
3643 // (PROPERTY_VALUE_MAX - 1) chars
3644 if (strlen(value) == 0) {
3645 // Empty value also needs one entry to store.
3646 num_entries = 1;
3647 } else {
3648 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3649 }
3650
3651 max_keylen = strlen(fieldname);
3652 if (num_entries > 1) {
3653 // Need an extra "_%d" suffix.
3654 max_keylen += 1 + log10(num_entries);
3655 }
3656 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3657 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003658 goto out;
3659 }
3660
Rubin Xu85c01f92014-10-13 12:49:54 +01003661 // Make sure we have enough space to write the new value
3662 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3663 persist_get_max_entries(encrypted)) {
3664 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3665 goto out;
3666 }
3667
3668 // Now that we know persist_data has enough space for value, let's delete the old field first
3669 // to make up space.
3670 persist_del_keys(fieldname, 0);
3671
3672 if (persist_set_key(fieldname, value, encrypted)) {
3673 // fail to set key, should not happen as we have already checked the available space
3674 SLOGE("persist_set_key() error during setfield()");
3675 goto out;
3676 }
3677
3678 for (field_id = 1; field_id < num_entries; field_id++) {
3679 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3680
3681 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3682 // fail to set key, should not happen as we have already checked the available space.
3683 SLOGE("persist_set_key() error during setfield()");
3684 goto out;
3685 }
3686 }
3687
Ken Sumrall160b4d62013-04-22 12:15:39 -07003688 /* If we are running encrypted, save the persistent data now */
3689 if (encrypted) {
3690 if (save_persistent_data()) {
3691 SLOGE("Setfield error, cannot save persistent data");
3692 goto out;
3693 }
3694 }
3695
Rubin Xu85c01f92014-10-13 12:49:54 +01003696 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003697
3698out:
3699 return rc;
3700}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003701
3702/* Checks userdata. Attempt to mount the volume if default-
3703 * encrypted.
3704 * On success trigger next init phase and return 0.
3705 * Currently do not handle failure - see TODO below.
3706 */
3707int cryptfs_mount_default_encrypted(void)
3708{
3709 char decrypt_state[PROPERTY_VALUE_MAX];
3710 property_get("vold.decrypt", decrypt_state, "0");
3711 if (!strcmp(decrypt_state, "0")) {
3712 SLOGE("Not encrypted - should not call here");
3713 } else {
3714 int crypt_type = cryptfs_get_password_type();
3715 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3716 SLOGE("Bad crypt type - error");
3717 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3718 SLOGD("Password is not default - "
3719 "starting min framework to prompt");
3720 property_set("vold.decrypt", "trigger_restart_min_framework");
3721 return 0;
3722 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3723 SLOGD("Password is default - restarting filesystem");
3724 cryptfs_restart_internal(0);
3725 return 0;
3726 } else {
3727 SLOGE("Encrypted, default crypt type but can't decrypt");
3728 }
3729 }
3730
Paul Lawrence6bfed202014-07-28 12:47:22 -07003731 /** Corrupt. Allow us to boot into framework, which will detect bad
3732 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003733 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003734 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003735 return 0;
3736}
3737
3738/* Returns type of the password, default, pattern, pin or password.
3739 */
3740int cryptfs_get_password_type(void)
3741{
Paul Crowley38132a12016-02-09 09:50:32 +00003742 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003743 SLOGE("cryptfs_get_password_type not valid for file encryption");
3744 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003745 }
3746
Paul Lawrencef4faa572014-01-29 13:31:03 -08003747 struct crypt_mnt_ftr crypt_ftr;
3748
3749 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3750 SLOGE("Error getting crypt footer and key\n");
3751 return -1;
3752 }
3753
Paul Lawrence6bfed202014-07-28 12:47:22 -07003754 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3755 return -1;
3756 }
3757
Paul Lawrencef4faa572014-01-29 13:31:03 -08003758 return crypt_ftr.crypt_type;
3759}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003760
Paul Lawrence05335c32015-03-05 09:46:23 -08003761const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003762{
Paul Crowley38132a12016-02-09 09:50:32 +00003763 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003764 SLOGE("cryptfs_get_password not valid for file encryption");
3765 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003766 }
3767
Paul Lawrence399317e2014-03-10 13:20:50 -07003768 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003769 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003770 if (now.tv_sec < password_expiry_time) {
3771 return password;
3772 } else {
3773 cryptfs_clear_password();
3774 return 0;
3775 }
3776}
3777
3778void cryptfs_clear_password()
3779{
3780 if (password) {
3781 size_t len = strlen(password);
3782 memset(password, 0, len);
3783 free(password);
3784 password = 0;
3785 password_expiry_time = 0;
3786 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003787}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003788
3789int cryptfs_enable_file()
3790{
Paul Crowley38132a12016-02-09 09:50:32 +00003791 return e4crypt_initialize_global_de();
Paul Lawrence731a7a22015-04-28 22:14:15 +00003792}
3793
Paul Lawrence0c247462015-10-29 10:30:57 -07003794int cryptfs_isConvertibleToFBE()
3795{
3796 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3797 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
3798}
3799
Paul Lawrence731a7a22015-04-28 22:14:15 +00003800int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3801{
3802 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3803 SLOGE("Failed to initialize crypt_ftr");
3804 return -1;
3805 }
3806
3807 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3808 crypt_ftr->salt, crypt_ftr)) {
3809 SLOGE("Cannot create encrypted master key\n");
3810 return -1;
3811 }
3812
3813 //crypt_ftr->keysize = key_length / 8;
3814 return 0;
3815}
3816
3817int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3818 unsigned char* master_key)
3819{
3820 int rc;
3821
Paul Lawrence731a7a22015-04-28 22:14:15 +00003822 unsigned char* intermediate_key = 0;
3823 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003824
3825 if (password == 0 || *password == 0) {
3826 password = DEFAULT_PASSWORD;
3827 }
3828
Paul Lawrence731a7a22015-04-28 22:14:15 +00003829 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3830 &intermediate_key_size);
3831
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003832 int N = 1 << ftr->N_factor;
3833 int r = 1 << ftr->r_factor;
3834 int p = 1 << ftr->p_factor;
3835
3836 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3837
3838 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3839 ftr->salt, sizeof(ftr->salt), N, r, p,
3840 scrypted_intermediate_key,
3841 sizeof(scrypted_intermediate_key));
3842
3843 free(intermediate_key);
3844
3845 if (rc) {
3846 SLOGE("Can't calculate intermediate key");
3847 return rc;
3848 }
3849
3850 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3851 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00003852}
3853
3854int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3855 const unsigned char* master_key)
3856{
3857 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3858 ftr);
3859}