blob: c436c20639ebe398842557a8161313faecebdfe7 [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 */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001067 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001068 int i;
1069
1070 io = (struct dm_ioctl *) buffer;
1071
1072 /* Load the mapping table for this device */
1073 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1074
1075 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1076 io->target_count = 1;
1077 tgt->status = 0;
1078 tgt->sector_start = 0;
1079 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -07001080#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001081 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1082 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1083 }
1084 else {
1085 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1086 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001087#else
1088 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1089#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001090
1091 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1092 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -08001093
1094 buff_offset = crypt_params - buffer;
1095 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
1096 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
1097 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001098 crypt_params += strlen(crypt_params) + 1;
1099 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1100 tgt->next = crypt_params - buffer;
1101
1102 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1103 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1104 break;
1105 }
1106 usleep(500000);
1107 }
1108
1109 if (i == TABLE_LOAD_RETRIES) {
1110 /* We failed to load the table, return an error */
1111 return -1;
1112 } else {
1113 return i + 1;
1114 }
1115}
1116
1117
1118static int get_dm_crypt_version(int fd, const char *name, int *version)
1119{
1120 char buffer[DM_CRYPT_BUF_SIZE];
1121 struct dm_ioctl *io;
1122 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001123
1124 io = (struct dm_ioctl *) buffer;
1125
1126 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1127
1128 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1129 return -1;
1130 }
1131
1132 /* Iterate over the returned versions, looking for name of "crypt".
1133 * When found, get and return the version.
1134 */
1135 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1136 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001137#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001138 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001139#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001140 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001141#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001142 /* We found the crypt driver, return the version, and get out */
1143 version[0] = v->version[0];
1144 version[1] = v->version[1];
1145 version[2] = v->version[2];
1146 return 0;
1147 }
1148 v = (struct dm_target_versions *)(((char *)v) + v->next);
1149 }
1150
1151 return -1;
1152}
1153
Jeff Sharkey9c484982015-03-31 10:35:33 -07001154static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
1155 const unsigned char *master_key, const char *real_blk_name,
1156 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001158 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001159 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001160 int fd=0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001162 int version[3];
1163 char *extra_params;
1164 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001166 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001167 SLOGE("Cannot open device-mapper\n");
1168 goto errout;
1169 }
1170
1171 io = (struct dm_ioctl *) buffer;
1172
1173 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1174 if (ioctl(fd, DM_DEV_CREATE, io)) {
1175 SLOGE("Cannot create dm-crypt device\n");
1176 goto errout;
1177 }
1178
1179 /* Get the device status, in particular, the name of it's device file */
1180 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1181 if (ioctl(fd, DM_DEV_STATUS, io)) {
1182 SLOGE("Cannot retrieve dm-crypt device status\n");
1183 goto errout;
1184 }
1185 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1186 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1187
Ken Sumralldb5e0262013-02-05 17:39:48 -08001188 extra_params = "";
1189 if (! get_dm_crypt_version(fd, name, version)) {
1190 /* Support for allow_discards was added in version 1.11.0 */
1191 if ((version[0] >= 2) ||
1192 ((version[0] == 1) && (version[1] >= 11))) {
1193 extra_params = "1 allow_discards";
1194 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1195 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001196 }
1197
Ken Sumralldb5e0262013-02-05 17:39:48 -08001198 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1199 fd, extra_params);
1200 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001201 SLOGE("Cannot load dm-crypt mapping table.\n");
1202 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001203 } else if (load_count > 1) {
1204 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001205 }
1206
1207 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001208 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001209
1210 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1211 SLOGE("Cannot resume the dm-crypt device\n");
1212 goto errout;
1213 }
1214
1215 /* We made it here with no errors. Woot! */
1216 retval = 0;
1217
1218errout:
1219 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1220
1221 return retval;
1222}
1223
Ken Sumrall29d8da82011-05-18 17:20:07 -07001224static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001225{
1226 int fd;
1227 char buffer[DM_CRYPT_BUF_SIZE];
1228 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001229 int retval = -1;
1230
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001231 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001232 SLOGE("Cannot open device-mapper\n");
1233 goto errout;
1234 }
1235
1236 io = (struct dm_ioctl *) buffer;
1237
1238 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1239 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1240 SLOGE("Cannot remove dm-crypt device\n");
1241 goto errout;
1242 }
1243
1244 /* We made it here with no errors. Woot! */
1245 retval = 0;
1246
1247errout:
1248 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1249
1250 return retval;
1251
1252}
1253
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001254static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001255 unsigned char *ikey, void *params UNUSED)
1256{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001257 SLOGI("Using pbkdf2 for cryptfs KDF");
1258
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001260 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1261 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1262 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001263}
1264
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001265static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001266 unsigned char *ikey, void *params)
1267{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001268 SLOGI("Using scrypt for cryptfs KDF");
1269
Kenny Rootc4c70f12013-06-14 12:11:38 -07001270 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1271
1272 int N = 1 << ftr->N_factor;
1273 int r = 1 << ftr->r_factor;
1274 int p = 1 << ftr->p_factor;
1275
1276 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001277 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001278 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1279 salt, SALT_LEN, N, r, p, ikey,
1280 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001281
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001282 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001283}
1284
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001285static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1286 unsigned char *ikey, void *params)
1287{
1288 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1289
1290 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001291 size_t signature_size;
1292 unsigned char* signature;
1293 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1294
1295 int N = 1 << ftr->N_factor;
1296 int r = 1 << ftr->r_factor;
1297 int p = 1 << ftr->p_factor;
1298
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001299 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1300 salt, SALT_LEN, N, r, p, ikey,
1301 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001302
1303 if (rc) {
1304 SLOGE("scrypt failed");
1305 return -1;
1306 }
1307
Shawn Willdene17a9c42014-09-08 13:04:08 -06001308 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1309 &signature, &signature_size)) {
1310 SLOGE("Signing failed");
1311 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001312 }
1313
1314 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1315 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1316 free(signature);
1317
1318 if (rc) {
1319 SLOGE("scrypt failed");
1320 return -1;
1321 }
1322
1323 return 0;
1324}
1325
1326static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1327 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001328 unsigned char *encrypted_master_key,
1329 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001330{
1331 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1332 EVP_CIPHER_CTX e_ctx;
1333 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001334 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001335
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001336 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001337 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001338
1339 switch (crypt_ftr->kdf_type) {
1340 case KDF_SCRYPT_KEYMASTER:
1341 if (keymaster_create_key(crypt_ftr)) {
1342 SLOGE("keymaster_create_key failed");
1343 return -1;
1344 }
1345
1346 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1347 SLOGE("scrypt failed");
1348 return -1;
1349 }
1350 break;
1351
1352 case KDF_SCRYPT:
1353 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1354 SLOGE("scrypt failed");
1355 return -1;
1356 }
1357 break;
1358
1359 default:
1360 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001361 return -1;
1362 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001363
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001364 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001365 EVP_CIPHER_CTX_init(&e_ctx);
1366 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001367 SLOGE("EVP_EncryptInit failed\n");
1368 return -1;
1369 }
1370 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001371
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001372 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001373 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001374 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001375 SLOGE("EVP_EncryptUpdate failed\n");
1376 return -1;
1377 }
Adam Langley889c4f12014-09-03 14:23:13 -07001378 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001379 SLOGE("EVP_EncryptFinal failed\n");
1380 return -1;
1381 }
1382
1383 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1384 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1385 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001386 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001387
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001388 /* Store the scrypt of the intermediate key, so we can validate if it's a
1389 password error or mount error when things go wrong.
1390 Note there's no need to check for errors, since if this is incorrect, we
1391 simply won't wipe userdata, which is the correct default behavior
1392 */
1393 int N = 1 << crypt_ftr->N_factor;
1394 int r = 1 << crypt_ftr->r_factor;
1395 int p = 1 << crypt_ftr->p_factor;
1396
1397 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1398 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1399 crypt_ftr->scrypted_intermediate_key,
1400 sizeof(crypt_ftr->scrypted_intermediate_key));
1401
1402 if (rc) {
1403 SLOGE("encrypt_master_key: crypto_scrypt failed");
1404 }
1405
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001406 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001407}
1408
Paul Lawrence731a7a22015-04-28 22:14:15 +00001409static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001410 unsigned char *encrypted_master_key,
1411 unsigned char *decrypted_master_key,
1412 kdf_func kdf, void *kdf_params,
1413 unsigned char** intermediate_key,
1414 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001415{
1416 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 -08001417 EVP_CIPHER_CTX d_ctx;
1418 int decrypted_len, final_len;
1419
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001420 /* Turn the password into an intermediate key and IV that can decrypt the
1421 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001422 if (kdf(passwd, salt, ikey, kdf_params)) {
1423 SLOGE("kdf failed");
1424 return -1;
1425 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426
1427 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001428 EVP_CIPHER_CTX_init(&d_ctx);
1429 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430 return -1;
1431 }
1432 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1433 /* Decrypt the master key */
1434 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1435 encrypted_master_key, KEY_LEN_BYTES)) {
1436 return -1;
1437 }
Adam Langley889c4f12014-09-03 14:23:13 -07001438 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001439 return -1;
1440 }
1441
1442 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1443 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001444 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001445
1446 /* Copy intermediate key if needed by params */
1447 if (intermediate_key && intermediate_key_size) {
1448 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1449 if (intermediate_key) {
1450 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1451 *intermediate_key_size = KEY_LEN_BYTES;
1452 }
1453 }
1454
1455 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001456}
1457
Kenny Rootc4c70f12013-06-14 12:11:38 -07001458static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001459{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001460 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001461 *kdf = scrypt_keymaster;
1462 *kdf_params = ftr;
1463 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001464 *kdf = scrypt;
1465 *kdf_params = ftr;
1466 } else {
1467 *kdf = pbkdf2;
1468 *kdf_params = NULL;
1469 }
1470}
1471
Paul Lawrence731a7a22015-04-28 22:14:15 +00001472static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001473 struct crypt_mnt_ftr *crypt_ftr,
1474 unsigned char** intermediate_key,
1475 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001476{
1477 kdf_func kdf;
1478 void *kdf_params;
1479 int ret;
1480
1481 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001482 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1483 decrypted_master_key, kdf, kdf_params,
1484 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001485 if (ret != 0) {
1486 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001487 }
1488
1489 return ret;
1490}
1491
1492static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1493 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001494 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001495 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001496
1497 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001498 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001499 read(fd, key_buf, sizeof(key_buf));
1500 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001501 close(fd);
1502
1503 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001504 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001505}
1506
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001507int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001508{
Greg Hackmann955653e2014-09-24 14:55:20 -07001509 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001510#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001511
1512 /* Now umount the tmpfs filesystem */
1513 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001514 if (umount(mountpoint) == 0) {
1515 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001516 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001517
1518 if (errno == EINVAL) {
1519 /* EINVAL is returned if the directory is not a mountpoint,
1520 * i.e. there is no filesystem mounted there. So just get out.
1521 */
1522 break;
1523 }
1524
1525 err = errno;
1526
1527 /* If allowed, be increasingly aggressive before the last two retries */
1528 if (kill) {
1529 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1530 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001531 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001532 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1533 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001534 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001535 }
1536 }
1537
1538 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001539 }
1540
1541 if (i < WAIT_UNMOUNT_COUNT) {
1542 SLOGD("unmounting %s succeeded\n", mountpoint);
1543 rc = 0;
1544 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001545 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001546 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001547 rc = -1;
1548 }
1549
1550 return rc;
1551}
1552
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001553#define DATA_PREP_TIMEOUT 1000
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001554static int prep_data_fs(void)
1555{
1556 int i;
1557
Jeff Sharkey47695b22016-02-01 17:02:29 -07001558 // NOTE: post_fs_data results in init calling back around to vold, so all
1559 // callers to this method must be async
1560
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001561 /* Do the prep of the /data filesystem */
1562 property_set("vold.post_fs_data_done", "0");
1563 property_set("vold.decrypt", "trigger_post_fs_data");
1564 SLOGD("Just triggered post_fs_data\n");
1565
Ken Sumrallc5872692013-05-14 15:26:31 -07001566 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001567 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001568 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001569
1570 property_get("vold.post_fs_data_done", p, "0");
1571 if (*p == '1') {
1572 break;
1573 } else {
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001574 usleep(50000);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001575 }
1576 }
1577 if (i == DATA_PREP_TIMEOUT) {
1578 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001579 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001580 return -1;
1581 } else {
1582 SLOGD("post_fs_data done\n");
1583 return 0;
1584 }
1585}
1586
Paul Lawrence74f29f12014-08-28 15:54:10 -07001587static void cryptfs_set_corrupt()
1588{
1589 // Mark the footer as bad
1590 struct crypt_mnt_ftr crypt_ftr;
1591 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1592 SLOGE("Failed to get crypto footer - panic");
1593 return;
1594 }
1595
1596 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1597 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1598 SLOGE("Failed to set crypto footer - panic");
1599 return;
1600 }
1601}
1602
1603static void cryptfs_trigger_restart_min_framework()
1604{
1605 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1606 SLOGE("Failed to mount tmpfs on data - panic");
1607 return;
1608 }
1609
1610 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1611 SLOGE("Failed to trigger post fs data - panic");
1612 return;
1613 }
1614
1615 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1616 SLOGE("Failed to trigger restart min framework - panic");
1617 return;
1618 }
1619}
1620
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001621/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001622static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001623{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001624 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001625 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001626 static int restart_successful = 0;
1627
1628 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001629 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001630 SLOGE("Encrypted filesystem not validated, aborting");
1631 return -1;
1632 }
1633
1634 if (restart_successful) {
1635 SLOGE("System already restarted with encrypted disk, aborting");
1636 return -1;
1637 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001638
Paul Lawrencef4faa572014-01-29 13:31:03 -08001639 if (restart_main) {
1640 /* Here is where we shut down the framework. The init scripts
1641 * start all services in one of three classes: core, main or late_start.
1642 * On boot, we start core and main. Now, we stop main, but not core,
1643 * as core includes vold and a few other really important things that
1644 * we need to keep running. Once main has stopped, we should be able
1645 * to umount the tmpfs /data, then mount the encrypted /data.
1646 * We then restart the class main, and also the class late_start.
1647 * At the moment, I've only put a few things in late_start that I know
1648 * are not needed to bring up the framework, and that also cause problems
1649 * with unmounting the tmpfs /data, but I hope to add add more services
1650 * to the late_start class as we optimize this to decrease the delay
1651 * till the user is asked for the password to the filesystem.
1652 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001653
Paul Lawrencef4faa572014-01-29 13:31:03 -08001654 /* The init files are setup to stop the class main when vold.decrypt is
1655 * set to trigger_reset_main.
1656 */
1657 property_set("vold.decrypt", "trigger_reset_main");
1658 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001659
Paul Lawrencef4faa572014-01-29 13:31:03 -08001660 /* Ugh, shutting down the framework is not synchronous, so until it
1661 * can be fixed, this horrible hack will wait a moment for it all to
1662 * shut down before proceeding. Without it, some devices cannot
1663 * restart the graphics services.
1664 */
1665 sleep(2);
1666 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001667
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001668 /* Now that the framework is shutdown, we should be able to umount()
1669 * the tmpfs filesystem, and mount the real one.
1670 */
1671
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001672 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1673 if (strlen(crypto_blkdev) == 0) {
1674 SLOGE("fs_crypto_blkdev not set\n");
1675 return -1;
1676 }
1677
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001678 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001679 /* If ro.crypto.readonly is set to 1, mount the decrypted
1680 * filesystem readonly. This is used when /data is mounted by
1681 * recovery mode.
1682 */
1683 char ro_prop[PROPERTY_VALUE_MAX];
1684 property_get("ro.crypto.readonly", ro_prop, "");
1685 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1686 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1687 rec->flags |= MS_RDONLY;
1688 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001689
Ken Sumralle5032c42012-04-01 23:58:44 -07001690 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001691 int retries = RETRY_MOUNT_ATTEMPTS;
1692 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001693
1694 /*
1695 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1696 * partitions in the fsck domain.
1697 */
1698 if (setexeccon(secontextFsck())){
1699 SLOGE("Failed to setexeccon");
1700 return -1;
1701 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001702 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1703 crypto_blkdev, 0))
1704 != 0) {
1705 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1706 /* TODO: invoke something similar to
1707 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1708 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1709 SLOGI("Failed to mount %s because it is busy - waiting",
1710 crypto_blkdev);
1711 if (--retries) {
1712 sleep(RETRY_MOUNT_DELAY_SECONDS);
1713 } else {
1714 /* Let's hope that a reboot clears away whatever is keeping
1715 the mount busy */
1716 cryptfs_reboot(reboot);
1717 }
1718 } else {
1719 SLOGE("Failed to mount decrypted data");
1720 cryptfs_set_corrupt();
1721 cryptfs_trigger_restart_min_framework();
1722 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001723 if (setexeccon(NULL)) {
1724 SLOGE("Failed to setexeccon");
1725 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001726 return -1;
1727 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001728 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001729 if (setexeccon(NULL)) {
1730 SLOGE("Failed to setexeccon");
1731 return -1;
1732 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001733
Ken Sumralle5032c42012-04-01 23:58:44 -07001734 property_set("vold.decrypt", "trigger_load_persist_props");
1735 /* Create necessary paths on /data */
1736 if (prep_data_fs()) {
1737 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001738 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001739
1740 /* startup service classes main and late_start */
1741 property_set("vold.decrypt", "trigger_restart_framework");
1742 SLOGD("Just triggered restart_framework\n");
1743
1744 /* Give it a few moments to get started */
1745 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001746 }
1747
Ken Sumrall0cc16632011-01-18 20:32:26 -08001748 if (rc == 0) {
1749 restart_successful = 1;
1750 }
1751
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001752 return rc;
1753}
1754
Paul Lawrencef4faa572014-01-29 13:31:03 -08001755int cryptfs_restart(void)
1756{
Paul Lawrence05335c32015-03-05 09:46:23 -08001757 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001758 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001759 SLOGE("cryptfs_restart not valid for file encryption:");
1760 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001761 }
1762
Paul Lawrencef4faa572014-01-29 13:31:03 -08001763 /* Call internal implementation forcing a restart of main service group */
1764 return cryptfs_restart_internal(1);
1765}
1766
Paul Lawrence05335c32015-03-05 09:46:23 -08001767static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001768{
1769 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001770 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001771 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001772
1773 property_get("ro.crypto.state", encrypted_state, "");
1774 if (strcmp(encrypted_state, "encrypted") ) {
1775 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001776 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001777 }
1778
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001779 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001780 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001781 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001782 }
1783
Ken Sumrall160b4d62013-04-22 12:15:39 -07001784 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001785 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001786
Ken Sumralle1a45852011-12-14 21:24:27 -08001787 /*
1788 * Only report this error if key_loc is a file and it exists.
1789 * If the device was never encrypted, and /data is not mountable for
1790 * some reason, returning 1 should prevent the UI from presenting the
1791 * a "enter password" screen, or worse, a "press button to wipe the
1792 * device" screen.
1793 */
1794 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1795 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001796 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001797 } else {
1798 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001799 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001800 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001801 }
1802
Paul Lawrence74f29f12014-08-28 15:54:10 -07001803 // Test for possible error flags
1804 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1805 SLOGE("Encryption process is partway completed\n");
1806 return CRYPTO_COMPLETE_PARTIAL;
1807 }
1808
1809 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1810 SLOGE("Encryption process was interrupted but cannot continue\n");
1811 return CRYPTO_COMPLETE_INCONSISTENT;
1812 }
1813
1814 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1815 SLOGE("Encryption is successful but data is corrupt\n");
1816 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001817 }
1818
1819 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001820 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001821}
1822
Paul Lawrencef4faa572014-01-29 13:31:03 -08001823static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1824 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001825{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001826 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001827 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001828 char crypto_blkdev[MAXPATHLEN];
1829 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001830 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001831 unsigned int orig_failed_decrypt_count;
1832 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001833 int use_keymaster = 0;
1834 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001835 unsigned char* intermediate_key = 0;
1836 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001837
Paul Lawrencef4faa572014-01-29 13:31:03 -08001838 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1839 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001840
Paul Lawrencef4faa572014-01-29 13:31:03 -08001841 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001842 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1843 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001844 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001845 rc = -1;
1846 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001847 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001848 }
1849
Paul Lawrencef4faa572014-01-29 13:31:03 -08001850 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1851
Ajay Dudani87701e22014-09-17 21:02:52 -07001852#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001853 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1854 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1855 SLOGE("Hardware encryption key does not match");
1856 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001857 }
1858#endif
1859
Paul Lawrence74f29f12014-08-28 15:54:10 -07001860 // Create crypto block device - all (non fatal) code paths
1861 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001862 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1863 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001864 SLOGE("Error creating decrypted block device\n");
1865 rc = -1;
1866 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001867 }
1868
Paul Lawrence74f29f12014-08-28 15:54:10 -07001869 /* Work out if the problem is the password or the data */
1870 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1871 scrypted_intermediate_key)];
1872 int N = 1 << crypt_ftr->N_factor;
1873 int r = 1 << crypt_ftr->r_factor;
1874 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001875
Paul Lawrence74f29f12014-08-28 15:54:10 -07001876 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1877 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1878 N, r, p, scrypted_intermediate_key,
1879 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001880
Paul Lawrence74f29f12014-08-28 15:54:10 -07001881 // Does the key match the crypto footer?
1882 if (rc == 0 && memcmp(scrypted_intermediate_key,
1883 crypt_ftr->scrypted_intermediate_key,
1884 sizeof(scrypted_intermediate_key)) == 0) {
1885 SLOGI("Password matches");
1886 rc = 0;
1887 } else {
1888 /* Try mounting the file system anyway, just in case the problem's with
1889 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001890 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1891 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001892 mkdir(tmp_mount_point, 0755);
1893 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1894 SLOGE("Error temp mounting decrypted block device\n");
1895 delete_crypto_blk_dev(label);
1896
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001897 rc = ++crypt_ftr->failed_decrypt_count;
1898 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001899 } else {
1900 /* Success! */
1901 SLOGI("Password did not match but decrypted drive mounted - continue");
1902 umount(tmp_mount_point);
1903 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001904 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001905 }
1906
1907 if (rc == 0) {
1908 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001909 if (orig_failed_decrypt_count != 0) {
1910 put_crypt_ftr_and_key(crypt_ftr);
1911 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001912
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001913 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001914 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001915 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001916
1917 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001918 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001919 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001920 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001921 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001922 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001923 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001924
Paul Lawrence74f29f12014-08-28 15:54:10 -07001925 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001926 use_keymaster = keymaster_check_compatibility();
1927 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001928 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001929 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1930 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1931 upgrade = 1;
1932 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001933 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001934 upgrade = 1;
1935 }
1936
1937 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001938 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1939 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001940 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001941 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001942 }
1943 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001944
1945 // Do not fail even if upgrade failed - machine is bootable
1946 // Note that if this code is ever hit, there is a *serious* problem
1947 // since KDFs should never fail. You *must* fix the kdf before
1948 // proceeding!
1949 if (rc) {
1950 SLOGW("Upgrade failed with error %d,"
1951 " but continuing with previous state",
1952 rc);
1953 rc = 0;
1954 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001955 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001956 }
1957
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001958 errout:
1959 if (intermediate_key) {
1960 memset(intermediate_key, 0, intermediate_key_size);
1961 free(intermediate_key);
1962 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001963 return rc;
1964}
1965
Ken Sumrall29d8da82011-05-18 17:20:07 -07001966/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001967 * Called by vold when it's asked to mount an encrypted external
1968 * storage volume. The incoming partition has no crypto header/footer,
1969 * as any metadata is been stored in a separate, small partition.
1970 *
1971 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001972 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001973int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1974 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001975 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001976 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001977 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001978 return -1;
1979 }
1980
1981 unsigned long nr_sec = 0;
1982 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001983 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001984
Ken Sumrall29d8da82011-05-18 17:20:07 -07001985 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001986 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001987 return -1;
1988 }
1989
Jeff Sharkey9c484982015-03-31 10:35:33 -07001990 struct crypt_mnt_ftr ext_crypt_ftr;
1991 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1992 ext_crypt_ftr.fs_size = nr_sec;
1993 ext_crypt_ftr.keysize = keysize;
1994 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001995
Jeff Sharkey9c484982015-03-31 10:35:33 -07001996 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1997 out_crypto_blkdev, label);
1998}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001999
Jeff Sharkey9c484982015-03-31 10:35:33 -07002000/*
2001 * Called by vold when it's asked to unmount an encrypted external
2002 * storage volume.
2003 */
2004int cryptfs_revert_ext_volume(const char* label) {
2005 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002006}
2007
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002008int cryptfs_crypto_complete(void)
2009{
2010 return do_crypto_complete("/data");
2011}
2012
Paul Lawrencef4faa572014-01-29 13:31:03 -08002013int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2014{
2015 char encrypted_state[PROPERTY_VALUE_MAX];
2016 property_get("ro.crypto.state", encrypted_state, "");
2017 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2018 SLOGE("encrypted fs already validated or not running with encryption,"
2019 " aborting");
2020 return -1;
2021 }
2022
2023 if (get_crypt_ftr_and_key(crypt_ftr)) {
2024 SLOGE("Error getting crypt footer and key");
2025 return -1;
2026 }
2027
2028 return 0;
2029}
2030
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002031int cryptfs_check_passwd(char *passwd)
2032{
Paul Lawrence05335c32015-03-05 09:46:23 -08002033 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00002034 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002035 SLOGE("cryptfs_check_passwd not valid for file encryption");
2036 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002037 }
2038
Paul Lawrencef4faa572014-01-29 13:31:03 -08002039 struct crypt_mnt_ftr crypt_ftr;
2040 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002041
Paul Lawrencef4faa572014-01-29 13:31:03 -08002042 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002043 if (rc) {
2044 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002045 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002046 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002047
Paul Lawrence3bd36d52015-06-09 13:37:44 -07002048 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002049 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2050 if (rc) {
2051 SLOGE("Password did not match");
2052 return rc;
2053 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002054
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002055 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2056 // Here we have a default actual password but a real password
2057 // we must test against the scrypted value
2058 // First, we must delete the crypto block device that
2059 // test_mount_encrypted_fs leaves behind as a side effect
2060 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2061 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2062 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2063 if (rc) {
2064 SLOGE("Default password did not match on reboot encryption");
2065 return rc;
2066 }
2067
2068 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2069 put_crypt_ftr_and_key(&crypt_ftr);
2070 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2071 if (rc) {
2072 SLOGE("Could not change password on reboot encryption");
2073 return rc;
2074 }
2075 }
2076
2077 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002078 cryptfs_clear_password();
2079 password = strdup(passwd);
2080 struct timespec now;
2081 clock_gettime(CLOCK_BOOTTIME, &now);
2082 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002083 }
2084
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002085 return rc;
2086}
2087
Ken Sumrall3ad90722011-10-04 20:38:29 -07002088int cryptfs_verify_passwd(char *passwd)
2089{
2090 struct crypt_mnt_ftr crypt_ftr;
2091 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002092 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002093 char encrypted_state[PROPERTY_VALUE_MAX];
2094 int rc;
2095
2096 property_get("ro.crypto.state", encrypted_state, "");
2097 if (strcmp(encrypted_state, "encrypted") ) {
2098 SLOGE("device not encrypted, aborting");
2099 return -2;
2100 }
2101
2102 if (!master_key_saved) {
2103 SLOGE("encrypted fs not yet mounted, aborting");
2104 return -1;
2105 }
2106
2107 if (!saved_mount_point) {
2108 SLOGE("encrypted fs failed to save mount point, aborting");
2109 return -1;
2110 }
2111
Ken Sumrall160b4d62013-04-22 12:15:39 -07002112 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002113 SLOGE("Error getting crypt footer and key\n");
2114 return -1;
2115 }
2116
2117 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2118 /* If the device has no password, then just say the password is valid */
2119 rc = 0;
2120 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002121 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002122 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2123 /* They match, the password is correct */
2124 rc = 0;
2125 } else {
2126 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2127 sleep(1);
2128 rc = 1;
2129 }
2130 }
2131
2132 return rc;
2133}
2134
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002135/* Initialize a crypt_mnt_ftr structure. The keysize is
2136 * defaulted to 16 bytes, and the filesystem size to 0.
2137 * Presumably, at a minimum, the caller will update the
2138 * filesystem size and crypto_type_name after calling this function.
2139 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002140static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002141{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002142 off64_t off;
2143
2144 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002145 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002146 ftr->major_version = CURRENT_MAJOR_VERSION;
2147 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002148 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002149 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002150
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002151 switch (keymaster_check_compatibility()) {
2152 case 1:
2153 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2154 break;
2155
2156 case 0:
2157 ftr->kdf_type = KDF_SCRYPT;
2158 break;
2159
2160 default:
2161 SLOGE("keymaster_check_compatibility failed");
2162 return -1;
2163 }
2164
Kenny Rootc4c70f12013-06-14 12:11:38 -07002165 get_device_scrypt_params(ftr);
2166
Ken Sumrall160b4d62013-04-22 12:15:39 -07002167 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2168 if (get_crypt_ftr_info(NULL, &off) == 0) {
2169 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2170 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2171 ftr->persist_data_size;
2172 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002173
2174 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002175}
2176
Ken Sumrall29d8da82011-05-18 17:20:07 -07002177static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002178{
Ken Sumralle550f782013-08-20 13:48:23 -07002179 const char *args[10];
2180 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2181 int num_args;
2182 int status;
2183 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002184 int rc = -1;
2185
Ken Sumrall29d8da82011-05-18 17:20:07 -07002186 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002187 args[0] = "/system/bin/make_ext4fs";
2188 args[1] = "-a";
2189 args[2] = "/data";
2190 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002191 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002192 args[4] = size_str;
2193 args[5] = crypto_blkdev;
2194 num_args = 6;
2195 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2196 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002197 } else if (type == F2FS_FS) {
2198 args[0] = "/system/bin/mkfs.f2fs";
2199 args[1] = "-t";
2200 args[2] = "-d1";
2201 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002202 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002203 args[4] = size_str;
2204 num_args = 5;
2205 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2206 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002207 } else {
2208 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2209 return -1;
2210 }
2211
Ken Sumralle550f782013-08-20 13:48:23 -07002212 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2213
2214 if (tmp != 0) {
2215 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002216 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002217 if (WIFEXITED(status)) {
2218 if (WEXITSTATUS(status)) {
2219 SLOGE("Error creating filesystem on %s, exit status %d ",
2220 crypto_blkdev, WEXITSTATUS(status));
2221 } else {
2222 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2223 rc = 0;
2224 }
2225 } else {
2226 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2227 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002228 }
2229
2230 return rc;
2231}
2232
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002233#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002234#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2235#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002236
2237/* aligned 32K writes tends to make flash happy.
2238 * SD card association recommends it.
2239 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002240#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002241#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002242#else
2243#define BLOCKS_AT_A_TIME 1024
2244#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002245
2246struct encryptGroupsData
2247{
2248 int realfd;
2249 int cryptofd;
2250 off64_t numblocks;
2251 off64_t one_pct, cur_pct, new_pct;
2252 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002253 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002254 char* real_blkdev, * crypto_blkdev;
2255 int count;
2256 off64_t offset;
2257 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002258 off64_t last_written_sector;
2259 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002260 time_t time_started;
2261 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002262};
2263
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002264static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002265{
2266 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002267
2268 if (is_used) {
2269 data->used_blocks_already_done++;
2270 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002271 if (data->tot_used_blocks) {
2272 data->new_pct = data->used_blocks_already_done / data->one_pct;
2273 } else {
2274 data->new_pct = data->blocks_already_done / data->one_pct;
2275 }
2276
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002277 if (data->new_pct > data->cur_pct) {
2278 char buf[8];
2279 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002280 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002281 property_set("vold.encrypt_progress", buf);
2282 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002283
2284 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002285 struct timespec time_now;
2286 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2287 SLOGW("Error getting time");
2288 } else {
2289 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2290 off64_t remaining_blocks = data->tot_used_blocks
2291 - data->used_blocks_already_done;
2292 int remaining_time = (int)(elapsed_time * remaining_blocks
2293 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002294
Paul Lawrence9c58a872014-09-30 09:12:51 -07002295 // Change time only if not yet set, lower, or a lot higher for
2296 // best user experience
2297 if (data->remaining_time == -1
2298 || remaining_time < data->remaining_time
2299 || remaining_time > data->remaining_time + 60) {
2300 char buf[8];
2301 snprintf(buf, sizeof(buf), "%d", remaining_time);
2302 property_set("vold.encrypt_time_remaining", buf);
2303 data->remaining_time = remaining_time;
2304 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002305 }
2306 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002307}
2308
Paul Lawrence3846be12014-09-22 11:33:54 -07002309static void log_progress(struct encryptGroupsData const* data, bool completed)
2310{
2311 // Precondition - if completed data = 0 else data != 0
2312
2313 // Track progress so we can skip logging blocks
2314 static off64_t offset = -1;
2315
2316 // Need to close existing 'Encrypting from' log?
2317 if (completed || (offset != -1 && data->offset != offset)) {
2318 SLOGI("Encrypted to sector %" PRId64,
2319 offset / info.block_size * CRYPT_SECTOR_SIZE);
2320 offset = -1;
2321 }
2322
2323 // Need to start new 'Encrypting from' log?
2324 if (!completed && offset != data->offset) {
2325 SLOGI("Encrypting from sector %" PRId64,
2326 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2327 }
2328
2329 // Update offset
2330 if (!completed) {
2331 offset = data->offset + (off64_t)data->count * info.block_size;
2332 }
2333}
2334
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002335static int flush_outstanding_data(struct encryptGroupsData* data)
2336{
2337 if (data->count == 0) {
2338 return 0;
2339 }
2340
Elliott Hughes231bdba2014-06-25 18:36:19 -07002341 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002342
2343 if (pread64(data->realfd, data->buffer,
2344 info.block_size * data->count, data->offset)
2345 <= 0) {
2346 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2347 data->real_blkdev);
2348 return -1;
2349 }
2350
2351 if (pwrite64(data->cryptofd, data->buffer,
2352 info.block_size * data->count, data->offset)
2353 <= 0) {
2354 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2355 data->crypto_blkdev);
2356 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002357 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002358 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002359 }
2360
2361 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002362 data->last_written_sector = (data->offset + data->count)
2363 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002364 return 0;
2365}
2366
2367static int encrypt_groups(struct encryptGroupsData* data)
2368{
2369 unsigned int i;
2370 u8 *block_bitmap = 0;
2371 unsigned int block;
2372 off64_t ret;
2373 int rc = -1;
2374
2375 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2376 if (!data->buffer) {
2377 SLOGE("Failed to allocate crypto buffer");
2378 goto errout;
2379 }
2380
2381 block_bitmap = malloc(info.block_size);
2382 if (!block_bitmap) {
2383 SLOGE("failed to allocate block bitmap");
2384 goto errout;
2385 }
2386
2387 for (i = 0; i < aux_info.groups; ++i) {
2388 SLOGI("Encrypting group %d", i);
2389
2390 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2391 u32 block_count = min(info.blocks_per_group,
2392 aux_info.len_blocks - first_block);
2393
2394 off64_t offset = (u64)info.block_size
2395 * aux_info.bg_desc[i].bg_block_bitmap;
2396
2397 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2398 if (ret != (int)info.block_size) {
2399 SLOGE("failed to read all of block group bitmap %d", i);
2400 goto errout;
2401 }
2402
2403 offset = (u64)info.block_size * first_block;
2404
2405 data->count = 0;
2406
2407 for (block = 0; block < block_count; block++) {
liminghaoaa08e582016-01-06 10:30:49 +08002408 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
2409 0 : bitmap_get_bit(block_bitmap, block);
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002410 update_progress(data, used);
2411 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002412 if (data->count == 0) {
2413 data->offset = offset;
2414 }
2415 data->count++;
2416 } else {
2417 if (flush_outstanding_data(data)) {
2418 goto errout;
2419 }
2420 }
2421
2422 offset += info.block_size;
2423
2424 /* Write data if we are aligned or buffer size reached */
2425 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2426 || data->count == BLOCKS_AT_A_TIME) {
2427 if (flush_outstanding_data(data)) {
2428 goto errout;
2429 }
2430 }
Paul Lawrence87999172014-02-20 12:21:31 -08002431
Paul Lawrence73d7a022014-06-09 14:10:09 -07002432 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002433 SLOGE("Stopping encryption due to low battery");
2434 rc = 0;
2435 goto errout;
2436 }
2437
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002438 }
2439 if (flush_outstanding_data(data)) {
2440 goto errout;
2441 }
2442 }
2443
Paul Lawrence87999172014-02-20 12:21:31 -08002444 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002445 rc = 0;
2446
2447errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002448 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002449 free(data->buffer);
2450 free(block_bitmap);
2451 return rc;
2452}
2453
2454static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2455 char *real_blkdev,
2456 off64_t size,
2457 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002458 off64_t tot_size,
2459 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002460{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002461 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002462 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002463 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002464
Paul Lawrence87999172014-02-20 12:21:31 -08002465 if (previously_encrypted_upto > *size_already_done) {
2466 SLOGD("Not fast encrypting since resuming part way through");
2467 return -1;
2468 }
2469
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002470 memset(&data, 0, sizeof(data));
2471 data.real_blkdev = real_blkdev;
2472 data.crypto_blkdev = crypto_blkdev;
2473
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002474 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002475 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2476 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002477 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002478 goto errout;
2479 }
2480
David Ng82fd8042015-01-21 13:55:21 -08002481 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2482 int retries = RETRY_MOUNT_ATTEMPTS;
2483 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2484 if (--retries) {
2485 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2486 crypto_blkdev, errno, strerror(errno));
2487 sleep(RETRY_MOUNT_DELAY_SECONDS);
2488 } else {
2489 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2490 crypto_blkdev, errno, strerror(errno));
2491 rc = ENABLE_INPLACE_ERR_DEV;
2492 goto errout;
2493 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002494 }
2495
2496 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002497 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002498 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002499 goto errout;
2500 }
2501
2502 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002503 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002504 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002505 goto errout;
2506 }
2507
2508 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2509 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2510 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2511
JP Abgrall7fc1de82014-10-10 18:43:41 -07002512 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002513
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002514 data.tot_used_blocks = data.numblocks;
2515 for (i = 0; i < aux_info.groups; ++i) {
2516 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2517 }
2518
2519 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002520 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002521
2522 struct timespec time_started = {0};
2523 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2524 SLOGW("Error getting time at start");
2525 // Note - continue anyway - we'll run with 0
2526 }
2527 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002528 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002529
2530 rc = encrypt_groups(&data);
2531 if (rc) {
2532 SLOGE("Error encrypting groups");
2533 goto errout;
2534 }
2535
Paul Lawrence87999172014-02-20 12:21:31 -08002536 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002537 rc = 0;
2538
2539errout:
2540 close(data.realfd);
2541 close(data.cryptofd);
2542
2543 return rc;
2544}
2545
Paul Lawrence3846be12014-09-22 11:33:54 -07002546static void log_progress_f2fs(u64 block, bool completed)
2547{
2548 // Precondition - if completed data = 0 else data != 0
2549
2550 // Track progress so we can skip logging blocks
2551 static u64 last_block = (u64)-1;
2552
2553 // Need to close existing 'Encrypting from' log?
2554 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2555 SLOGI("Encrypted to block %" PRId64, last_block);
2556 last_block = -1;
2557 }
2558
2559 // Need to start new 'Encrypting from' log?
2560 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2561 SLOGI("Encrypting from block %" PRId64, block);
2562 }
2563
2564 // Update offset
2565 if (!completed) {
2566 last_block = block;
2567 }
2568}
2569
Daniel Rosenberge82df162014-08-15 22:19:23 +00002570static int encrypt_one_block_f2fs(u64 pos, void *data)
2571{
2572 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2573
2574 priv_dat->blocks_already_done = pos - 1;
2575 update_progress(priv_dat, 1);
2576
2577 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2578
2579 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002580 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002581 return -1;
2582 }
2583
2584 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002585 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002586 return -1;
2587 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002588 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002589 }
2590
2591 return 0;
2592}
2593
2594static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2595 char *real_blkdev,
2596 off64_t size,
2597 off64_t *size_already_done,
2598 off64_t tot_size,
2599 off64_t previously_encrypted_upto)
2600{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002601 struct encryptGroupsData data;
2602 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002603 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002604 if (previously_encrypted_upto > *size_already_done) {
2605 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002606 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002607 }
2608 memset(&data, 0, sizeof(data));
2609 data.real_blkdev = real_blkdev;
2610 data.crypto_blkdev = crypto_blkdev;
2611 data.realfd = -1;
2612 data.cryptofd = -1;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002613 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002614 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002615 real_blkdev);
2616 goto errout;
2617 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002618 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002619 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002620 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002621 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002622 goto errout;
2623 }
2624
2625 f2fs_info = generate_f2fs_info(data.realfd);
2626 if (!f2fs_info)
2627 goto errout;
2628
2629 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2630 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2631 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2632
2633 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2634
2635 data.one_pct = data.tot_used_blocks / 100;
2636 data.cur_pct = 0;
2637 data.time_started = time(NULL);
2638 data.remaining_time = -1;
2639
2640 data.buffer = malloc(f2fs_info->block_size);
2641 if (!data.buffer) {
2642 SLOGE("Failed to allocate crypto buffer");
2643 goto errout;
2644 }
2645
2646 data.count = 0;
2647
2648 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2649 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2650
2651 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002652 SLOGE("Error in running over f2fs blocks");
2653 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002654 goto errout;
2655 }
2656
2657 *size_already_done += size;
2658 rc = 0;
2659
2660errout:
2661 if (rc)
2662 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2663
Paul Lawrence3846be12014-09-22 11:33:54 -07002664 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002665 free(f2fs_info);
2666 free(data.buffer);
2667 close(data.realfd);
2668 close(data.cryptofd);
2669
2670 return rc;
2671}
2672
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002673static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2674 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002675 off64_t tot_size,
2676 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002677{
2678 int realfd, cryptofd;
2679 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002680 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002681 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002682 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002683 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002684
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002685 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002686 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002687 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002688 }
2689
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002690 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002691 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2692 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002693 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002694 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002695 }
2696
2697 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2698 * The size passed in is the number of 512 byte sectors in the filesystem.
2699 * So compute the number of whole 4K blocks we should read/write,
2700 * and the remainder.
2701 */
2702 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2703 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002704 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2705 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002706
2707 SLOGE("Encrypting filesystem in place...");
2708
Paul Lawrence87999172014-02-20 12:21:31 -08002709 i = previously_encrypted_upto + 1 - *size_already_done;
2710
2711 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2712 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2713 goto errout;
2714 }
2715
2716 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2717 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2718 goto errout;
2719 }
2720
2721 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2722 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2723 SLOGE("Error reading initial sectors from real_blkdev %s for "
2724 "inplace encrypt\n", crypto_blkdev);
2725 goto errout;
2726 }
2727 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2728 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2729 "inplace encrypt\n", crypto_blkdev);
2730 goto errout;
2731 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002732 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002733 }
2734 }
2735
Ken Sumrall29d8da82011-05-18 17:20:07 -07002736 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002737 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002738 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002739 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002740 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002741 if (new_pct > cur_pct) {
2742 char buf[8];
2743
2744 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002745 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002746 property_set("vold.encrypt_progress", buf);
2747 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002748 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002749 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002750 goto errout;
2751 }
2752 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002753 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2754 goto errout;
2755 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002756 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002757 CRYPT_SECTORS_PER_BUFSIZE,
2758 i * CRYPT_SECTORS_PER_BUFSIZE);
2759 }
2760
Paul Lawrence73d7a022014-06-09 14:10:09 -07002761 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002762 SLOGE("Stopping encryption due to low battery");
2763 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2764 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002765 goto errout;
2766 }
2767 }
2768
2769 /* Do any remaining sectors */
2770 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002771 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2772 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002773 goto errout;
2774 }
Paul Lawrence87999172014-02-20 12:21:31 -08002775 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2776 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002777 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002778 } else {
2779 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002780 }
2781 }
2782
Ken Sumrall29d8da82011-05-18 17:20:07 -07002783 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002784 rc = 0;
2785
2786errout:
2787 close(realfd);
2788 close(cryptofd);
2789
2790 return rc;
2791}
2792
JP Abgrall7fc1de82014-10-10 18:43:41 -07002793/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002794static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2795 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002796 off64_t tot_size,
2797 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002798{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002799 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002800 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002801 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002802 }
2803
2804 if (*size_already_done + size < previously_encrypted_upto) {
2805 *size_already_done += size;
2806 return 0;
2807 }
2808
Daniel Rosenberge82df162014-08-15 22:19:23 +00002809 /* TODO: identify filesystem type.
2810 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2811 * then we will drop down to cryptfs_enable_inplace_f2fs.
2812 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002813 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002814 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002815 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002816 return 0;
2817 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002818 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002819
JP Abgrall7fc1de82014-10-10 18:43:41 -07002820 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002821 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002822 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002823 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002824 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002825 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002826
JP Abgrall7fc1de82014-10-10 18:43:41 -07002827 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002828 size, size_already_done, tot_size,
2829 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002830 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2831
2832 /* Hack for b/17898962, the following is the symptom... */
2833 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2834 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2835 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2836 return ENABLE_INPLACE_ERR_DEV;
2837 }
2838 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002839}
2840
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002841#define CRYPTO_ENABLE_WIPE 1
2842#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002843
2844#define FRAMEWORK_BOOT_WAIT 60
2845
Paul Lawrence87999172014-02-20 12:21:31 -08002846static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2847{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002848 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002849 if (fd == -1) {
2850 SLOGE("Error opening file %s", filename);
2851 return -1;
2852 }
2853
2854 char block[CRYPT_INPLACE_BUFSIZE];
2855 memset(block, 0, sizeof(block));
2856 if (unix_read(fd, block, sizeof(block)) < 0) {
2857 SLOGE("Error reading file %s", filename);
2858 close(fd);
2859 return -1;
2860 }
2861
2862 close(fd);
2863
2864 SHA256_CTX c;
2865 SHA256_Init(&c);
2866 SHA256_Update(&c, block, sizeof(block));
2867 SHA256_Final(buf, &c);
2868
2869 return 0;
2870}
2871
JP Abgrall62c7af32014-06-16 13:01:23 -07002872static int get_fs_type(struct fstab_rec *rec)
2873{
2874 if (!strcmp(rec->fs_type, "ext4")) {
2875 return EXT4_FS;
2876 } else if (!strcmp(rec->fs_type, "f2fs")) {
2877 return F2FS_FS;
2878 } else {
2879 return -1;
2880 }
2881}
2882
Paul Lawrence87999172014-02-20 12:21:31 -08002883static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2884 char *crypto_blkdev, char *real_blkdev,
2885 int previously_encrypted_upto)
2886{
2887 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002888 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002889
Paul Lawrence73d7a022014-06-09 14:10:09 -07002890 if (!is_battery_ok_to_start()) {
2891 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002892 return 0;
2893 }
2894
2895 /* The size of the userdata partition, and add in the vold volumes below */
2896 tot_encryption_size = crypt_ftr->fs_size;
2897
2898 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002899 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2900 int fs_type = get_fs_type(rec);
2901 if (fs_type < 0) {
2902 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2903 return -1;
2904 }
2905 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002906 } else if (how == CRYPTO_ENABLE_INPLACE) {
2907 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2908 crypt_ftr->fs_size, &cur_encryption_done,
2909 tot_encryption_size,
2910 previously_encrypted_upto);
2911
JP Abgrall7fc1de82014-10-10 18:43:41 -07002912 if (rc == ENABLE_INPLACE_ERR_DEV) {
2913 /* Hack for b/17898962 */
2914 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2915 cryptfs_reboot(reboot);
2916 }
2917
Paul Lawrence73d7a022014-06-09 14:10:09 -07002918 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002919 crypt_ftr->encrypted_upto = cur_encryption_done;
2920 }
2921
Paul Lawrence73d7a022014-06-09 14:10:09 -07002922 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002923 /* The inplace routine never actually sets the progress to 100% due
2924 * to the round down nature of integer division, so set it here */
2925 property_set("vold.encrypt_progress", "100");
2926 }
2927 } else {
2928 /* Shouldn't happen */
2929 SLOGE("cryptfs_enable: internal error, unknown option\n");
2930 rc = -1;
2931 }
2932
2933 return rc;
2934}
2935
Paul Lawrence13486032014-02-03 13:28:11 -08002936int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002937 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002938{
2939 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002940 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002941 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002942 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002943 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002944 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002945 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002946 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002947 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002948 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002949 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002950 bool rebootEncryption = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002951
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002952 if (!strcmp(howarg, "wipe")) {
2953 how = CRYPTO_ENABLE_WIPE;
2954 } else if (! strcmp(howarg, "inplace")) {
2955 how = CRYPTO_ENABLE_INPLACE;
2956 } else {
2957 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002958 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002959 }
2960
Paul Lawrence87999172014-02-20 12:21:31 -08002961 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002962 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2963 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2964 /* An encryption was underway and was interrupted */
2965 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2966 crypt_ftr.encrypted_upto = 0;
2967 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002968
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002969 /* At this point, we are in an inconsistent state. Until we successfully
2970 complete encryption, a reboot will leave us broken. So mark the
2971 encryption failed in case that happens.
2972 On successfully completing encryption, remove this flag */
2973 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002974
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002975 put_crypt_ftr_and_key(&crypt_ftr);
2976 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2977 if (!check_ftr_sha(&crypt_ftr)) {
2978 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2979 put_crypt_ftr_and_key(&crypt_ftr);
2980 goto error_unencrypted;
2981 }
2982
2983 /* Doing a reboot-encryption*/
2984 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2985 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2986 rebootEncryption = true;
2987 }
Paul Lawrence87999172014-02-20 12:21:31 -08002988 }
2989
2990 property_get("ro.crypto.state", encrypted_state, "");
2991 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2992 SLOGE("Device is already running encrypted, aborting");
2993 goto error_unencrypted;
2994 }
2995
2996 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2997 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002998 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002999
Ken Sumrall3ed82362011-01-28 23:31:16 -08003000 /* Get the size of the real block device */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003001 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09003002 if (fd == -1) {
3003 SLOGE("Cannot open block device %s\n", real_blkdev);
3004 goto error_unencrypted;
3005 }
3006 unsigned long nr_sec;
3007 get_blkdev_size(fd, &nr_sec);
3008 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003009 SLOGE("Cannot get size of block device %s\n", real_blkdev);
3010 goto error_unencrypted;
3011 }
3012 close(fd);
3013
3014 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003015 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003016 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00003017 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00003018 if (fs_size_sec == 0)
3019 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3020
Paul Lawrence87999172014-02-20 12:21:31 -08003021 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003022
3023 if (fs_size_sec > max_fs_size_sec) {
3024 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3025 goto error_unencrypted;
3026 }
3027 }
3028
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003029 /* Get a wakelock as this may take a while, and we don't want the
3030 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3031 * wants to keep the screen on, it can grab a full wakelock.
3032 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003033 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003034 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3035
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003036 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003037 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003038 */
3039 property_set("vold.decrypt", "trigger_shutdown_framework");
3040 SLOGD("Just asked init to shut down class main\n");
3041
Jeff Sharkey9c484982015-03-31 10:35:33 -07003042 /* Ask vold to unmount all devices that it manages */
3043 if (vold_unmountAll()) {
3044 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003045 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003046
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003047 /* no_ui means we are being called from init, not settings.
3048 Now we always reboot from settings, so !no_ui means reboot
3049 */
3050 bool onlyCreateHeader = false;
3051 if (!no_ui) {
3052 /* Try fallback, which is to reboot and try there */
3053 onlyCreateHeader = true;
3054 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
3055 if (breadcrumb == 0) {
3056 SLOGE("Failed to create breadcrumb file");
3057 goto error_shutting_down;
3058 }
3059 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003060 }
3061
3062 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003063 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003064 /* Now that /data is unmounted, we need to mount a tmpfs
3065 * /data, set a property saying we're doing inplace encryption,
3066 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003067 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003068 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003069 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003070 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003071 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003072 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003073
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003074 /* restart the framework. */
3075 /* Create necessary paths on /data */
3076 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003077 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003078 }
3079
Ken Sumrall92736ef2012-10-17 20:57:14 -07003080 /* Ugh, shutting down the framework is not synchronous, so until it
3081 * can be fixed, this horrible hack will wait a moment for it all to
3082 * shut down before proceeding. Without it, some devices cannot
3083 * restart the graphics services.
3084 */
3085 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003086 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003087
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003088 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003089 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003090 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003091 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3092 goto error_shutting_down;
3093 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003094
Paul Lawrence87999172014-02-20 12:21:31 -08003095 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3096 crypt_ftr.fs_size = nr_sec
3097 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3098 } else {
3099 crypt_ftr.fs_size = nr_sec;
3100 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003101 /* At this point, we are in an inconsistent state. Until we successfully
3102 complete encryption, a reboot will leave us broken. So mark the
3103 encryption failed in case that happens.
3104 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003105 if (onlyCreateHeader) {
3106 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
3107 } else {
3108 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3109 }
Paul Lawrence87999172014-02-20 12:21:31 -08003110 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003111#ifndef CONFIG_HW_DISK_ENCRYPTION
3112 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3113#else
3114 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3115
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003116 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003117 if (!rc) {
3118 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3119 }
3120
3121 rc = set_hw_device_encryption_key(passwd,
3122 (char*) crypt_ftr.crypto_type_name);
3123 if (!rc) {
3124 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3125 goto error_shutting_down;
3126 }
3127#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003128
Paul Lawrence87999172014-02-20 12:21:31 -08003129 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003130 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
3131 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08003132 SLOGE("Cannot create encrypted master key\n");
3133 goto error_shutting_down;
3134 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003135
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003136 /* Replace scrypted intermediate key if we are preparing for a reboot */
3137 if (onlyCreateHeader) {
3138 unsigned char fake_master_key[KEY_LEN_BYTES];
3139 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
3140 memset(fake_master_key, 0, sizeof(fake_master_key));
3141 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
3142 encrypted_fake_master_key, &crypt_ftr);
3143 }
3144
Paul Lawrence87999172014-02-20 12:21:31 -08003145 /* Write the key to the end of the partition */
3146 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003147
Paul Lawrence87999172014-02-20 12:21:31 -08003148 /* If any persistent data has been remembered, save it.
3149 * If none, create a valid empty table and save that.
3150 */
3151 if (!persist_data) {
3152 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3153 if (pdata) {
3154 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3155 persist_data = pdata;
3156 }
3157 }
3158 if (persist_data) {
3159 save_persistent_data();
3160 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003161 }
3162
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003163 if (onlyCreateHeader) {
3164 sleep(2);
3165 cryptfs_reboot(reboot);
3166 }
3167
3168 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07003169 /* startup service classes main and late_start */
3170 property_set("vold.decrypt", "trigger_restart_min_framework");
3171 SLOGD("Just triggered restart_min_framework\n");
3172
3173 /* OK, the framework is restarted and will soon be showing a
3174 * progress bar. Time to setup an encrypted mapping, and
3175 * either write a new filesystem, or encrypt in place updating
3176 * the progress bar as we work.
3177 */
3178 }
3179
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003180 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003181 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003182 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003183
Paul Lawrence87999172014-02-20 12:21:31 -08003184 /* If we are continuing, check checksums match */
3185 rc = 0;
3186 if (previously_encrypted_upto) {
3187 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3188 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003189
Paul Lawrence87999172014-02-20 12:21:31 -08003190 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3191 sizeof(hash_first_block)) != 0) {
3192 SLOGE("Checksums do not match - trigger wipe");
3193 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003194 }
3195 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003196
Paul Lawrence87999172014-02-20 12:21:31 -08003197 if (!rc) {
3198 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3199 crypto_blkdev, real_blkdev,
3200 previously_encrypted_upto);
3201 }
3202
3203 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003204 if (!rc && how == CRYPTO_ENABLE_INPLACE
3205 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003206 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3207 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003208 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003209 SLOGE("Error calculating checksum for continuing encryption");
3210 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003211 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003212 }
3213
3214 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003215 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003216
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003217 if (! rc) {
3218 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003219 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003220
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003221 if (how == CRYPTO_ENABLE_INPLACE
3222 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003223 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3224 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003225 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003226 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003227
Paul Lawrence6bfed202014-07-28 12:47:22 -07003228 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003229
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003230 if (how == CRYPTO_ENABLE_WIPE
3231 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003232 char value[PROPERTY_VALUE_MAX];
3233 property_get("ro.crypto.state", value, "");
3234 if (!strcmp(value, "")) {
3235 /* default encryption - continue first boot sequence */
3236 property_set("ro.crypto.state", "encrypted");
3237 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003238 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
3239 // Bring up cryptkeeper that will check the password and set it
3240 property_set("vold.decrypt", "trigger_shutdown_framework");
3241 sleep(2);
3242 property_set("vold.encrypt_progress", "");
3243 cryptfs_trigger_restart_min_framework();
3244 } else {
3245 cryptfs_check_passwd(DEFAULT_PASSWORD);
3246 cryptfs_restart_internal(1);
3247 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003248 return 0;
3249 } else {
3250 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003251 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003252 }
Paul Lawrence87999172014-02-20 12:21:31 -08003253 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003254 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003255 cryptfs_reboot(shutdown);
3256 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003257 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003258 char value[PROPERTY_VALUE_MAX];
3259
Ken Sumrall319369a2012-06-27 16:30:18 -07003260 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003261 if (!strcmp(value, "1")) {
3262 /* wipe data if encryption failed */
3263 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3264 mkdir("/cache/recovery", 0700);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003265 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003266 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003267 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3268 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003269 close(fd);
3270 } else {
3271 SLOGE("could not open /cache/recovery/command\n");
3272 }
Paul Lawrence87999172014-02-20 12:21:31 -08003273 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003274 } else {
3275 /* set property to trigger dialog */
3276 property_set("vold.encrypt_progress", "error_partially_encrypted");
3277 release_wake_lock(lockid);
3278 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003279 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003280 }
3281
Ken Sumrall3ed82362011-01-28 23:31:16 -08003282 /* hrm, the encrypt step claims success, but the reboot failed.
3283 * This should not happen.
3284 * Set the property and return. Hope the framework can deal with it.
3285 */
3286 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003287 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003288 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003289
3290error_unencrypted:
3291 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003292 if (lockid[0]) {
3293 release_wake_lock(lockid);
3294 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003295 return -1;
3296
3297error_shutting_down:
3298 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3299 * but the framework is stopped and not restarted to show the error, so it's up to
3300 * vold to restart the system.
3301 */
3302 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003303 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003304
3305 /* shouldn't get here */
3306 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003307 if (lockid[0]) {
3308 release_wake_lock(lockid);
3309 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003310 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003311}
3312
Paul Lawrence569649f2015-09-09 12:13:00 -07003313int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003314{
Paul Lawrence569649f2015-09-09 12:13:00 -07003315 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003316}
3317
Paul Lawrence569649f2015-09-09 12:13:00 -07003318int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003319{
3320 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07003321 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003322}
3323
3324int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003325{
Paul Crowley38132a12016-02-09 09:50:32 +00003326 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003327 SLOGE("cryptfs_changepw not valid for file encryption");
3328 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003329 }
3330
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003331 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003332 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003333
3334 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003335 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003336 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003337 return -1;
3338 }
3339
Paul Lawrencef4faa572014-01-29 13:31:03 -08003340 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3341 SLOGE("Invalid crypt_type %d", crypt_type);
3342 return -1;
3343 }
3344
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003345 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003346 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003347 SLOGE("Error getting crypt footer and key");
3348 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003349 }
3350
Paul Lawrencef4faa572014-01-29 13:31:03 -08003351 crypt_ftr.crypt_type = crypt_type;
3352
JP Abgrall933216c2015-02-11 13:44:32 -08003353 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003354 : newpw,
3355 crypt_ftr.salt,
3356 saved_master_key,
3357 crypt_ftr.master_key,
3358 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003359 if (rc) {
3360 SLOGE("Encrypt master key failed: %d", rc);
3361 return -1;
3362 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003363 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003364 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003365
Ajay Dudani87701e22014-09-17 21:02:52 -07003366#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003367 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3368 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3369 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3370 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3371 if (!rc)
3372 return -1;
3373 } else {
3374 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3375 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3376 if (!rc)
3377 return -1;
3378 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003379 }
3380#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003381 return 0;
3382}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003383
Rubin Xu85c01f92014-10-13 12:49:54 +01003384static unsigned int persist_get_max_entries(int encrypted) {
3385 struct crypt_mnt_ftr crypt_ftr;
3386 unsigned int dsize;
3387 unsigned int max_persistent_entries;
3388
3389 /* If encrypted, use the values from the crypt_ftr, otherwise
3390 * use the values for the current spec.
3391 */
3392 if (encrypted) {
3393 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3394 return -1;
3395 }
3396 dsize = crypt_ftr.persist_data_size;
3397 } else {
3398 dsize = CRYPT_PERSIST_DATA_SIZE;
3399 }
3400
3401 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3402 sizeof(struct crypt_persist_entry);
3403
3404 return max_persistent_entries;
3405}
3406
3407static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003408{
3409 unsigned int i;
3410
3411 if (persist_data == NULL) {
3412 return -1;
3413 }
3414 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3415 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3416 /* We found it! */
3417 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3418 return 0;
3419 }
3420 }
3421
3422 return -1;
3423}
3424
Rubin Xu85c01f92014-10-13 12:49:54 +01003425static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003426{
3427 unsigned int i;
3428 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003429 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003430
3431 if (persist_data == NULL) {
3432 return -1;
3433 }
3434
Rubin Xu85c01f92014-10-13 12:49:54 +01003435 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003436
3437 num = persist_data->persist_valid_entries;
3438
3439 for (i = 0; i < num; i++) {
3440 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3441 /* We found an existing entry, update it! */
3442 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3443 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3444 return 0;
3445 }
3446 }
3447
3448 /* We didn't find it, add it to the end, if there is room */
3449 if (persist_data->persist_valid_entries < max_persistent_entries) {
3450 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3451 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3452 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3453 persist_data->persist_valid_entries++;
3454 return 0;
3455 }
3456
3457 return -1;
3458}
3459
Rubin Xu85c01f92014-10-13 12:49:54 +01003460/**
3461 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3462 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3463 */
3464static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003465 unsigned int field_len;
3466 unsigned int key_index;
3467 field_len = strlen(field);
3468
3469 if (index == 0) {
3470 // The first key in a multi-entry field is just the filedname itself.
3471 if (!strcmp(key, field)) {
3472 return 1;
3473 }
3474 }
3475 // Match key against "%s_%d" % (field, index)
3476 if (strlen(key) < field_len + 1 + 1) {
3477 // Need at least a '_' and a digit.
3478 return 0;
3479 }
3480 if (strncmp(key, field, field_len)) {
3481 // If the key does not begin with field, it's not a match.
3482 return 0;
3483 }
3484 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3485 return 0;
3486 }
3487 return key_index >= index;
3488}
3489
3490/*
3491 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3492 * remaining entries starting from index will be deleted.
3493 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3494 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3495 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3496 *
3497 */
3498static int persist_del_keys(const char *fieldname, unsigned index)
3499{
3500 unsigned int i;
3501 unsigned int j;
3502 unsigned int num;
3503
3504 if (persist_data == NULL) {
3505 return PERSIST_DEL_KEY_ERROR_OTHER;
3506 }
3507
3508 num = persist_data->persist_valid_entries;
3509
3510 j = 0; // points to the end of non-deleted entries.
3511 // Filter out to-be-deleted entries in place.
3512 for (i = 0; i < num; i++) {
3513 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3514 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3515 j++;
3516 }
3517 }
3518
3519 if (j < num) {
3520 persist_data->persist_valid_entries = j;
3521 // Zeroise the remaining entries
3522 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3523 return PERSIST_DEL_KEY_OK;
3524 } else {
3525 // Did not find an entry matching the given fieldname
3526 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3527 }
3528}
3529
3530static int persist_count_keys(const char *fieldname)
3531{
3532 unsigned int i;
3533 unsigned int count;
3534
3535 if (persist_data == NULL) {
3536 return -1;
3537 }
3538
3539 count = 0;
3540 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3541 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3542 count++;
3543 }
3544 }
3545
3546 return count;
3547}
3548
Ken Sumrall160b4d62013-04-22 12:15:39 -07003549/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003550int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003551{
Paul Crowley38132a12016-02-09 09:50:32 +00003552 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003553 SLOGE("Cannot get field when file encrypted");
3554 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003555 }
3556
Ken Sumrall160b4d62013-04-22 12:15:39 -07003557 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003558 /* CRYPTO_GETFIELD_OK is success,
3559 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3560 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3561 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003562 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003563 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3564 int i;
3565 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003566
3567 if (persist_data == NULL) {
3568 load_persistent_data();
3569 if (persist_data == NULL) {
3570 SLOGE("Getfield error, cannot load persistent data");
3571 goto out;
3572 }
3573 }
3574
Rubin Xu85c01f92014-10-13 12:49:54 +01003575 // Read value from persistent entries. If the original value is split into multiple entries,
3576 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003577 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003578 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3579 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3580 // value too small
3581 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3582 goto out;
3583 }
3584 rc = CRYPTO_GETFIELD_OK;
3585
3586 for (i = 1; /* break explicitly */; i++) {
3587 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3588 (int) sizeof(temp_field)) {
3589 // If the fieldname is very long, we stop as soon as it begins to overflow the
3590 // maximum field length. At this point we have in fact fully read out the original
3591 // value because cryptfs_setfield would not allow fields with longer names to be
3592 // written in the first place.
3593 break;
3594 }
3595 if (!persist_get_key(temp_field, temp_value)) {
3596 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3597 // value too small.
3598 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3599 goto out;
3600 }
3601 } else {
3602 // Exhaust all entries.
3603 break;
3604 }
3605 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003606 } else {
3607 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003608 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003609 }
3610
3611out:
3612 return rc;
3613}
3614
3615/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003616int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003617{
Paul Crowley38132a12016-02-09 09:50:32 +00003618 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003619 SLOGE("Cannot set field when file encrypted");
3620 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003621 }
3622
Ken Sumrall160b4d62013-04-22 12:15:39 -07003623 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003624 /* 0 is success, negative values are error */
3625 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003626 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003627 unsigned int field_id;
3628 char temp_field[PROPERTY_KEY_MAX];
3629 unsigned int num_entries;
3630 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003631
3632 if (persist_data == NULL) {
3633 load_persistent_data();
3634 if (persist_data == NULL) {
3635 SLOGE("Setfield error, cannot load persistent data");
3636 goto out;
3637 }
3638 }
3639
3640 property_get("ro.crypto.state", encrypted_state, "");
3641 if (!strcmp(encrypted_state, "encrypted") ) {
3642 encrypted = 1;
3643 }
3644
Rubin Xu85c01f92014-10-13 12:49:54 +01003645 // Compute the number of entries required to store value, each entry can store up to
3646 // (PROPERTY_VALUE_MAX - 1) chars
3647 if (strlen(value) == 0) {
3648 // Empty value also needs one entry to store.
3649 num_entries = 1;
3650 } else {
3651 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3652 }
3653
3654 max_keylen = strlen(fieldname);
3655 if (num_entries > 1) {
3656 // Need an extra "_%d" suffix.
3657 max_keylen += 1 + log10(num_entries);
3658 }
3659 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3660 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003661 goto out;
3662 }
3663
Rubin Xu85c01f92014-10-13 12:49:54 +01003664 // Make sure we have enough space to write the new value
3665 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3666 persist_get_max_entries(encrypted)) {
3667 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3668 goto out;
3669 }
3670
3671 // Now that we know persist_data has enough space for value, let's delete the old field first
3672 // to make up space.
3673 persist_del_keys(fieldname, 0);
3674
3675 if (persist_set_key(fieldname, value, encrypted)) {
3676 // fail to set key, should not happen as we have already checked the available space
3677 SLOGE("persist_set_key() error during setfield()");
3678 goto out;
3679 }
3680
3681 for (field_id = 1; field_id < num_entries; field_id++) {
3682 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3683
3684 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3685 // fail to set key, should not happen as we have already checked the available space.
3686 SLOGE("persist_set_key() error during setfield()");
3687 goto out;
3688 }
3689 }
3690
Ken Sumrall160b4d62013-04-22 12:15:39 -07003691 /* If we are running encrypted, save the persistent data now */
3692 if (encrypted) {
3693 if (save_persistent_data()) {
3694 SLOGE("Setfield error, cannot save persistent data");
3695 goto out;
3696 }
3697 }
3698
Rubin Xu85c01f92014-10-13 12:49:54 +01003699 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003700
3701out:
3702 return rc;
3703}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003704
3705/* Checks userdata. Attempt to mount the volume if default-
3706 * encrypted.
3707 * On success trigger next init phase and return 0.
3708 * Currently do not handle failure - see TODO below.
3709 */
3710int cryptfs_mount_default_encrypted(void)
3711{
3712 char decrypt_state[PROPERTY_VALUE_MAX];
3713 property_get("vold.decrypt", decrypt_state, "0");
3714 if (!strcmp(decrypt_state, "0")) {
3715 SLOGE("Not encrypted - should not call here");
3716 } else {
3717 int crypt_type = cryptfs_get_password_type();
3718 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3719 SLOGE("Bad crypt type - error");
3720 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3721 SLOGD("Password is not default - "
3722 "starting min framework to prompt");
3723 property_set("vold.decrypt", "trigger_restart_min_framework");
3724 return 0;
3725 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3726 SLOGD("Password is default - restarting filesystem");
3727 cryptfs_restart_internal(0);
3728 return 0;
3729 } else {
3730 SLOGE("Encrypted, default crypt type but can't decrypt");
3731 }
3732 }
3733
Paul Lawrence6bfed202014-07-28 12:47:22 -07003734 /** Corrupt. Allow us to boot into framework, which will detect bad
3735 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003736 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003737 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003738 return 0;
3739}
3740
3741/* Returns type of the password, default, pattern, pin or password.
3742 */
3743int cryptfs_get_password_type(void)
3744{
Paul Crowley38132a12016-02-09 09:50:32 +00003745 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003746 SLOGE("cryptfs_get_password_type not valid for file encryption");
3747 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003748 }
3749
Paul Lawrencef4faa572014-01-29 13:31:03 -08003750 struct crypt_mnt_ftr crypt_ftr;
3751
3752 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3753 SLOGE("Error getting crypt footer and key\n");
3754 return -1;
3755 }
3756
Paul Lawrence6bfed202014-07-28 12:47:22 -07003757 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3758 return -1;
3759 }
3760
Paul Lawrencef4faa572014-01-29 13:31:03 -08003761 return crypt_ftr.crypt_type;
3762}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003763
Paul Lawrence05335c32015-03-05 09:46:23 -08003764const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003765{
Paul Crowley38132a12016-02-09 09:50:32 +00003766 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003767 SLOGE("cryptfs_get_password not valid for file encryption");
3768 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003769 }
3770
Paul Lawrence399317e2014-03-10 13:20:50 -07003771 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003772 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003773 if (now.tv_sec < password_expiry_time) {
3774 return password;
3775 } else {
3776 cryptfs_clear_password();
3777 return 0;
3778 }
3779}
3780
3781void cryptfs_clear_password()
3782{
3783 if (password) {
3784 size_t len = strlen(password);
3785 memset(password, 0, len);
3786 free(password);
3787 password = 0;
3788 password_expiry_time = 0;
3789 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003790}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003791
3792int cryptfs_enable_file()
3793{
Paul Crowley38132a12016-02-09 09:50:32 +00003794 return e4crypt_initialize_global_de();
Paul Lawrence731a7a22015-04-28 22:14:15 +00003795}
3796
Paul Lawrence0c247462015-10-29 10:30:57 -07003797int cryptfs_isConvertibleToFBE()
3798{
3799 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3800 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
3801}
3802
Paul Lawrence731a7a22015-04-28 22:14:15 +00003803int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3804{
3805 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3806 SLOGE("Failed to initialize crypt_ftr");
3807 return -1;
3808 }
3809
3810 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3811 crypt_ftr->salt, crypt_ftr)) {
3812 SLOGE("Cannot create encrypted master key\n");
3813 return -1;
3814 }
3815
3816 //crypt_ftr->keysize = key_length / 8;
3817 return 0;
3818}
3819
3820int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3821 unsigned char* master_key)
3822{
3823 int rc;
3824
Paul Lawrence731a7a22015-04-28 22:14:15 +00003825 unsigned char* intermediate_key = 0;
3826 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003827
3828 if (password == 0 || *password == 0) {
3829 password = DEFAULT_PASSWORD;
3830 }
3831
Paul Lawrence731a7a22015-04-28 22:14:15 +00003832 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3833 &intermediate_key_size);
3834
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003835 int N = 1 << ftr->N_factor;
3836 int r = 1 << ftr->r_factor;
3837 int p = 1 << ftr->p_factor;
3838
3839 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3840
3841 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3842 ftr->salt, sizeof(ftr->salt), N, r, p,
3843 scrypted_intermediate_key,
3844 sizeof(scrypted_intermediate_key));
3845
3846 free(intermediate_key);
3847
3848 if (rc) {
3849 SLOGE("Can't calculate intermediate key");
3850 return rc;
3851 }
3852
3853 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3854 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00003855}
3856
3857int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3858 const unsigned char* master_key)
3859{
3860 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3861 ftr);
3862}