blob: 65acb603e17af2058b3baebef44e151d54fba59d [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080041#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080046#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080047#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080048#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080049#define LOG_TAG "Cryptfs"
50#include "cutils/log.h"
51#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070052#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080053#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070054#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070055#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070056#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070057#include "crypto_scrypt.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000058#include "Ext4Crypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080059#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000060#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080061#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080062#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080063
Shawn Willden8af33352015-02-24 09:51:34 -070064#include <hardware/keymaster0.h>
Shawn Willdenda6e8992015-06-03 09:40:45 -060065#include <hardware/keymaster1.h>
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070066
Mark Salyzyn3e971272014-01-21 13:27:04 -080067#define UNUSED __attribute__((unused))
68
Mark Salyzyn5eecc442014-02-12 14:16:14 -080069#define UNUSED __attribute__((unused))
70
Ajay Dudani87701e22014-09-17 21:02:52 -070071#ifdef CONFIG_HW_DISK_ENCRYPTION
72#include "cryptfs_hw.h"
73#endif
74
Ken Sumrall8f869aa2010-12-03 03:47:09 -080075#define DM_CRYPT_BUF_SIZE 4096
76
Jason parks70a4b3f2011-01-28 10:10:47 -060077#define HASH_COUNT 2000
78#define KEY_LEN_BYTES 16
79#define IV_LEN_BYTES 16
80
Ken Sumrall29d8da82011-05-18 17:20:07 -070081#define KEY_IN_FOOTER "footer"
82
Paul Lawrence3bd36d52015-06-09 13:37:44 -070083#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080084
Paul Lawrence3d99eba2015-11-20 07:07:19 -080085#define CRYPTO_BLOCK_DEVICE "userdata"
86
87#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
88
Ken Sumrall29d8da82011-05-18 17:20:07 -070089#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070090#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070091
Ken Sumralle919efe2012-09-29 17:07:41 -070092#define TABLE_LOAD_RETRIES 10
93
Shawn Willden47ba10d2014-09-03 17:07:06 -060094#define RSA_KEY_SIZE 2048
95#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
96#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060097#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070098
Paul Lawrence8e3f4512014-09-08 10:11:17 -070099#define RETRY_MOUNT_ATTEMPTS 10
100#define RETRY_MOUNT_DELAY_SECONDS 1
101
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800102char *me = "cryptfs";
103
Jason parks70a4b3f2011-01-28 10:10:47 -0600104static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700105static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600106static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700107static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800108
Shawn Willdenda6e8992015-06-03 09:40:45 -0600109static int keymaster_init(keymaster0_device_t **keymaster0_dev,
110 keymaster1_device_t **keymaster1_dev)
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700111{
112 int rc;
113
114 const hw_module_t* mod;
115 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
116 if (rc) {
117 ALOGE("could not find any keystore module");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600118 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700119 }
120
Shawn Willdenda6e8992015-06-03 09:40:45 -0600121 SLOGI("keymaster module name is %s", mod->name);
122 SLOGI("keymaster version is %d", mod->module_api_version);
123
124 *keymaster0_dev = NULL;
125 *keymaster1_dev = NULL;
126 if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
127 SLOGI("Found keymaster1 module, using keymaster1 API.");
128 rc = keymaster1_open(mod, keymaster1_dev);
129 } else {
130 SLOGI("Found keymaster0 module, using keymaster0 API.");
131 rc = keymaster0_open(mod, keymaster0_dev);
132 }
133
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700134 if (rc) {
135 ALOGE("could not open keymaster device in %s (%s)",
Shawn Willdenda6e8992015-06-03 09:40:45 -0600136 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
137 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700138 }
139
140 return 0;
141
Shawn Willdenda6e8992015-06-03 09:40:45 -0600142err:
143 *keymaster0_dev = NULL;
144 *keymaster1_dev = NULL;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700145 return rc;
146}
147
148/* Should we use keymaster? */
149static int keymaster_check_compatibility()
150{
Shawn Willdenda6e8992015-06-03 09:40:45 -0600151 keymaster0_device_t *keymaster0_dev = 0;
152 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700153 int rc = 0;
154
Shawn Willdenda6e8992015-06-03 09:40:45 -0600155 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700156 SLOGE("Failed to init keymaster");
157 rc = -1;
158 goto out;
159 }
160
Shawn Willdenda6e8992015-06-03 09:40:45 -0600161 if (keymaster1_dev) {
162 rc = 1;
163 goto out;
164 }
Paul Lawrence8c008392014-05-06 14:02:48 -0700165
Shawn Willdenda6e8992015-06-03 09:40:45 -0600166 // TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
167 // should work.
168 if (keymaster0_dev->common.module->module_api_version
Paul Lawrence8c008392014-05-06 14:02:48 -0700169 < KEYMASTER_MODULE_API_VERSION_0_3) {
170 rc = 0;
171 goto out;
172 }
173
Shawn Willdenda6e8992015-06-03 09:40:45 -0600174 if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
175 (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700176 rc = 1;
177 }
178
179out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600180 if (keymaster1_dev) {
181 keymaster1_close(keymaster1_dev);
182 }
183 if (keymaster0_dev) {
184 keymaster0_close(keymaster0_dev);
185 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700186 return rc;
187}
188
189/* Create a new keymaster key and store it in this footer */
190static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
191{
192 uint8_t* key = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600193 keymaster0_device_t *keymaster0_dev = 0;
194 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700195
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800196 if (ftr->keymaster_blob_size) {
197 SLOGI("Already have key");
198 return 0;
199 }
200
Shawn Willdenda6e8992015-06-03 09:40:45 -0600201 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700202 SLOGE("Failed to init keymaster");
203 return -1;
204 }
205
206 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600207 size_t key_size = 0;
208 if (keymaster1_dev) {
209 keymaster_key_param_t params[] = {
210 /* Algorithm & size specifications. Stick with RSA for now. Switch to AES later. */
211 keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
212 keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
213 keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700214
Shawn Willden86af3552015-06-24 07:21:54 -0700215 /* The only allowed purpose for this key is signing. */
216 keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
217
218 /* Padding & digest specifications. */
Shawn Willdenda6e8992015-06-03 09:40:45 -0600219 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
Shawn Willdenda6e8992015-06-03 09:40:45 -0600220 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700221
Shawn Willdenda6e8992015-06-03 09:40:45 -0600222 /* Require that the key be usable in standalone mode. File system isn't available. */
223 keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
224
225 /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
226 keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
227
Shawn Willdenda6e8992015-06-03 09:40:45 -0600228 /* Rate-limit key usage attempts, to rate-limit brute force */
229 keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
230 };
231 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
232 keymaster_key_blob_t key_blob;
233 keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, &param_set,
234 &key_blob,
235 NULL /* characteristics */);
236 if (error != KM_ERROR_OK) {
237 SLOGE("Failed to generate keymaster1 key, error %d", error);
238 rc = -1;
239 goto out;
240 }
241
242 key = (uint8_t*)key_blob.key_material;
243 key_size = key_blob.key_material_size;
244 }
245 else if (keymaster0_dev) {
246 keymaster_rsa_keygen_params_t params;
247 memset(&params, '\0', sizeof(params));
248 params.public_exponent = RSA_EXPONENT;
249 params.modulus_size = RSA_KEY_SIZE;
250
251 if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, &params,
252 &key, &key_size)) {
253 SLOGE("Failed to generate keypair");
254 rc = -1;
255 goto out;
256 }
257 } else {
258 SLOGE("Cryptfs bug: keymaster_init succeeded but didn't initialize a device");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700259 rc = -1;
260 goto out;
261 }
262
263 if (key_size > KEYMASTER_BLOB_SIZE) {
264 SLOGE("Keymaster key too large for crypto footer");
265 rc = -1;
266 goto out;
267 }
268
269 memcpy(ftr->keymaster_blob, key, key_size);
270 ftr->keymaster_blob_size = key_size;
271
272out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600273 if (keymaster0_dev)
274 keymaster0_close(keymaster0_dev);
275 if (keymaster1_dev)
276 keymaster1_close(keymaster1_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700277 free(key);
278 return rc;
279}
280
Shawn Willdene17a9c42014-09-08 13:04:08 -0600281/* This signs the given object using the keymaster key. */
282static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600283 const unsigned char *object,
284 const size_t object_size,
285 unsigned char **signature,
286 size_t *signature_size)
287{
288 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600289 keymaster0_device_t *keymaster0_dev = 0;
290 keymaster1_device_t *keymaster1_dev = 0;
291 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600292 SLOGE("Failed to init keymaster");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600293 rc = -1;
294 goto out;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600295 }
296
Shawn Willden47ba10d2014-09-03 17:07:06 -0600297 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600298 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600299 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600300
Shawn Willdene17a9c42014-09-08 13:04:08 -0600301 // To sign a message with RSA, the message must satisfy two
302 // constraints:
303 //
304 // 1. The message, when interpreted as a big-endian numeric value, must
305 // be strictly less than the public modulus of the RSA key. Note
306 // that because the most significant bit of the public modulus is
307 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
308 // key), an n-bit message with most significant bit 0 always
309 // satisfies this requirement.
310 //
311 // 2. The message must have the same length in bits as the public
312 // modulus of the RSA key. This requirement isn't mathematically
313 // necessary, but is necessary to ensure consistency in
314 // implementations.
315 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600316 case KDF_SCRYPT_KEYMASTER:
317 // This ensures the most significant byte of the signed message
318 // is zero. We could have zero-padded to the left instead, but
319 // this approach is slightly more robust against changes in
320 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600321 // so) because we really should be using a proper deterministic
322 // RSA padding function, such as PKCS1.
Shawn Willdene17a9c42014-09-08 13:04:08 -0600323 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
324 SLOGI("Signing safely-padded object");
325 break;
326 default:
327 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Shawn Willdenda6e8992015-06-03 09:40:45 -0600328 rc = -1;
329 goto out;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600330 }
331
Shawn Willdenda6e8992015-06-03 09:40:45 -0600332 if (keymaster0_dev) {
333 keymaster_rsa_sign_params_t params;
334 params.digest_type = DIGEST_NONE;
335 params.padding_type = PADDING_NONE;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600336
Shawn Willdenda6e8992015-06-03 09:40:45 -0600337 rc = keymaster0_dev->sign_data(keymaster0_dev,
338 &params,
339 ftr->keymaster_blob,
340 ftr->keymaster_blob_size,
341 to_sign,
342 to_sign_size,
343 signature,
344 signature_size);
345 goto out;
346 } else if (keymaster1_dev) {
347 keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
348 keymaster_key_param_t params[] = {
349 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
350 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
351 };
352 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
353 keymaster_operation_handle_t op_handle;
354 keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
355 &param_set, NULL /* out_params */,
356 &op_handle);
Shawn Willden04170602015-06-18 12:26:59 -0600357 if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
Shawn Willdenda6e8992015-06-03 09:40:45 -0600358 // Key usage has been rate-limited. Wait a bit and try again.
359 sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
360 error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
361 &param_set, NULL /* out_params */,
362 &op_handle);
363 }
364 if (error != KM_ERROR_OK) {
365 SLOGE("Error starting keymaster signature transaction: %d", error);
366 rc = -1;
367 goto out;
368 }
369
370 keymaster_blob_t input = { to_sign, to_sign_size };
371 size_t input_consumed;
372 error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
373 &input, &input_consumed, NULL /* out_params */,
374 NULL /* output */);
375 if (error != KM_ERROR_OK) {
376 SLOGE("Error sending data to keymaster signature transaction: %d", error);
377 rc = -1;
378 goto out;
379 }
380 if (input_consumed != to_sign_size) {
381 // This should never happen. If it does, it's a bug in the keymaster implementation.
382 SLOGE("Keymaster update() did not consume all data.");
383 keymaster1_dev->abort(keymaster1_dev, op_handle);
384 rc = -1;
385 goto out;
386 }
387
388 keymaster_blob_t tmp_sig;
389 error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
390 NULL /* verify signature */, NULL /* out_params */,
391 &tmp_sig);
392 if (error != KM_ERROR_OK) {
393 SLOGE("Error finishing keymaster signature transaction: %d", error);
394 rc = -1;
395 goto out;
396 }
397
398 *signature = (uint8_t*)tmp_sig.data;
399 *signature_size = tmp_sig.data_length;
400 } else {
401 SLOGE("Cryptfs bug: keymaster_init succeded but didn't initialize a device.");
402 rc = -1;
403 goto out;
404 }
405
406 out:
407 if (keymaster1_dev)
408 keymaster1_close(keymaster1_dev);
409 if (keymaster0_dev)
410 keymaster0_close(keymaster0_dev);
411
412 return rc;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600413}
414
Paul Lawrence399317e2014-03-10 13:20:50 -0700415/* Store password when userdata is successfully decrypted and mounted.
416 * Cleared by cryptfs_clear_password
417 *
418 * To avoid a double prompt at boot, we need to store the CryptKeeper
419 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
420 * Since the entire framework is torn down and rebuilt after encryption,
421 * we have to use a daemon or similar to store the password. Since vold
422 * is secured against IPC except from system processes, it seems a reasonable
423 * place to store this.
424 *
425 * password should be cleared once it has been used.
426 *
427 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800428 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700429static char* password = 0;
430static int password_expiry_time = 0;
431static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800432
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800433extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800434
Paul Lawrence87999172014-02-20 12:21:31 -0800435enum RebootType {reboot, recovery, shutdown};
436static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700437{
Paul Lawrence87999172014-02-20 12:21:31 -0800438 switch(rt) {
439 case reboot:
440 property_set(ANDROID_RB_PROPERTY, "reboot");
441 break;
442
443 case recovery:
444 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
445 break;
446
447 case shutdown:
448 property_set(ANDROID_RB_PROPERTY, "shutdown");
449 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700450 }
Paul Lawrence87999172014-02-20 12:21:31 -0800451
Ken Sumralladfba362013-06-04 16:37:52 -0700452 sleep(20);
453
454 /* Shouldn't get here, reboot should happen before sleep times out */
455 return;
456}
457
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800458static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
459{
460 memset(io, 0, dataSize);
461 io->data_size = dataSize;
462 io->data_start = sizeof(struct dm_ioctl);
463 io->version[0] = 4;
464 io->version[1] = 0;
465 io->version[2] = 0;
466 io->flags = flags;
467 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100468 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800469 }
470}
471
Kenny Rootc4c70f12013-06-14 12:11:38 -0700472/**
473 * Gets the default device scrypt parameters for key derivation time tuning.
474 * The parameters should lead to about one second derivation time for the
475 * given device.
476 */
477static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
478 const int default_params[] = SCRYPT_DEFAULTS;
479 int params[] = SCRYPT_DEFAULTS;
480 char paramstr[PROPERTY_VALUE_MAX];
481 char *token;
482 char *saveptr;
483 int i;
484
485 property_get(SCRYPT_PROP, paramstr, "");
486 if (paramstr[0] != '\0') {
487 /*
488 * The token we're looking for should be three integers separated by
489 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
490 */
Kenny Root2947e342013-08-14 15:54:49 -0700491 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
492 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700493 i++, token = strtok_r(NULL, ":", &saveptr)) {
494 char *endptr;
495 params[i] = strtol(token, &endptr, 10);
496
497 /*
498 * Check that there was a valid number and it's 8-bit. If not,
499 * break out and the end check will take the default values.
500 */
501 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
502 break;
503 }
504 }
505
506 /*
507 * If there were not enough tokens or a token was malformed (not an
508 * integer), it will end up here and the default parameters can be
509 * taken.
510 */
511 if ((i != 3) || (token != NULL)) {
512 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
513 memcpy(params, default_params, sizeof(params));
514 }
515 }
516
517 ftr->N_factor = params[0];
518 ftr->r_factor = params[1];
519 ftr->p_factor = params[2];
520}
521
Ken Sumrall3ed82362011-01-28 23:31:16 -0800522static unsigned int get_fs_size(char *dev)
523{
524 int fd, block_size;
525 struct ext4_super_block sb;
526 off64_t len;
527
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700528 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800529 SLOGE("Cannot open device to get filesystem size ");
530 return 0;
531 }
532
533 if (lseek64(fd, 1024, SEEK_SET) < 0) {
534 SLOGE("Cannot seek to superblock");
535 return 0;
536 }
537
538 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
539 SLOGE("Cannot read superblock");
540 return 0;
541 }
542
543 close(fd);
544
Daniel Rosenberge82df162014-08-15 22:19:23 +0000545 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
546 SLOGE("Not a valid ext4 superblock");
547 return 0;
548 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800549 block_size = 1024 << sb.s_log_block_size;
550 /* compute length in bytes */
551 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
552
553 /* return length in sectors */
554 return (unsigned int) (len / 512);
555}
556
Ken Sumrall160b4d62013-04-22 12:15:39 -0700557static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
558{
559 static int cached_data = 0;
560 static off64_t cached_off = 0;
561 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
562 int fd;
563 char key_loc[PROPERTY_VALUE_MAX];
564 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700565 int rc = -1;
566
567 if (!cached_data) {
568 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
569
570 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700571 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700572 SLOGE("Cannot open real block device %s\n", real_blkdev);
573 return -1;
574 }
575
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900576 unsigned long nr_sec = 0;
577 get_blkdev_size(fd, &nr_sec);
578 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700579 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
580 * encryption info footer and key, and plenty of bytes to spare for future
581 * growth.
582 */
583 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
584 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
585 cached_data = 1;
586 } else {
587 SLOGE("Cannot get size of block device %s\n", real_blkdev);
588 }
589 close(fd);
590 } else {
591 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
592 cached_off = 0;
593 cached_data = 1;
594 }
595 }
596
597 if (cached_data) {
598 if (metadata_fname) {
599 *metadata_fname = cached_metadata_fname;
600 }
601 if (off) {
602 *off = cached_off;
603 }
604 rc = 0;
605 }
606
607 return rc;
608}
609
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800610/* Set sha256 checksum in structure */
611static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
612{
613 SHA256_CTX c;
614 SHA256_Init(&c);
615 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
616 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
617 SHA256_Final(crypt_ftr->sha256, &c);
618}
619
Ken Sumralle8744072011-01-18 22:01:55 -0800620/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800621 * update the failed mount count but not change the key.
622 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700623static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800624{
625 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800626 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700627 /* starting_off is set to the SEEK_SET offset
628 * where the crypto structure starts
629 */
630 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800631 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700632 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700633 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800634
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800635 set_ftr_sha(crypt_ftr);
636
Ken Sumrall160b4d62013-04-22 12:15:39 -0700637 if (get_crypt_ftr_info(&fname, &starting_off)) {
638 SLOGE("Unable to get crypt_ftr_info\n");
639 return -1;
640 }
641 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700642 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700643 return -1;
644 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700645 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700646 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700647 return -1;
648 }
649
650 /* Seek to the start of the crypt footer */
651 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
652 SLOGE("Cannot seek to real block device footer\n");
653 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800654 }
655
656 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
657 SLOGE("Cannot write real block device footer\n");
658 goto errout;
659 }
660
Ken Sumrall3be890f2011-09-14 16:53:46 -0700661 fstat(fd, &statbuf);
662 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700663 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700664 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800665 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800666 goto errout;
667 }
668 }
669
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800670 /* Success! */
671 rc = 0;
672
673errout:
674 close(fd);
675 return rc;
676
677}
678
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800679static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
680{
681 struct crypt_mnt_ftr copy;
682 memcpy(&copy, crypt_ftr, sizeof(copy));
683 set_ftr_sha(&copy);
684 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
685}
686
Ken Sumrall160b4d62013-04-22 12:15:39 -0700687static inline int unix_read(int fd, void* buff, int len)
688{
689 return TEMP_FAILURE_RETRY(read(fd, buff, len));
690}
691
692static inline int unix_write(int fd, const void* buff, int len)
693{
694 return TEMP_FAILURE_RETRY(write(fd, buff, len));
695}
696
697static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
698{
699 memset(pdata, 0, len);
700 pdata->persist_magic = PERSIST_DATA_MAGIC;
701 pdata->persist_valid_entries = 0;
702}
703
704/* A routine to update the passed in crypt_ftr to the lastest version.
705 * fd is open read/write on the device that holds the crypto footer and persistent
706 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
707 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
708 */
709static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
710{
Kenny Root7434b312013-06-14 11:29:53 -0700711 int orig_major = crypt_ftr->major_version;
712 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700713
Kenny Root7434b312013-06-14 11:29:53 -0700714 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
715 struct crypt_persist_data *pdata;
716 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700717
Kenny Rootc4c70f12013-06-14 12:11:38 -0700718 SLOGW("upgrading crypto footer to 1.1");
719
Kenny Root7434b312013-06-14 11:29:53 -0700720 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
721 if (pdata == NULL) {
722 SLOGE("Cannot allocate persisent data\n");
723 return;
724 }
725 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
726
727 /* Need to initialize the persistent data area */
728 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
729 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100730 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700731 return;
732 }
733 /* Write all zeros to the first copy, making it invalid */
734 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
735
736 /* Write a valid but empty structure to the second copy */
737 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
738 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
739
740 /* Update the footer */
741 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
742 crypt_ftr->persist_data_offset[0] = pdata_offset;
743 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
744 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100745 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700746 }
747
Paul Lawrencef4faa572014-01-29 13:31:03 -0800748 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700749 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800750 /* But keep the old kdf_type.
751 * It will get updated later to KDF_SCRYPT after the password has been verified.
752 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700753 crypt_ftr->kdf_type = KDF_PBKDF2;
754 get_device_scrypt_params(crypt_ftr);
755 crypt_ftr->minor_version = 2;
756 }
757
Paul Lawrencef4faa572014-01-29 13:31:03 -0800758 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
759 SLOGW("upgrading crypto footer to 1.3");
760 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
761 crypt_ftr->minor_version = 3;
762 }
763
Kenny Root7434b312013-06-14 11:29:53 -0700764 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
765 if (lseek64(fd, offset, SEEK_SET) == -1) {
766 SLOGE("Cannot seek to crypt footer\n");
767 return;
768 }
769 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700770 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700771}
772
773
774static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800775{
776 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800777 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700778 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800779 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700780 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700781 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800782
Ken Sumrall160b4d62013-04-22 12:15:39 -0700783 if (get_crypt_ftr_info(&fname, &starting_off)) {
784 SLOGE("Unable to get crypt_ftr_info\n");
785 return -1;
786 }
787 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700788 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700789 return -1;
790 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700791 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700792 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700793 return -1;
794 }
795
796 /* Make sure it's 16 Kbytes in length */
797 fstat(fd, &statbuf);
798 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
799 SLOGE("footer file %s is not the expected size!\n", fname);
800 goto errout;
801 }
802
803 /* Seek to the start of the crypt footer */
804 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
805 SLOGE("Cannot seek to real block device footer\n");
806 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800807 }
808
809 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
810 SLOGE("Cannot read real block device footer\n");
811 goto errout;
812 }
813
814 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700815 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800816 goto errout;
817 }
818
Kenny Rootc96a5f82013-06-14 12:08:28 -0700819 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
820 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
821 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800822 goto errout;
823 }
824
Kenny Rootc96a5f82013-06-14 12:08:28 -0700825 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
826 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
827 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800828 }
829
Ken Sumrall160b4d62013-04-22 12:15:39 -0700830 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
831 * copy on disk before returning.
832 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700833 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700834 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800835 }
836
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800837 /* Success! */
838 rc = 0;
839
840errout:
841 close(fd);
842 return rc;
843}
844
Ken Sumrall160b4d62013-04-22 12:15:39 -0700845static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
846{
847 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
848 crypt_ftr->persist_data_offset[1]) {
849 SLOGE("Crypt_ftr persist data regions overlap");
850 return -1;
851 }
852
853 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
854 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
855 return -1;
856 }
857
858 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
859 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
860 CRYPT_FOOTER_OFFSET) {
861 SLOGE("Persistent data extends past crypto footer");
862 return -1;
863 }
864
865 return 0;
866}
867
868static int load_persistent_data(void)
869{
870 struct crypt_mnt_ftr crypt_ftr;
871 struct crypt_persist_data *pdata = NULL;
872 char encrypted_state[PROPERTY_VALUE_MAX];
873 char *fname;
874 int found = 0;
875 int fd;
876 int ret;
877 int i;
878
879 if (persist_data) {
880 /* Nothing to do, we've already loaded or initialized it */
881 return 0;
882 }
883
884
885 /* If not encrypted, just allocate an empty table and initialize it */
886 property_get("ro.crypto.state", encrypted_state, "");
887 if (strcmp(encrypted_state, "encrypted") ) {
888 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
889 if (pdata) {
890 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
891 persist_data = pdata;
892 return 0;
893 }
894 return -1;
895 }
896
897 if(get_crypt_ftr_and_key(&crypt_ftr)) {
898 return -1;
899 }
900
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700901 if ((crypt_ftr.major_version < 1)
902 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700903 SLOGE("Crypt_ftr version doesn't support persistent data");
904 return -1;
905 }
906
907 if (get_crypt_ftr_info(&fname, NULL)) {
908 return -1;
909 }
910
911 ret = validate_persistent_data_storage(&crypt_ftr);
912 if (ret) {
913 return -1;
914 }
915
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700916 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700917 if (fd < 0) {
918 SLOGE("Cannot open %s metadata file", fname);
919 return -1;
920 }
921
922 if (persist_data == NULL) {
923 pdata = malloc(crypt_ftr.persist_data_size);
924 if (pdata == NULL) {
925 SLOGE("Cannot allocate memory for persistent data");
926 goto err;
927 }
928 }
929
930 for (i = 0; i < 2; i++) {
931 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
932 SLOGE("Cannot seek to read persistent data on %s", fname);
933 goto err2;
934 }
935 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
936 SLOGE("Error reading persistent data on iteration %d", i);
937 goto err2;
938 }
939 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
940 found = 1;
941 break;
942 }
943 }
944
945 if (!found) {
946 SLOGI("Could not find valid persistent data, creating");
947 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
948 }
949
950 /* Success */
951 persist_data = pdata;
952 close(fd);
953 return 0;
954
955err2:
956 free(pdata);
957
958err:
959 close(fd);
960 return -1;
961}
962
963static int save_persistent_data(void)
964{
965 struct crypt_mnt_ftr crypt_ftr;
966 struct crypt_persist_data *pdata;
967 char *fname;
968 off64_t write_offset;
969 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700970 int fd;
971 int ret;
972
973 if (persist_data == NULL) {
974 SLOGE("No persistent data to save");
975 return -1;
976 }
977
978 if(get_crypt_ftr_and_key(&crypt_ftr)) {
979 return -1;
980 }
981
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700982 if ((crypt_ftr.major_version < 1)
983 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700984 SLOGE("Crypt_ftr version doesn't support persistent data");
985 return -1;
986 }
987
988 ret = validate_persistent_data_storage(&crypt_ftr);
989 if (ret) {
990 return -1;
991 }
992
993 if (get_crypt_ftr_info(&fname, NULL)) {
994 return -1;
995 }
996
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700997 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700998 if (fd < 0) {
999 SLOGE("Cannot open %s metadata file", fname);
1000 return -1;
1001 }
1002
1003 pdata = malloc(crypt_ftr.persist_data_size);
1004 if (pdata == NULL) {
1005 SLOGE("Cannot allocate persistant data");
1006 goto err;
1007 }
1008
1009 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1010 SLOGE("Cannot seek to read persistent data on %s", fname);
1011 goto err2;
1012 }
1013
1014 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
1015 SLOGE("Error reading persistent data before save");
1016 goto err2;
1017 }
1018
1019 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1020 /* The first copy is the curent valid copy, so write to
1021 * the second copy and erase this one */
1022 write_offset = crypt_ftr.persist_data_offset[1];
1023 erase_offset = crypt_ftr.persist_data_offset[0];
1024 } else {
1025 /* The second copy must be the valid copy, so write to
1026 * the first copy, and erase the second */
1027 write_offset = crypt_ftr.persist_data_offset[0];
1028 erase_offset = crypt_ftr.persist_data_offset[1];
1029 }
1030
1031 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001032 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001033 SLOGE("Cannot seek to write persistent data");
1034 goto err2;
1035 }
1036 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1037 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001038 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001039 SLOGE("Cannot seek to erase previous persistent data");
1040 goto err2;
1041 }
1042 fsync(fd);
1043 memset(pdata, 0, crypt_ftr.persist_data_size);
1044 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
1045 (int) crypt_ftr.persist_data_size) {
1046 SLOGE("Cannot write to erase previous persistent data");
1047 goto err2;
1048 }
1049 fsync(fd);
1050 } else {
1051 SLOGE("Cannot write to save persistent data");
1052 goto err2;
1053 }
1054
1055 /* Success */
1056 free(pdata);
1057 close(fd);
1058 return 0;
1059
1060err2:
1061 free(pdata);
1062err:
1063 close(fd);
1064 return -1;
1065}
1066
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001067/* Convert a binary key of specified length into an ascii hex string equivalent,
1068 * without the leading 0x and with null termination
1069 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001070static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001071 unsigned int keysize, char *master_key_ascii) {
1072 unsigned int i, a;
1073 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001074
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001075 for (i=0, a=0; i<keysize; i++, a+=2) {
1076 /* For each byte, write out two ascii hex digits */
1077 nibble = (master_key[i] >> 4) & 0xf;
1078 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001079
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001080 nibble = master_key[i] & 0xf;
1081 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1082 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001083
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001084 /* Add the null termination */
1085 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001086
1087}
1088
Jeff Sharkey9c484982015-03-31 10:35:33 -07001089static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
1090 const unsigned char *master_key, const char *real_blk_name,
1091 const char *name, int fd, const char *extra_params) {
Dan Albertc07fa3f2014-12-18 10:00:55 -08001092 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001093 struct dm_ioctl *io;
1094 struct dm_target_spec *tgt;
1095 char *crypt_params;
1096 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1097 int i;
1098
1099 io = (struct dm_ioctl *) buffer;
1100
1101 /* Load the mapping table for this device */
1102 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1103
1104 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1105 io->target_count = 1;
1106 tgt->status = 0;
1107 tgt->sector_start = 0;
1108 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -07001109#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001110 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1111 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1112 }
1113 else {
1114 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1115 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001116#else
1117 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1118#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001119
1120 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1121 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1122 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1123 master_key_ascii, real_blk_name, extra_params);
1124 crypt_params += strlen(crypt_params) + 1;
1125 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1126 tgt->next = crypt_params - buffer;
1127
1128 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1129 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1130 break;
1131 }
1132 usleep(500000);
1133 }
1134
1135 if (i == TABLE_LOAD_RETRIES) {
1136 /* We failed to load the table, return an error */
1137 return -1;
1138 } else {
1139 return i + 1;
1140 }
1141}
1142
1143
1144static int get_dm_crypt_version(int fd, const char *name, int *version)
1145{
1146 char buffer[DM_CRYPT_BUF_SIZE];
1147 struct dm_ioctl *io;
1148 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001149
1150 io = (struct dm_ioctl *) buffer;
1151
1152 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1153
1154 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1155 return -1;
1156 }
1157
1158 /* Iterate over the returned versions, looking for name of "crypt".
1159 * When found, get and return the version.
1160 */
1161 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1162 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001163#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001164 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001165#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001166 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001167#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001168 /* We found the crypt driver, return the version, and get out */
1169 version[0] = v->version[0];
1170 version[1] = v->version[1];
1171 version[2] = v->version[2];
1172 return 0;
1173 }
1174 v = (struct dm_target_versions *)(((char *)v) + v->next);
1175 }
1176
1177 return -1;
1178}
1179
Jeff Sharkey9c484982015-03-31 10:35:33 -07001180static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
1181 const unsigned char *master_key, const char *real_blk_name,
1182 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001183 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001184 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001185 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001186 int fd=0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001187 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001188 int version[3];
1189 char *extra_params;
1190 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001191
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001192 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001193 SLOGE("Cannot open device-mapper\n");
1194 goto errout;
1195 }
1196
1197 io = (struct dm_ioctl *) buffer;
1198
1199 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1200 if (ioctl(fd, DM_DEV_CREATE, io)) {
1201 SLOGE("Cannot create dm-crypt device\n");
1202 goto errout;
1203 }
1204
1205 /* Get the device status, in particular, the name of it's device file */
1206 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1207 if (ioctl(fd, DM_DEV_STATUS, io)) {
1208 SLOGE("Cannot retrieve dm-crypt device status\n");
1209 goto errout;
1210 }
1211 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1212 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1213
Ken Sumralldb5e0262013-02-05 17:39:48 -08001214 extra_params = "";
1215 if (! get_dm_crypt_version(fd, name, version)) {
1216 /* Support for allow_discards was added in version 1.11.0 */
1217 if ((version[0] >= 2) ||
1218 ((version[0] == 1) && (version[1] >= 11))) {
1219 extra_params = "1 allow_discards";
1220 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1221 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001222 }
1223
Ken Sumralldb5e0262013-02-05 17:39:48 -08001224 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1225 fd, extra_params);
1226 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001227 SLOGE("Cannot load dm-crypt mapping table.\n");
1228 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001229 } else if (load_count > 1) {
1230 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001231 }
1232
1233 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001234 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001235
1236 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1237 SLOGE("Cannot resume the dm-crypt device\n");
1238 goto errout;
1239 }
1240
1241 /* We made it here with no errors. Woot! */
1242 retval = 0;
1243
1244errout:
1245 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1246
1247 return retval;
1248}
1249
Ken Sumrall29d8da82011-05-18 17:20:07 -07001250static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251{
1252 int fd;
1253 char buffer[DM_CRYPT_BUF_SIZE];
1254 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001255 int retval = -1;
1256
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001257 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001258 SLOGE("Cannot open device-mapper\n");
1259 goto errout;
1260 }
1261
1262 io = (struct dm_ioctl *) buffer;
1263
1264 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1265 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1266 SLOGE("Cannot remove dm-crypt device\n");
1267 goto errout;
1268 }
1269
1270 /* We made it here with no errors. Woot! */
1271 retval = 0;
1272
1273errout:
1274 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1275
1276 return retval;
1277
1278}
1279
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001280static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001281 unsigned char *ikey, void *params UNUSED)
1282{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001283 SLOGI("Using pbkdf2 for cryptfs KDF");
1284
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001285 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001286 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1287 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1288 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001289}
1290
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001291static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001292 unsigned char *ikey, void *params)
1293{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001294 SLOGI("Using scrypt for cryptfs KDF");
1295
Kenny Rootc4c70f12013-06-14 12:11:38 -07001296 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1297
1298 int N = 1 << ftr->N_factor;
1299 int r = 1 << ftr->r_factor;
1300 int p = 1 << ftr->p_factor;
1301
1302 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001303 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001304 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1305 salt, SALT_LEN, N, r, p, ikey,
1306 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001307
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001308 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001309}
1310
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001311static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1312 unsigned char *ikey, void *params)
1313{
1314 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1315
1316 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001317 size_t signature_size;
1318 unsigned char* signature;
1319 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1320
1321 int N = 1 << ftr->N_factor;
1322 int r = 1 << ftr->r_factor;
1323 int p = 1 << ftr->p_factor;
1324
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001325 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1326 salt, SALT_LEN, N, r, p, ikey,
1327 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001328
1329 if (rc) {
1330 SLOGE("scrypt failed");
1331 return -1;
1332 }
1333
Shawn Willdene17a9c42014-09-08 13:04:08 -06001334 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1335 &signature, &signature_size)) {
1336 SLOGE("Signing failed");
1337 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001338 }
1339
1340 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1341 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1342 free(signature);
1343
1344 if (rc) {
1345 SLOGE("scrypt failed");
1346 return -1;
1347 }
1348
1349 return 0;
1350}
1351
1352static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1353 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001354 unsigned char *encrypted_master_key,
1355 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001356{
1357 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1358 EVP_CIPHER_CTX e_ctx;
1359 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001360 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001361
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001362 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001363 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001364
1365 switch (crypt_ftr->kdf_type) {
1366 case KDF_SCRYPT_KEYMASTER:
1367 if (keymaster_create_key(crypt_ftr)) {
1368 SLOGE("keymaster_create_key failed");
1369 return -1;
1370 }
1371
1372 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1373 SLOGE("scrypt failed");
1374 return -1;
1375 }
1376 break;
1377
1378 case KDF_SCRYPT:
1379 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1380 SLOGE("scrypt failed");
1381 return -1;
1382 }
1383 break;
1384
1385 default:
1386 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001387 return -1;
1388 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001389
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001390 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001391 EVP_CIPHER_CTX_init(&e_ctx);
1392 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001393 SLOGE("EVP_EncryptInit failed\n");
1394 return -1;
1395 }
1396 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001397
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001398 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001399 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001400 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001401 SLOGE("EVP_EncryptUpdate failed\n");
1402 return -1;
1403 }
Adam Langley889c4f12014-09-03 14:23:13 -07001404 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001405 SLOGE("EVP_EncryptFinal failed\n");
1406 return -1;
1407 }
1408
1409 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1410 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1411 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001412 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001413
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001414 /* Store the scrypt of the intermediate key, so we can validate if it's a
1415 password error or mount error when things go wrong.
1416 Note there's no need to check for errors, since if this is incorrect, we
1417 simply won't wipe userdata, which is the correct default behavior
1418 */
1419 int N = 1 << crypt_ftr->N_factor;
1420 int r = 1 << crypt_ftr->r_factor;
1421 int p = 1 << crypt_ftr->p_factor;
1422
1423 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1424 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1425 crypt_ftr->scrypted_intermediate_key,
1426 sizeof(crypt_ftr->scrypted_intermediate_key));
1427
1428 if (rc) {
1429 SLOGE("encrypt_master_key: crypto_scrypt failed");
1430 }
1431
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001432 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001433}
1434
Paul Lawrence731a7a22015-04-28 22:14:15 +00001435static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001436 unsigned char *encrypted_master_key,
1437 unsigned char *decrypted_master_key,
1438 kdf_func kdf, void *kdf_params,
1439 unsigned char** intermediate_key,
1440 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001441{
1442 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 -08001443 EVP_CIPHER_CTX d_ctx;
1444 int decrypted_len, final_len;
1445
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001446 /* Turn the password into an intermediate key and IV that can decrypt the
1447 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001448 if (kdf(passwd, salt, ikey, kdf_params)) {
1449 SLOGE("kdf failed");
1450 return -1;
1451 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001452
1453 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001454 EVP_CIPHER_CTX_init(&d_ctx);
1455 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001456 return -1;
1457 }
1458 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1459 /* Decrypt the master key */
1460 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1461 encrypted_master_key, KEY_LEN_BYTES)) {
1462 return -1;
1463 }
Adam Langley889c4f12014-09-03 14:23:13 -07001464 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001465 return -1;
1466 }
1467
1468 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1469 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001470 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001471
1472 /* Copy intermediate key if needed by params */
1473 if (intermediate_key && intermediate_key_size) {
1474 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1475 if (intermediate_key) {
1476 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1477 *intermediate_key_size = KEY_LEN_BYTES;
1478 }
1479 }
1480
1481 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001482}
1483
Kenny Rootc4c70f12013-06-14 12:11:38 -07001484static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001485{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001486 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001487 *kdf = scrypt_keymaster;
1488 *kdf_params = ftr;
1489 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001490 *kdf = scrypt;
1491 *kdf_params = ftr;
1492 } else {
1493 *kdf = pbkdf2;
1494 *kdf_params = NULL;
1495 }
1496}
1497
Paul Lawrence731a7a22015-04-28 22:14:15 +00001498static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001499 struct crypt_mnt_ftr *crypt_ftr,
1500 unsigned char** intermediate_key,
1501 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001502{
1503 kdf_func kdf;
1504 void *kdf_params;
1505 int ret;
1506
1507 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001508 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1509 decrypted_master_key, kdf, kdf_params,
1510 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001511 if (ret != 0) {
1512 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001513 }
1514
1515 return ret;
1516}
1517
1518static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1519 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001520 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001521 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001522
1523 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001524 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001525 read(fd, key_buf, sizeof(key_buf));
1526 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001527 close(fd);
1528
1529 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001530 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001531}
1532
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001533int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001534{
Greg Hackmann955653e2014-09-24 14:55:20 -07001535 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001536#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001537
1538 /* Now umount the tmpfs filesystem */
1539 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001540 if (umount(mountpoint) == 0) {
1541 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001542 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001543
1544 if (errno == EINVAL) {
1545 /* EINVAL is returned if the directory is not a mountpoint,
1546 * i.e. there is no filesystem mounted there. So just get out.
1547 */
1548 break;
1549 }
1550
1551 err = errno;
1552
1553 /* If allowed, be increasingly aggressive before the last two retries */
1554 if (kill) {
1555 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1556 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001557 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001558 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1559 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001560 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001561 }
1562 }
1563
1564 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001565 }
1566
1567 if (i < WAIT_UNMOUNT_COUNT) {
1568 SLOGD("unmounting %s succeeded\n", mountpoint);
1569 rc = 0;
1570 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001571 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001572 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001573 rc = -1;
1574 }
1575
1576 return rc;
1577}
1578
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001579#define DATA_PREP_TIMEOUT 1000
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001580static int prep_data_fs(void)
1581{
1582 int i;
1583
Jeff Sharkey47695b22016-02-01 17:02:29 -07001584 // NOTE: post_fs_data results in init calling back around to vold, so all
1585 // callers to this method must be async
1586
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001587 /* Do the prep of the /data filesystem */
1588 property_set("vold.post_fs_data_done", "0");
1589 property_set("vold.decrypt", "trigger_post_fs_data");
1590 SLOGD("Just triggered post_fs_data\n");
1591
Ken Sumrallc5872692013-05-14 15:26:31 -07001592 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001593 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001594 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001595
1596 property_get("vold.post_fs_data_done", p, "0");
1597 if (*p == '1') {
1598 break;
1599 } else {
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001600 usleep(50000);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001601 }
1602 }
1603 if (i == DATA_PREP_TIMEOUT) {
1604 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001605 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001606 return -1;
1607 } else {
1608 SLOGD("post_fs_data done\n");
1609 return 0;
1610 }
1611}
1612
Paul Lawrence74f29f12014-08-28 15:54:10 -07001613static void cryptfs_set_corrupt()
1614{
1615 // Mark the footer as bad
1616 struct crypt_mnt_ftr crypt_ftr;
1617 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1618 SLOGE("Failed to get crypto footer - panic");
1619 return;
1620 }
1621
1622 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1623 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1624 SLOGE("Failed to set crypto footer - panic");
1625 return;
1626 }
1627}
1628
1629static void cryptfs_trigger_restart_min_framework()
1630{
1631 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1632 SLOGE("Failed to mount tmpfs on data - panic");
1633 return;
1634 }
1635
1636 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1637 SLOGE("Failed to trigger post fs data - panic");
1638 return;
1639 }
1640
1641 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1642 SLOGE("Failed to trigger restart min framework - panic");
1643 return;
1644 }
1645}
1646
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001647/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001648static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001649{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001650 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001651 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001652 static int restart_successful = 0;
1653
1654 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001655 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001656 SLOGE("Encrypted filesystem not validated, aborting");
1657 return -1;
1658 }
1659
1660 if (restart_successful) {
1661 SLOGE("System already restarted with encrypted disk, aborting");
1662 return -1;
1663 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001664
Paul Lawrencef4faa572014-01-29 13:31:03 -08001665 if (restart_main) {
1666 /* Here is where we shut down the framework. The init scripts
1667 * start all services in one of three classes: core, main or late_start.
1668 * On boot, we start core and main. Now, we stop main, but not core,
1669 * as core includes vold and a few other really important things that
1670 * we need to keep running. Once main has stopped, we should be able
1671 * to umount the tmpfs /data, then mount the encrypted /data.
1672 * We then restart the class main, and also the class late_start.
1673 * At the moment, I've only put a few things in late_start that I know
1674 * are not needed to bring up the framework, and that also cause problems
1675 * with unmounting the tmpfs /data, but I hope to add add more services
1676 * to the late_start class as we optimize this to decrease the delay
1677 * till the user is asked for the password to the filesystem.
1678 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001679
Paul Lawrencef4faa572014-01-29 13:31:03 -08001680 /* The init files are setup to stop the class main when vold.decrypt is
1681 * set to trigger_reset_main.
1682 */
1683 property_set("vold.decrypt", "trigger_reset_main");
1684 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001685
Paul Lawrencef4faa572014-01-29 13:31:03 -08001686 /* Ugh, shutting down the framework is not synchronous, so until it
1687 * can be fixed, this horrible hack will wait a moment for it all to
1688 * shut down before proceeding. Without it, some devices cannot
1689 * restart the graphics services.
1690 */
1691 sleep(2);
1692 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001693
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001694 /* Now that the framework is shutdown, we should be able to umount()
1695 * the tmpfs filesystem, and mount the real one.
1696 */
1697
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001698 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1699 if (strlen(crypto_blkdev) == 0) {
1700 SLOGE("fs_crypto_blkdev not set\n");
1701 return -1;
1702 }
1703
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001704 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001705 /* If ro.crypto.readonly is set to 1, mount the decrypted
1706 * filesystem readonly. This is used when /data is mounted by
1707 * recovery mode.
1708 */
1709 char ro_prop[PROPERTY_VALUE_MAX];
1710 property_get("ro.crypto.readonly", ro_prop, "");
1711 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1712 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1713 rec->flags |= MS_RDONLY;
1714 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001715
Ken Sumralle5032c42012-04-01 23:58:44 -07001716 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001717 int retries = RETRY_MOUNT_ATTEMPTS;
1718 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001719
1720 /*
1721 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1722 * partitions in the fsck domain.
1723 */
1724 if (setexeccon(secontextFsck())){
1725 SLOGE("Failed to setexeccon");
1726 return -1;
1727 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001728 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1729 crypto_blkdev, 0))
1730 != 0) {
1731 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1732 /* TODO: invoke something similar to
1733 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1734 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1735 SLOGI("Failed to mount %s because it is busy - waiting",
1736 crypto_blkdev);
1737 if (--retries) {
1738 sleep(RETRY_MOUNT_DELAY_SECONDS);
1739 } else {
1740 /* Let's hope that a reboot clears away whatever is keeping
1741 the mount busy */
1742 cryptfs_reboot(reboot);
1743 }
1744 } else {
1745 SLOGE("Failed to mount decrypted data");
1746 cryptfs_set_corrupt();
1747 cryptfs_trigger_restart_min_framework();
1748 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001749 if (setexeccon(NULL)) {
1750 SLOGE("Failed to setexeccon");
1751 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001752 return -1;
1753 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001754 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001755 if (setexeccon(NULL)) {
1756 SLOGE("Failed to setexeccon");
1757 return -1;
1758 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001759
Ken Sumralle5032c42012-04-01 23:58:44 -07001760 property_set("vold.decrypt", "trigger_load_persist_props");
1761 /* Create necessary paths on /data */
1762 if (prep_data_fs()) {
1763 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001764 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001765
1766 /* startup service classes main and late_start */
1767 property_set("vold.decrypt", "trigger_restart_framework");
1768 SLOGD("Just triggered restart_framework\n");
1769
1770 /* Give it a few moments to get started */
1771 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001772 }
1773
Ken Sumrall0cc16632011-01-18 20:32:26 -08001774 if (rc == 0) {
1775 restart_successful = 1;
1776 }
1777
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001778 return rc;
1779}
1780
Paul Lawrencef4faa572014-01-29 13:31:03 -08001781int cryptfs_restart(void)
1782{
Paul Lawrence05335c32015-03-05 09:46:23 -08001783 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001784 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001785 SLOGE("cryptfs_restart not valid for file encryption:");
1786 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001787 }
1788
Paul Lawrencef4faa572014-01-29 13:31:03 -08001789 /* Call internal implementation forcing a restart of main service group */
1790 return cryptfs_restart_internal(1);
1791}
1792
Paul Lawrence05335c32015-03-05 09:46:23 -08001793static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001794{
1795 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001796 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001797 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001798
1799 property_get("ro.crypto.state", encrypted_state, "");
1800 if (strcmp(encrypted_state, "encrypted") ) {
1801 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001802 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001803 }
1804
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001805 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001806 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001807 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001808 }
1809
Ken Sumrall160b4d62013-04-22 12:15:39 -07001810 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001811 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001812
Ken Sumralle1a45852011-12-14 21:24:27 -08001813 /*
1814 * Only report this error if key_loc is a file and it exists.
1815 * If the device was never encrypted, and /data is not mountable for
1816 * some reason, returning 1 should prevent the UI from presenting the
1817 * a "enter password" screen, or worse, a "press button to wipe the
1818 * device" screen.
1819 */
1820 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1821 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001822 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001823 } else {
1824 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001825 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001826 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001827 }
1828
Paul Lawrence74f29f12014-08-28 15:54:10 -07001829 // Test for possible error flags
1830 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1831 SLOGE("Encryption process is partway completed\n");
1832 return CRYPTO_COMPLETE_PARTIAL;
1833 }
1834
1835 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1836 SLOGE("Encryption process was interrupted but cannot continue\n");
1837 return CRYPTO_COMPLETE_INCONSISTENT;
1838 }
1839
1840 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1841 SLOGE("Encryption is successful but data is corrupt\n");
1842 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001843 }
1844
1845 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001846 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001847}
1848
Paul Lawrencef4faa572014-01-29 13:31:03 -08001849static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1850 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001851{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001852 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001853 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001854 char crypto_blkdev[MAXPATHLEN];
1855 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001856 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001857 unsigned int orig_failed_decrypt_count;
1858 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001859 int use_keymaster = 0;
1860 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001861 unsigned char* intermediate_key = 0;
1862 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001863
Paul Lawrencef4faa572014-01-29 13:31:03 -08001864 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1865 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001866
Paul Lawrencef4faa572014-01-29 13:31:03 -08001867 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001868 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1869 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001870 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001871 rc = -1;
1872 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001873 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001874 }
1875
Paul Lawrencef4faa572014-01-29 13:31:03 -08001876 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1877
Ajay Dudani87701e22014-09-17 21:02:52 -07001878#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001879 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1880 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1881 SLOGE("Hardware encryption key does not match");
1882 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001883 }
1884#endif
1885
Paul Lawrence74f29f12014-08-28 15:54:10 -07001886 // Create crypto block device - all (non fatal) code paths
1887 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001888 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1889 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001890 SLOGE("Error creating decrypted block device\n");
1891 rc = -1;
1892 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001893 }
1894
Paul Lawrence74f29f12014-08-28 15:54:10 -07001895 /* Work out if the problem is the password or the data */
1896 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1897 scrypted_intermediate_key)];
1898 int N = 1 << crypt_ftr->N_factor;
1899 int r = 1 << crypt_ftr->r_factor;
1900 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001901
Paul Lawrence74f29f12014-08-28 15:54:10 -07001902 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1903 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1904 N, r, p, scrypted_intermediate_key,
1905 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001906
Paul Lawrence74f29f12014-08-28 15:54:10 -07001907 // Does the key match the crypto footer?
1908 if (rc == 0 && memcmp(scrypted_intermediate_key,
1909 crypt_ftr->scrypted_intermediate_key,
1910 sizeof(scrypted_intermediate_key)) == 0) {
1911 SLOGI("Password matches");
1912 rc = 0;
1913 } else {
1914 /* Try mounting the file system anyway, just in case the problem's with
1915 * the footer, not the key. */
1916 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1917 mkdir(tmp_mount_point, 0755);
1918 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1919 SLOGE("Error temp mounting decrypted block device\n");
1920 delete_crypto_blk_dev(label);
1921
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001922 rc = ++crypt_ftr->failed_decrypt_count;
1923 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001924 } else {
1925 /* Success! */
1926 SLOGI("Password did not match but decrypted drive mounted - continue");
1927 umount(tmp_mount_point);
1928 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001929 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001930 }
1931
1932 if (rc == 0) {
1933 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001934 if (orig_failed_decrypt_count != 0) {
1935 put_crypt_ftr_and_key(crypt_ftr);
1936 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001937
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001938 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001939 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001940 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001941
1942 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001943 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001944 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001945 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001946 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001947 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001948 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001949
Paul Lawrence74f29f12014-08-28 15:54:10 -07001950 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001951 use_keymaster = keymaster_check_compatibility();
1952 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001953 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001954 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1955 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1956 upgrade = 1;
1957 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001958 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001959 upgrade = 1;
1960 }
1961
1962 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001963 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1964 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001965 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001966 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001967 }
1968 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001969
1970 // Do not fail even if upgrade failed - machine is bootable
1971 // Note that if this code is ever hit, there is a *serious* problem
1972 // since KDFs should never fail. You *must* fix the kdf before
1973 // proceeding!
1974 if (rc) {
1975 SLOGW("Upgrade failed with error %d,"
1976 " but continuing with previous state",
1977 rc);
1978 rc = 0;
1979 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001980 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001981 }
1982
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001983 errout:
1984 if (intermediate_key) {
1985 memset(intermediate_key, 0, intermediate_key_size);
1986 free(intermediate_key);
1987 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001988 return rc;
1989}
1990
Ken Sumrall29d8da82011-05-18 17:20:07 -07001991/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001992 * Called by vold when it's asked to mount an encrypted external
1993 * storage volume. The incoming partition has no crypto header/footer,
1994 * as any metadata is been stored in a separate, small partition.
1995 *
1996 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001997 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001998int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1999 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002000 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002001 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002002 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002003 return -1;
2004 }
2005
2006 unsigned long nr_sec = 0;
2007 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002008 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002009
Ken Sumrall29d8da82011-05-18 17:20:07 -07002010 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002011 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002012 return -1;
2013 }
2014
Jeff Sharkey9c484982015-03-31 10:35:33 -07002015 struct crypt_mnt_ftr ext_crypt_ftr;
2016 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2017 ext_crypt_ftr.fs_size = nr_sec;
2018 ext_crypt_ftr.keysize = keysize;
2019 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002020
Jeff Sharkey9c484982015-03-31 10:35:33 -07002021 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
2022 out_crypto_blkdev, label);
2023}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002024
Jeff Sharkey9c484982015-03-31 10:35:33 -07002025/*
2026 * Called by vold when it's asked to unmount an encrypted external
2027 * storage volume.
2028 */
2029int cryptfs_revert_ext_volume(const char* label) {
2030 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002031}
2032
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002033int cryptfs_crypto_complete(void)
2034{
2035 return do_crypto_complete("/data");
2036}
2037
Paul Lawrencef4faa572014-01-29 13:31:03 -08002038int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2039{
2040 char encrypted_state[PROPERTY_VALUE_MAX];
2041 property_get("ro.crypto.state", encrypted_state, "");
2042 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2043 SLOGE("encrypted fs already validated or not running with encryption,"
2044 " aborting");
2045 return -1;
2046 }
2047
2048 if (get_crypt_ftr_and_key(crypt_ftr)) {
2049 SLOGE("Error getting crypt footer and key");
2050 return -1;
2051 }
2052
2053 return 0;
2054}
2055
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002056int cryptfs_check_passwd(char *passwd)
2057{
Paul Lawrence05335c32015-03-05 09:46:23 -08002058 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00002059 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002060 SLOGE("cryptfs_check_passwd not valid for file encryption");
2061 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002062 }
2063
Paul Lawrencef4faa572014-01-29 13:31:03 -08002064 struct crypt_mnt_ftr crypt_ftr;
2065 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002066
Paul Lawrencef4faa572014-01-29 13:31:03 -08002067 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002068 if (rc) {
2069 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002070 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002071 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002072
Paul Lawrence3bd36d52015-06-09 13:37:44 -07002073 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002074 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2075 if (rc) {
2076 SLOGE("Password did not match");
2077 return rc;
2078 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002079
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002080 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2081 // Here we have a default actual password but a real password
2082 // we must test against the scrypted value
2083 // First, we must delete the crypto block device that
2084 // test_mount_encrypted_fs leaves behind as a side effect
2085 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2086 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2087 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2088 if (rc) {
2089 SLOGE("Default password did not match on reboot encryption");
2090 return rc;
2091 }
2092
2093 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2094 put_crypt_ftr_and_key(&crypt_ftr);
2095 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2096 if (rc) {
2097 SLOGE("Could not change password on reboot encryption");
2098 return rc;
2099 }
2100 }
2101
2102 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002103 cryptfs_clear_password();
2104 password = strdup(passwd);
2105 struct timespec now;
2106 clock_gettime(CLOCK_BOOTTIME, &now);
2107 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002108 }
2109
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002110 return rc;
2111}
2112
Ken Sumrall3ad90722011-10-04 20:38:29 -07002113int cryptfs_verify_passwd(char *passwd)
2114{
2115 struct crypt_mnt_ftr crypt_ftr;
2116 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002117 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002118 char encrypted_state[PROPERTY_VALUE_MAX];
2119 int rc;
2120
2121 property_get("ro.crypto.state", encrypted_state, "");
2122 if (strcmp(encrypted_state, "encrypted") ) {
2123 SLOGE("device not encrypted, aborting");
2124 return -2;
2125 }
2126
2127 if (!master_key_saved) {
2128 SLOGE("encrypted fs not yet mounted, aborting");
2129 return -1;
2130 }
2131
2132 if (!saved_mount_point) {
2133 SLOGE("encrypted fs failed to save mount point, aborting");
2134 return -1;
2135 }
2136
Ken Sumrall160b4d62013-04-22 12:15:39 -07002137 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002138 SLOGE("Error getting crypt footer and key\n");
2139 return -1;
2140 }
2141
2142 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2143 /* If the device has no password, then just say the password is valid */
2144 rc = 0;
2145 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002146 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002147 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2148 /* They match, the password is correct */
2149 rc = 0;
2150 } else {
2151 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2152 sleep(1);
2153 rc = 1;
2154 }
2155 }
2156
2157 return rc;
2158}
2159
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002160/* Initialize a crypt_mnt_ftr structure. The keysize is
2161 * defaulted to 16 bytes, and the filesystem size to 0.
2162 * Presumably, at a minimum, the caller will update the
2163 * filesystem size and crypto_type_name after calling this function.
2164 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002165static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002166{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002167 off64_t off;
2168
2169 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002170 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002171 ftr->major_version = CURRENT_MAJOR_VERSION;
2172 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002173 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002174 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002175
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002176 switch (keymaster_check_compatibility()) {
2177 case 1:
2178 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2179 break;
2180
2181 case 0:
2182 ftr->kdf_type = KDF_SCRYPT;
2183 break;
2184
2185 default:
2186 SLOGE("keymaster_check_compatibility failed");
2187 return -1;
2188 }
2189
Kenny Rootc4c70f12013-06-14 12:11:38 -07002190 get_device_scrypt_params(ftr);
2191
Ken Sumrall160b4d62013-04-22 12:15:39 -07002192 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2193 if (get_crypt_ftr_info(NULL, &off) == 0) {
2194 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2195 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2196 ftr->persist_data_size;
2197 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002198
2199 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002200}
2201
Ken Sumrall29d8da82011-05-18 17:20:07 -07002202static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002203{
Ken Sumralle550f782013-08-20 13:48:23 -07002204 const char *args[10];
2205 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2206 int num_args;
2207 int status;
2208 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002209 int rc = -1;
2210
Ken Sumrall29d8da82011-05-18 17:20:07 -07002211 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002212 args[0] = "/system/bin/make_ext4fs";
2213 args[1] = "-a";
2214 args[2] = "/data";
2215 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002216 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002217 args[4] = size_str;
2218 args[5] = crypto_blkdev;
2219 num_args = 6;
2220 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2221 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002222 } else if (type == F2FS_FS) {
2223 args[0] = "/system/bin/mkfs.f2fs";
2224 args[1] = "-t";
2225 args[2] = "-d1";
2226 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002227 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002228 args[4] = size_str;
2229 num_args = 5;
2230 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2231 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002232 } else {
2233 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2234 return -1;
2235 }
2236
Ken Sumralle550f782013-08-20 13:48:23 -07002237 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2238
2239 if (tmp != 0) {
2240 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002241 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002242 if (WIFEXITED(status)) {
2243 if (WEXITSTATUS(status)) {
2244 SLOGE("Error creating filesystem on %s, exit status %d ",
2245 crypto_blkdev, WEXITSTATUS(status));
2246 } else {
2247 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2248 rc = 0;
2249 }
2250 } else {
2251 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2252 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002253 }
2254
2255 return rc;
2256}
2257
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002258#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002259#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2260#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002261
2262/* aligned 32K writes tends to make flash happy.
2263 * SD card association recommends it.
2264 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002265#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002266#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002267#else
2268#define BLOCKS_AT_A_TIME 1024
2269#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002270
2271struct encryptGroupsData
2272{
2273 int realfd;
2274 int cryptofd;
2275 off64_t numblocks;
2276 off64_t one_pct, cur_pct, new_pct;
2277 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002278 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002279 char* real_blkdev, * crypto_blkdev;
2280 int count;
2281 off64_t offset;
2282 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002283 off64_t last_written_sector;
2284 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002285 time_t time_started;
2286 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002287};
2288
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002289static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002290{
2291 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002292
2293 if (is_used) {
2294 data->used_blocks_already_done++;
2295 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002296 if (data->tot_used_blocks) {
2297 data->new_pct = data->used_blocks_already_done / data->one_pct;
2298 } else {
2299 data->new_pct = data->blocks_already_done / data->one_pct;
2300 }
2301
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002302 if (data->new_pct > data->cur_pct) {
2303 char buf[8];
2304 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002305 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002306 property_set("vold.encrypt_progress", buf);
2307 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002308
2309 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002310 struct timespec time_now;
2311 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2312 SLOGW("Error getting time");
2313 } else {
2314 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2315 off64_t remaining_blocks = data->tot_used_blocks
2316 - data->used_blocks_already_done;
2317 int remaining_time = (int)(elapsed_time * remaining_blocks
2318 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002319
Paul Lawrence9c58a872014-09-30 09:12:51 -07002320 // Change time only if not yet set, lower, or a lot higher for
2321 // best user experience
2322 if (data->remaining_time == -1
2323 || remaining_time < data->remaining_time
2324 || remaining_time > data->remaining_time + 60) {
2325 char buf[8];
2326 snprintf(buf, sizeof(buf), "%d", remaining_time);
2327 property_set("vold.encrypt_time_remaining", buf);
2328 data->remaining_time = remaining_time;
2329 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002330 }
2331 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002332}
2333
Paul Lawrence3846be12014-09-22 11:33:54 -07002334static void log_progress(struct encryptGroupsData const* data, bool completed)
2335{
2336 // Precondition - if completed data = 0 else data != 0
2337
2338 // Track progress so we can skip logging blocks
2339 static off64_t offset = -1;
2340
2341 // Need to close existing 'Encrypting from' log?
2342 if (completed || (offset != -1 && data->offset != offset)) {
2343 SLOGI("Encrypted to sector %" PRId64,
2344 offset / info.block_size * CRYPT_SECTOR_SIZE);
2345 offset = -1;
2346 }
2347
2348 // Need to start new 'Encrypting from' log?
2349 if (!completed && offset != data->offset) {
2350 SLOGI("Encrypting from sector %" PRId64,
2351 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2352 }
2353
2354 // Update offset
2355 if (!completed) {
2356 offset = data->offset + (off64_t)data->count * info.block_size;
2357 }
2358}
2359
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002360static int flush_outstanding_data(struct encryptGroupsData* data)
2361{
2362 if (data->count == 0) {
2363 return 0;
2364 }
2365
Elliott Hughes231bdba2014-06-25 18:36:19 -07002366 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002367
2368 if (pread64(data->realfd, data->buffer,
2369 info.block_size * data->count, data->offset)
2370 <= 0) {
2371 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2372 data->real_blkdev);
2373 return -1;
2374 }
2375
2376 if (pwrite64(data->cryptofd, data->buffer,
2377 info.block_size * data->count, data->offset)
2378 <= 0) {
2379 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2380 data->crypto_blkdev);
2381 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002382 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002383 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002384 }
2385
2386 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002387 data->last_written_sector = (data->offset + data->count)
2388 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002389 return 0;
2390}
2391
2392static int encrypt_groups(struct encryptGroupsData* data)
2393{
2394 unsigned int i;
2395 u8 *block_bitmap = 0;
2396 unsigned int block;
2397 off64_t ret;
2398 int rc = -1;
2399
2400 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2401 if (!data->buffer) {
2402 SLOGE("Failed to allocate crypto buffer");
2403 goto errout;
2404 }
2405
2406 block_bitmap = malloc(info.block_size);
2407 if (!block_bitmap) {
2408 SLOGE("failed to allocate block bitmap");
2409 goto errout;
2410 }
2411
2412 for (i = 0; i < aux_info.groups; ++i) {
2413 SLOGI("Encrypting group %d", i);
2414
2415 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2416 u32 block_count = min(info.blocks_per_group,
2417 aux_info.len_blocks - first_block);
2418
2419 off64_t offset = (u64)info.block_size
2420 * aux_info.bg_desc[i].bg_block_bitmap;
2421
2422 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2423 if (ret != (int)info.block_size) {
2424 SLOGE("failed to read all of block group bitmap %d", i);
2425 goto errout;
2426 }
2427
2428 offset = (u64)info.block_size * first_block;
2429
2430 data->count = 0;
2431
2432 for (block = 0; block < block_count; block++) {
liminghaoaa08e582016-01-06 10:30:49 +08002433 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
2434 0 : bitmap_get_bit(block_bitmap, block);
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002435 update_progress(data, used);
2436 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002437 if (data->count == 0) {
2438 data->offset = offset;
2439 }
2440 data->count++;
2441 } else {
2442 if (flush_outstanding_data(data)) {
2443 goto errout;
2444 }
2445 }
2446
2447 offset += info.block_size;
2448
2449 /* Write data if we are aligned or buffer size reached */
2450 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2451 || data->count == BLOCKS_AT_A_TIME) {
2452 if (flush_outstanding_data(data)) {
2453 goto errout;
2454 }
2455 }
Paul Lawrence87999172014-02-20 12:21:31 -08002456
Paul Lawrence73d7a022014-06-09 14:10:09 -07002457 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002458 SLOGE("Stopping encryption due to low battery");
2459 rc = 0;
2460 goto errout;
2461 }
2462
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002463 }
2464 if (flush_outstanding_data(data)) {
2465 goto errout;
2466 }
2467 }
2468
Paul Lawrence87999172014-02-20 12:21:31 -08002469 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002470 rc = 0;
2471
2472errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002473 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002474 free(data->buffer);
2475 free(block_bitmap);
2476 return rc;
2477}
2478
2479static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2480 char *real_blkdev,
2481 off64_t size,
2482 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002483 off64_t tot_size,
2484 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002485{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002486 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002487 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002488 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002489
Paul Lawrence87999172014-02-20 12:21:31 -08002490 if (previously_encrypted_upto > *size_already_done) {
2491 SLOGD("Not fast encrypting since resuming part way through");
2492 return -1;
2493 }
2494
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002495 memset(&data, 0, sizeof(data));
2496 data.real_blkdev = real_blkdev;
2497 data.crypto_blkdev = crypto_blkdev;
2498
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002499 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002500 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2501 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002502 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002503 goto errout;
2504 }
2505
David Ng82fd8042015-01-21 13:55:21 -08002506 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2507 int retries = RETRY_MOUNT_ATTEMPTS;
2508 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2509 if (--retries) {
2510 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2511 crypto_blkdev, errno, strerror(errno));
2512 sleep(RETRY_MOUNT_DELAY_SECONDS);
2513 } else {
2514 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2515 crypto_blkdev, errno, strerror(errno));
2516 rc = ENABLE_INPLACE_ERR_DEV;
2517 goto errout;
2518 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002519 }
2520
2521 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002522 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002523 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002524 goto errout;
2525 }
2526
2527 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002528 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002529 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002530 goto errout;
2531 }
2532
2533 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2534 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2535 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2536
JP Abgrall7fc1de82014-10-10 18:43:41 -07002537 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002538
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002539 data.tot_used_blocks = data.numblocks;
2540 for (i = 0; i < aux_info.groups; ++i) {
2541 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2542 }
2543
2544 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002545 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002546
2547 struct timespec time_started = {0};
2548 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2549 SLOGW("Error getting time at start");
2550 // Note - continue anyway - we'll run with 0
2551 }
2552 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002553 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002554
2555 rc = encrypt_groups(&data);
2556 if (rc) {
2557 SLOGE("Error encrypting groups");
2558 goto errout;
2559 }
2560
Paul Lawrence87999172014-02-20 12:21:31 -08002561 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002562 rc = 0;
2563
2564errout:
2565 close(data.realfd);
2566 close(data.cryptofd);
2567
2568 return rc;
2569}
2570
Paul Lawrence3846be12014-09-22 11:33:54 -07002571static void log_progress_f2fs(u64 block, bool completed)
2572{
2573 // Precondition - if completed data = 0 else data != 0
2574
2575 // Track progress so we can skip logging blocks
2576 static u64 last_block = (u64)-1;
2577
2578 // Need to close existing 'Encrypting from' log?
2579 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2580 SLOGI("Encrypted to block %" PRId64, last_block);
2581 last_block = -1;
2582 }
2583
2584 // Need to start new 'Encrypting from' log?
2585 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2586 SLOGI("Encrypting from block %" PRId64, block);
2587 }
2588
2589 // Update offset
2590 if (!completed) {
2591 last_block = block;
2592 }
2593}
2594
Daniel Rosenberge82df162014-08-15 22:19:23 +00002595static int encrypt_one_block_f2fs(u64 pos, void *data)
2596{
2597 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2598
2599 priv_dat->blocks_already_done = pos - 1;
2600 update_progress(priv_dat, 1);
2601
2602 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2603
2604 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002605 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002606 return -1;
2607 }
2608
2609 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002610 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002611 return -1;
2612 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002613 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002614 }
2615
2616 return 0;
2617}
2618
2619static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2620 char *real_blkdev,
2621 off64_t size,
2622 off64_t *size_already_done,
2623 off64_t tot_size,
2624 off64_t previously_encrypted_upto)
2625{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002626 struct encryptGroupsData data;
2627 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002628 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002629 if (previously_encrypted_upto > *size_already_done) {
2630 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002631 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002632 }
2633 memset(&data, 0, sizeof(data));
2634 data.real_blkdev = real_blkdev;
2635 data.crypto_blkdev = crypto_blkdev;
2636 data.realfd = -1;
2637 data.cryptofd = -1;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002638 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002639 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002640 real_blkdev);
2641 goto errout;
2642 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002643 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002644 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002645 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002646 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002647 goto errout;
2648 }
2649
2650 f2fs_info = generate_f2fs_info(data.realfd);
2651 if (!f2fs_info)
2652 goto errout;
2653
2654 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2655 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2656 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2657
2658 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2659
2660 data.one_pct = data.tot_used_blocks / 100;
2661 data.cur_pct = 0;
2662 data.time_started = time(NULL);
2663 data.remaining_time = -1;
2664
2665 data.buffer = malloc(f2fs_info->block_size);
2666 if (!data.buffer) {
2667 SLOGE("Failed to allocate crypto buffer");
2668 goto errout;
2669 }
2670
2671 data.count = 0;
2672
2673 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2674 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2675
2676 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002677 SLOGE("Error in running over f2fs blocks");
2678 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002679 goto errout;
2680 }
2681
2682 *size_already_done += size;
2683 rc = 0;
2684
2685errout:
2686 if (rc)
2687 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2688
Paul Lawrence3846be12014-09-22 11:33:54 -07002689 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002690 free(f2fs_info);
2691 free(data.buffer);
2692 close(data.realfd);
2693 close(data.cryptofd);
2694
2695 return rc;
2696}
2697
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002698static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2699 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002700 off64_t tot_size,
2701 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002702{
2703 int realfd, cryptofd;
2704 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002705 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002706 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002707 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002708 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002709
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002710 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002711 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002712 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002713 }
2714
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002715 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002716 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2717 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002718 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002719 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002720 }
2721
2722 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2723 * The size passed in is the number of 512 byte sectors in the filesystem.
2724 * So compute the number of whole 4K blocks we should read/write,
2725 * and the remainder.
2726 */
2727 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2728 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002729 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2730 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002731
2732 SLOGE("Encrypting filesystem in place...");
2733
Paul Lawrence87999172014-02-20 12:21:31 -08002734 i = previously_encrypted_upto + 1 - *size_already_done;
2735
2736 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2737 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2738 goto errout;
2739 }
2740
2741 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2742 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2743 goto errout;
2744 }
2745
2746 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2747 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2748 SLOGE("Error reading initial sectors from real_blkdev %s for "
2749 "inplace encrypt\n", crypto_blkdev);
2750 goto errout;
2751 }
2752 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2753 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2754 "inplace encrypt\n", crypto_blkdev);
2755 goto errout;
2756 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002757 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002758 }
2759 }
2760
Ken Sumrall29d8da82011-05-18 17:20:07 -07002761 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002762 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002763 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002764 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002765 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002766 if (new_pct > cur_pct) {
2767 char buf[8];
2768
2769 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002770 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002771 property_set("vold.encrypt_progress", buf);
2772 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002773 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002774 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002775 goto errout;
2776 }
2777 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002778 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2779 goto errout;
2780 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002781 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002782 CRYPT_SECTORS_PER_BUFSIZE,
2783 i * CRYPT_SECTORS_PER_BUFSIZE);
2784 }
2785
Paul Lawrence73d7a022014-06-09 14:10:09 -07002786 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002787 SLOGE("Stopping encryption due to low battery");
2788 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2789 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002790 goto errout;
2791 }
2792 }
2793
2794 /* Do any remaining sectors */
2795 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002796 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2797 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002798 goto errout;
2799 }
Paul Lawrence87999172014-02-20 12:21:31 -08002800 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2801 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002802 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002803 } else {
2804 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002805 }
2806 }
2807
Ken Sumrall29d8da82011-05-18 17:20:07 -07002808 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002809 rc = 0;
2810
2811errout:
2812 close(realfd);
2813 close(cryptofd);
2814
2815 return rc;
2816}
2817
JP Abgrall7fc1de82014-10-10 18:43:41 -07002818/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002819static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2820 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002821 off64_t tot_size,
2822 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002823{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002824 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002825 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002826 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002827 }
2828
2829 if (*size_already_done + size < previously_encrypted_upto) {
2830 *size_already_done += size;
2831 return 0;
2832 }
2833
Daniel Rosenberge82df162014-08-15 22:19:23 +00002834 /* TODO: identify filesystem type.
2835 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2836 * then we will drop down to cryptfs_enable_inplace_f2fs.
2837 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002838 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002839 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002840 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002841 return 0;
2842 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002843 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002844
JP Abgrall7fc1de82014-10-10 18:43:41 -07002845 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002846 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002847 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002848 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002849 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002850 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002851
JP Abgrall7fc1de82014-10-10 18:43:41 -07002852 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002853 size, size_already_done, tot_size,
2854 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002855 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2856
2857 /* Hack for b/17898962, the following is the symptom... */
2858 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2859 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2860 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2861 return ENABLE_INPLACE_ERR_DEV;
2862 }
2863 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002864}
2865
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002866#define CRYPTO_ENABLE_WIPE 1
2867#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002868
2869#define FRAMEWORK_BOOT_WAIT 60
2870
Paul Lawrence87999172014-02-20 12:21:31 -08002871static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2872{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002873 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002874 if (fd == -1) {
2875 SLOGE("Error opening file %s", filename);
2876 return -1;
2877 }
2878
2879 char block[CRYPT_INPLACE_BUFSIZE];
2880 memset(block, 0, sizeof(block));
2881 if (unix_read(fd, block, sizeof(block)) < 0) {
2882 SLOGE("Error reading file %s", filename);
2883 close(fd);
2884 return -1;
2885 }
2886
2887 close(fd);
2888
2889 SHA256_CTX c;
2890 SHA256_Init(&c);
2891 SHA256_Update(&c, block, sizeof(block));
2892 SHA256_Final(buf, &c);
2893
2894 return 0;
2895}
2896
JP Abgrall62c7af32014-06-16 13:01:23 -07002897static int get_fs_type(struct fstab_rec *rec)
2898{
2899 if (!strcmp(rec->fs_type, "ext4")) {
2900 return EXT4_FS;
2901 } else if (!strcmp(rec->fs_type, "f2fs")) {
2902 return F2FS_FS;
2903 } else {
2904 return -1;
2905 }
2906}
2907
Paul Lawrence87999172014-02-20 12:21:31 -08002908static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2909 char *crypto_blkdev, char *real_blkdev,
2910 int previously_encrypted_upto)
2911{
2912 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002913 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002914
Paul Lawrence73d7a022014-06-09 14:10:09 -07002915 if (!is_battery_ok_to_start()) {
2916 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002917 return 0;
2918 }
2919
2920 /* The size of the userdata partition, and add in the vold volumes below */
2921 tot_encryption_size = crypt_ftr->fs_size;
2922
2923 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002924 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2925 int fs_type = get_fs_type(rec);
2926 if (fs_type < 0) {
2927 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2928 return -1;
2929 }
2930 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002931 } else if (how == CRYPTO_ENABLE_INPLACE) {
2932 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2933 crypt_ftr->fs_size, &cur_encryption_done,
2934 tot_encryption_size,
2935 previously_encrypted_upto);
2936
JP Abgrall7fc1de82014-10-10 18:43:41 -07002937 if (rc == ENABLE_INPLACE_ERR_DEV) {
2938 /* Hack for b/17898962 */
2939 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2940 cryptfs_reboot(reboot);
2941 }
2942
Paul Lawrence73d7a022014-06-09 14:10:09 -07002943 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002944 crypt_ftr->encrypted_upto = cur_encryption_done;
2945 }
2946
Paul Lawrence73d7a022014-06-09 14:10:09 -07002947 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002948 /* The inplace routine never actually sets the progress to 100% due
2949 * to the round down nature of integer division, so set it here */
2950 property_set("vold.encrypt_progress", "100");
2951 }
2952 } else {
2953 /* Shouldn't happen */
2954 SLOGE("cryptfs_enable: internal error, unknown option\n");
2955 rc = -1;
2956 }
2957
2958 return rc;
2959}
2960
Paul Lawrence13486032014-02-03 13:28:11 -08002961int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002962 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002963{
2964 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002965 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002966 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002967 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002968 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002969 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002970 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002971 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002972 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002973 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002974 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002975 bool rebootEncryption = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002976
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002977 if (!strcmp(howarg, "wipe")) {
2978 how = CRYPTO_ENABLE_WIPE;
2979 } else if (! strcmp(howarg, "inplace")) {
2980 how = CRYPTO_ENABLE_INPLACE;
2981 } else {
2982 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002983 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002984 }
2985
Paul Lawrence87999172014-02-20 12:21:31 -08002986 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002987 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2988 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2989 /* An encryption was underway and was interrupted */
2990 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2991 crypt_ftr.encrypted_upto = 0;
2992 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002993
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002994 /* At this point, we are in an inconsistent state. Until we successfully
2995 complete encryption, a reboot will leave us broken. So mark the
2996 encryption failed in case that happens.
2997 On successfully completing encryption, remove this flag */
2998 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002999
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003000 put_crypt_ftr_and_key(&crypt_ftr);
3001 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
3002 if (!check_ftr_sha(&crypt_ftr)) {
3003 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
3004 put_crypt_ftr_and_key(&crypt_ftr);
3005 goto error_unencrypted;
3006 }
3007
3008 /* Doing a reboot-encryption*/
3009 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
3010 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
3011 rebootEncryption = true;
3012 }
Paul Lawrence87999172014-02-20 12:21:31 -08003013 }
3014
3015 property_get("ro.crypto.state", encrypted_state, "");
3016 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
3017 SLOGE("Device is already running encrypted, aborting");
3018 goto error_unencrypted;
3019 }
3020
3021 // TODO refactor fs_mgr_get_crypt_info to get both in one call
3022 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08003023 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003024
Ken Sumrall3ed82362011-01-28 23:31:16 -08003025 /* Get the size of the real block device */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003026 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09003027 if (fd == -1) {
3028 SLOGE("Cannot open block device %s\n", real_blkdev);
3029 goto error_unencrypted;
3030 }
3031 unsigned long nr_sec;
3032 get_blkdev_size(fd, &nr_sec);
3033 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003034 SLOGE("Cannot get size of block device %s\n", real_blkdev);
3035 goto error_unencrypted;
3036 }
3037 close(fd);
3038
3039 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003040 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003041 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00003042 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00003043 if (fs_size_sec == 0)
3044 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3045
Paul Lawrence87999172014-02-20 12:21:31 -08003046 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003047
3048 if (fs_size_sec > max_fs_size_sec) {
3049 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3050 goto error_unencrypted;
3051 }
3052 }
3053
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003054 /* Get a wakelock as this may take a while, and we don't want the
3055 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3056 * wants to keep the screen on, it can grab a full wakelock.
3057 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003058 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003059 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3060
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003061 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003062 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003063 */
3064 property_set("vold.decrypt", "trigger_shutdown_framework");
3065 SLOGD("Just asked init to shut down class main\n");
3066
Jeff Sharkey9c484982015-03-31 10:35:33 -07003067 /* Ask vold to unmount all devices that it manages */
3068 if (vold_unmountAll()) {
3069 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003070 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003071
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003072 /* no_ui means we are being called from init, not settings.
3073 Now we always reboot from settings, so !no_ui means reboot
3074 */
3075 bool onlyCreateHeader = false;
3076 if (!no_ui) {
3077 /* Try fallback, which is to reboot and try there */
3078 onlyCreateHeader = true;
3079 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
3080 if (breadcrumb == 0) {
3081 SLOGE("Failed to create breadcrumb file");
3082 goto error_shutting_down;
3083 }
3084 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003085 }
3086
3087 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003088 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003089 /* Now that /data is unmounted, we need to mount a tmpfs
3090 * /data, set a property saying we're doing inplace encryption,
3091 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003092 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003093 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003094 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003095 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003096 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003097 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003098
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003099 /* restart the framework. */
3100 /* Create necessary paths on /data */
3101 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003102 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003103 }
3104
Ken Sumrall92736ef2012-10-17 20:57:14 -07003105 /* Ugh, shutting down the framework is not synchronous, so until it
3106 * can be fixed, this horrible hack will wait a moment for it all to
3107 * shut down before proceeding. Without it, some devices cannot
3108 * restart the graphics services.
3109 */
3110 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003111 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003112
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003113 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003114 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003115 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003116 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3117 goto error_shutting_down;
3118 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003119
Paul Lawrence87999172014-02-20 12:21:31 -08003120 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3121 crypt_ftr.fs_size = nr_sec
3122 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3123 } else {
3124 crypt_ftr.fs_size = nr_sec;
3125 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003126 /* At this point, we are in an inconsistent state. Until we successfully
3127 complete encryption, a reboot will leave us broken. So mark the
3128 encryption failed in case that happens.
3129 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003130 if (onlyCreateHeader) {
3131 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
3132 } else {
3133 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3134 }
Paul Lawrence87999172014-02-20 12:21:31 -08003135 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003136#ifndef CONFIG_HW_DISK_ENCRYPTION
3137 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3138#else
3139 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3140
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003141 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003142 if (!rc) {
3143 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3144 }
3145
3146 rc = set_hw_device_encryption_key(passwd,
3147 (char*) crypt_ftr.crypto_type_name);
3148 if (!rc) {
3149 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3150 goto error_shutting_down;
3151 }
3152#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003153
Paul Lawrence87999172014-02-20 12:21:31 -08003154 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003155 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
3156 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08003157 SLOGE("Cannot create encrypted master key\n");
3158 goto error_shutting_down;
3159 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003160
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003161 /* Replace scrypted intermediate key if we are preparing for a reboot */
3162 if (onlyCreateHeader) {
3163 unsigned char fake_master_key[KEY_LEN_BYTES];
3164 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
3165 memset(fake_master_key, 0, sizeof(fake_master_key));
3166 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
3167 encrypted_fake_master_key, &crypt_ftr);
3168 }
3169
Paul Lawrence87999172014-02-20 12:21:31 -08003170 /* Write the key to the end of the partition */
3171 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003172
Paul Lawrence87999172014-02-20 12:21:31 -08003173 /* If any persistent data has been remembered, save it.
3174 * If none, create a valid empty table and save that.
3175 */
3176 if (!persist_data) {
3177 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3178 if (pdata) {
3179 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3180 persist_data = pdata;
3181 }
3182 }
3183 if (persist_data) {
3184 save_persistent_data();
3185 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003186 }
3187
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003188 if (onlyCreateHeader) {
3189 sleep(2);
3190 cryptfs_reboot(reboot);
3191 }
3192
3193 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07003194 /* startup service classes main and late_start */
3195 property_set("vold.decrypt", "trigger_restart_min_framework");
3196 SLOGD("Just triggered restart_min_framework\n");
3197
3198 /* OK, the framework is restarted and will soon be showing a
3199 * progress bar. Time to setup an encrypted mapping, and
3200 * either write a new filesystem, or encrypt in place updating
3201 * the progress bar as we work.
3202 */
3203 }
3204
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003205 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003206 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003207 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003208
Paul Lawrence87999172014-02-20 12:21:31 -08003209 /* If we are continuing, check checksums match */
3210 rc = 0;
3211 if (previously_encrypted_upto) {
3212 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3213 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003214
Paul Lawrence87999172014-02-20 12:21:31 -08003215 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3216 sizeof(hash_first_block)) != 0) {
3217 SLOGE("Checksums do not match - trigger wipe");
3218 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003219 }
3220 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003221
Paul Lawrence87999172014-02-20 12:21:31 -08003222 if (!rc) {
3223 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3224 crypto_blkdev, real_blkdev,
3225 previously_encrypted_upto);
3226 }
3227
3228 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003229 if (!rc && how == CRYPTO_ENABLE_INPLACE
3230 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003231 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3232 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003233 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003234 SLOGE("Error calculating checksum for continuing encryption");
3235 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003236 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003237 }
3238
3239 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003240 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003241
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003242 if (! rc) {
3243 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003244 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003245
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003246 if (how == CRYPTO_ENABLE_INPLACE
3247 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003248 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3249 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003250 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003251 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003252
Paul Lawrence6bfed202014-07-28 12:47:22 -07003253 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003254
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003255 if (how == CRYPTO_ENABLE_WIPE
3256 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003257 char value[PROPERTY_VALUE_MAX];
3258 property_get("ro.crypto.state", value, "");
3259 if (!strcmp(value, "")) {
3260 /* default encryption - continue first boot sequence */
3261 property_set("ro.crypto.state", "encrypted");
3262 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003263 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
3264 // Bring up cryptkeeper that will check the password and set it
3265 property_set("vold.decrypt", "trigger_shutdown_framework");
3266 sleep(2);
3267 property_set("vold.encrypt_progress", "");
3268 cryptfs_trigger_restart_min_framework();
3269 } else {
3270 cryptfs_check_passwd(DEFAULT_PASSWORD);
3271 cryptfs_restart_internal(1);
3272 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003273 return 0;
3274 } else {
3275 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003276 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003277 }
Paul Lawrence87999172014-02-20 12:21:31 -08003278 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003279 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003280 cryptfs_reboot(shutdown);
3281 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003282 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003283 char value[PROPERTY_VALUE_MAX];
3284
Ken Sumrall319369a2012-06-27 16:30:18 -07003285 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003286 if (!strcmp(value, "1")) {
3287 /* wipe data if encryption failed */
3288 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3289 mkdir("/cache/recovery", 0700);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003290 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003291 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003292 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3293 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003294 close(fd);
3295 } else {
3296 SLOGE("could not open /cache/recovery/command\n");
3297 }
Paul Lawrence87999172014-02-20 12:21:31 -08003298 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003299 } else {
3300 /* set property to trigger dialog */
3301 property_set("vold.encrypt_progress", "error_partially_encrypted");
3302 release_wake_lock(lockid);
3303 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003304 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003305 }
3306
Ken Sumrall3ed82362011-01-28 23:31:16 -08003307 /* hrm, the encrypt step claims success, but the reboot failed.
3308 * This should not happen.
3309 * Set the property and return. Hope the framework can deal with it.
3310 */
3311 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003312 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003313 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003314
3315error_unencrypted:
3316 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003317 if (lockid[0]) {
3318 release_wake_lock(lockid);
3319 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003320 return -1;
3321
3322error_shutting_down:
3323 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3324 * but the framework is stopped and not restarted to show the error, so it's up to
3325 * vold to restart the system.
3326 */
3327 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003328 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003329
3330 /* shouldn't get here */
3331 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003332 if (lockid[0]) {
3333 release_wake_lock(lockid);
3334 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003335 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003336}
3337
Paul Lawrence569649f2015-09-09 12:13:00 -07003338int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003339{
Paul Lawrence569649f2015-09-09 12:13:00 -07003340 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003341}
3342
Paul Lawrence569649f2015-09-09 12:13:00 -07003343int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003344{
3345 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07003346 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003347}
3348
3349int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003350{
Paul Crowley38132a12016-02-09 09:50:32 +00003351 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003352 SLOGE("cryptfs_changepw not valid for file encryption");
3353 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003354 }
3355
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003356 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003357 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003358
3359 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003360 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003361 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003362 return -1;
3363 }
3364
Paul Lawrencef4faa572014-01-29 13:31:03 -08003365 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3366 SLOGE("Invalid crypt_type %d", crypt_type);
3367 return -1;
3368 }
3369
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003370 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003371 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003372 SLOGE("Error getting crypt footer and key");
3373 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003374 }
3375
Paul Lawrencef4faa572014-01-29 13:31:03 -08003376 crypt_ftr.crypt_type = crypt_type;
3377
JP Abgrall933216c2015-02-11 13:44:32 -08003378 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003379 : newpw,
3380 crypt_ftr.salt,
3381 saved_master_key,
3382 crypt_ftr.master_key,
3383 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003384 if (rc) {
3385 SLOGE("Encrypt master key failed: %d", rc);
3386 return -1;
3387 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003388 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003389 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003390
Ajay Dudani87701e22014-09-17 21:02:52 -07003391#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003392 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3393 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3394 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3395 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3396 if (!rc)
3397 return -1;
3398 } else {
3399 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3400 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3401 if (!rc)
3402 return -1;
3403 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003404 }
3405#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003406 return 0;
3407}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003408
Rubin Xu85c01f92014-10-13 12:49:54 +01003409static unsigned int persist_get_max_entries(int encrypted) {
3410 struct crypt_mnt_ftr crypt_ftr;
3411 unsigned int dsize;
3412 unsigned int max_persistent_entries;
3413
3414 /* If encrypted, use the values from the crypt_ftr, otherwise
3415 * use the values for the current spec.
3416 */
3417 if (encrypted) {
3418 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3419 return -1;
3420 }
3421 dsize = crypt_ftr.persist_data_size;
3422 } else {
3423 dsize = CRYPT_PERSIST_DATA_SIZE;
3424 }
3425
3426 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3427 sizeof(struct crypt_persist_entry);
3428
3429 return max_persistent_entries;
3430}
3431
3432static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003433{
3434 unsigned int i;
3435
3436 if (persist_data == NULL) {
3437 return -1;
3438 }
3439 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3440 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3441 /* We found it! */
3442 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3443 return 0;
3444 }
3445 }
3446
3447 return -1;
3448}
3449
Rubin Xu85c01f92014-10-13 12:49:54 +01003450static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003451{
3452 unsigned int i;
3453 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003454 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003455
3456 if (persist_data == NULL) {
3457 return -1;
3458 }
3459
Rubin Xu85c01f92014-10-13 12:49:54 +01003460 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003461
3462 num = persist_data->persist_valid_entries;
3463
3464 for (i = 0; i < num; i++) {
3465 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3466 /* We found an existing entry, update it! */
3467 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3468 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3469 return 0;
3470 }
3471 }
3472
3473 /* We didn't find it, add it to the end, if there is room */
3474 if (persist_data->persist_valid_entries < max_persistent_entries) {
3475 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3476 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3477 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3478 persist_data->persist_valid_entries++;
3479 return 0;
3480 }
3481
3482 return -1;
3483}
3484
Rubin Xu85c01f92014-10-13 12:49:54 +01003485/**
3486 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3487 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3488 */
3489static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003490 unsigned int field_len;
3491 unsigned int key_index;
3492 field_len = strlen(field);
3493
3494 if (index == 0) {
3495 // The first key in a multi-entry field is just the filedname itself.
3496 if (!strcmp(key, field)) {
3497 return 1;
3498 }
3499 }
3500 // Match key against "%s_%d" % (field, index)
3501 if (strlen(key) < field_len + 1 + 1) {
3502 // Need at least a '_' and a digit.
3503 return 0;
3504 }
3505 if (strncmp(key, field, field_len)) {
3506 // If the key does not begin with field, it's not a match.
3507 return 0;
3508 }
3509 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3510 return 0;
3511 }
3512 return key_index >= index;
3513}
3514
3515/*
3516 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3517 * remaining entries starting from index will be deleted.
3518 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3519 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3520 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3521 *
3522 */
3523static int persist_del_keys(const char *fieldname, unsigned index)
3524{
3525 unsigned int i;
3526 unsigned int j;
3527 unsigned int num;
3528
3529 if (persist_data == NULL) {
3530 return PERSIST_DEL_KEY_ERROR_OTHER;
3531 }
3532
3533 num = persist_data->persist_valid_entries;
3534
3535 j = 0; // points to the end of non-deleted entries.
3536 // Filter out to-be-deleted entries in place.
3537 for (i = 0; i < num; i++) {
3538 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3539 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3540 j++;
3541 }
3542 }
3543
3544 if (j < num) {
3545 persist_data->persist_valid_entries = j;
3546 // Zeroise the remaining entries
3547 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3548 return PERSIST_DEL_KEY_OK;
3549 } else {
3550 // Did not find an entry matching the given fieldname
3551 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3552 }
3553}
3554
3555static int persist_count_keys(const char *fieldname)
3556{
3557 unsigned int i;
3558 unsigned int count;
3559
3560 if (persist_data == NULL) {
3561 return -1;
3562 }
3563
3564 count = 0;
3565 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3566 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3567 count++;
3568 }
3569 }
3570
3571 return count;
3572}
3573
Ken Sumrall160b4d62013-04-22 12:15:39 -07003574/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003575int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003576{
Paul Crowley38132a12016-02-09 09:50:32 +00003577 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003578 SLOGE("Cannot get field when file encrypted");
3579 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003580 }
3581
Ken Sumrall160b4d62013-04-22 12:15:39 -07003582 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003583 /* CRYPTO_GETFIELD_OK is success,
3584 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3585 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3586 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003587 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003588 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3589 int i;
3590 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003591
3592 if (persist_data == NULL) {
3593 load_persistent_data();
3594 if (persist_data == NULL) {
3595 SLOGE("Getfield error, cannot load persistent data");
3596 goto out;
3597 }
3598 }
3599
Rubin Xu85c01f92014-10-13 12:49:54 +01003600 // Read value from persistent entries. If the original value is split into multiple entries,
3601 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003602 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003603 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3604 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3605 // value too small
3606 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3607 goto out;
3608 }
3609 rc = CRYPTO_GETFIELD_OK;
3610
3611 for (i = 1; /* break explicitly */; i++) {
3612 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3613 (int) sizeof(temp_field)) {
3614 // If the fieldname is very long, we stop as soon as it begins to overflow the
3615 // maximum field length. At this point we have in fact fully read out the original
3616 // value because cryptfs_setfield would not allow fields with longer names to be
3617 // written in the first place.
3618 break;
3619 }
3620 if (!persist_get_key(temp_field, temp_value)) {
3621 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3622 // value too small.
3623 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3624 goto out;
3625 }
3626 } else {
3627 // Exhaust all entries.
3628 break;
3629 }
3630 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003631 } else {
3632 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003633 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003634 }
3635
3636out:
3637 return rc;
3638}
3639
3640/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003641int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003642{
Paul Crowley38132a12016-02-09 09:50:32 +00003643 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003644 SLOGE("Cannot set field when file encrypted");
3645 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003646 }
3647
Ken Sumrall160b4d62013-04-22 12:15:39 -07003648 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003649 /* 0 is success, negative values are error */
3650 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003651 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003652 unsigned int field_id;
3653 char temp_field[PROPERTY_KEY_MAX];
3654 unsigned int num_entries;
3655 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003656
3657 if (persist_data == NULL) {
3658 load_persistent_data();
3659 if (persist_data == NULL) {
3660 SLOGE("Setfield error, cannot load persistent data");
3661 goto out;
3662 }
3663 }
3664
3665 property_get("ro.crypto.state", encrypted_state, "");
3666 if (!strcmp(encrypted_state, "encrypted") ) {
3667 encrypted = 1;
3668 }
3669
Rubin Xu85c01f92014-10-13 12:49:54 +01003670 // Compute the number of entries required to store value, each entry can store up to
3671 // (PROPERTY_VALUE_MAX - 1) chars
3672 if (strlen(value) == 0) {
3673 // Empty value also needs one entry to store.
3674 num_entries = 1;
3675 } else {
3676 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3677 }
3678
3679 max_keylen = strlen(fieldname);
3680 if (num_entries > 1) {
3681 // Need an extra "_%d" suffix.
3682 max_keylen += 1 + log10(num_entries);
3683 }
3684 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3685 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003686 goto out;
3687 }
3688
Rubin Xu85c01f92014-10-13 12:49:54 +01003689 // Make sure we have enough space to write the new value
3690 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3691 persist_get_max_entries(encrypted)) {
3692 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3693 goto out;
3694 }
3695
3696 // Now that we know persist_data has enough space for value, let's delete the old field first
3697 // to make up space.
3698 persist_del_keys(fieldname, 0);
3699
3700 if (persist_set_key(fieldname, value, encrypted)) {
3701 // fail to set key, should not happen as we have already checked the available space
3702 SLOGE("persist_set_key() error during setfield()");
3703 goto out;
3704 }
3705
3706 for (field_id = 1; field_id < num_entries; field_id++) {
3707 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3708
3709 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3710 // fail to set key, should not happen as we have already checked the available space.
3711 SLOGE("persist_set_key() error during setfield()");
3712 goto out;
3713 }
3714 }
3715
Ken Sumrall160b4d62013-04-22 12:15:39 -07003716 /* If we are running encrypted, save the persistent data now */
3717 if (encrypted) {
3718 if (save_persistent_data()) {
3719 SLOGE("Setfield error, cannot save persistent data");
3720 goto out;
3721 }
3722 }
3723
Rubin Xu85c01f92014-10-13 12:49:54 +01003724 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003725
3726out:
3727 return rc;
3728}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003729
3730/* Checks userdata. Attempt to mount the volume if default-
3731 * encrypted.
3732 * On success trigger next init phase and return 0.
3733 * Currently do not handle failure - see TODO below.
3734 */
3735int cryptfs_mount_default_encrypted(void)
3736{
3737 char decrypt_state[PROPERTY_VALUE_MAX];
3738 property_get("vold.decrypt", decrypt_state, "0");
3739 if (!strcmp(decrypt_state, "0")) {
3740 SLOGE("Not encrypted - should not call here");
3741 } else {
3742 int crypt_type = cryptfs_get_password_type();
3743 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3744 SLOGE("Bad crypt type - error");
3745 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3746 SLOGD("Password is not default - "
3747 "starting min framework to prompt");
3748 property_set("vold.decrypt", "trigger_restart_min_framework");
3749 return 0;
3750 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3751 SLOGD("Password is default - restarting filesystem");
3752 cryptfs_restart_internal(0);
3753 return 0;
3754 } else {
3755 SLOGE("Encrypted, default crypt type but can't decrypt");
3756 }
3757 }
3758
Paul Lawrence6bfed202014-07-28 12:47:22 -07003759 /** Corrupt. Allow us to boot into framework, which will detect bad
3760 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003761 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003762 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003763 return 0;
3764}
3765
3766/* Returns type of the password, default, pattern, pin or password.
3767 */
3768int cryptfs_get_password_type(void)
3769{
Paul Crowley38132a12016-02-09 09:50:32 +00003770 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003771 SLOGE("cryptfs_get_password_type not valid for file encryption");
3772 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003773 }
3774
Paul Lawrencef4faa572014-01-29 13:31:03 -08003775 struct crypt_mnt_ftr crypt_ftr;
3776
3777 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3778 SLOGE("Error getting crypt footer and key\n");
3779 return -1;
3780 }
3781
Paul Lawrence6bfed202014-07-28 12:47:22 -07003782 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3783 return -1;
3784 }
3785
Paul Lawrencef4faa572014-01-29 13:31:03 -08003786 return crypt_ftr.crypt_type;
3787}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003788
Paul Lawrence05335c32015-03-05 09:46:23 -08003789const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003790{
Paul Crowley38132a12016-02-09 09:50:32 +00003791 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003792 SLOGE("cryptfs_get_password not valid for file encryption");
3793 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003794 }
3795
Paul Lawrence399317e2014-03-10 13:20:50 -07003796 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003797 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003798 if (now.tv_sec < password_expiry_time) {
3799 return password;
3800 } else {
3801 cryptfs_clear_password();
3802 return 0;
3803 }
3804}
3805
3806void cryptfs_clear_password()
3807{
3808 if (password) {
3809 size_t len = strlen(password);
3810 memset(password, 0, len);
3811 free(password);
3812 password = 0;
3813 password_expiry_time = 0;
3814 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003815}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003816
3817int cryptfs_enable_file()
3818{
Paul Crowley38132a12016-02-09 09:50:32 +00003819 return e4crypt_initialize_global_de();
Paul Lawrence731a7a22015-04-28 22:14:15 +00003820}
3821
Paul Lawrence0c247462015-10-29 10:30:57 -07003822int cryptfs_isConvertibleToFBE()
3823{
3824 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3825 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
3826}
3827
Paul Lawrence731a7a22015-04-28 22:14:15 +00003828int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3829{
3830 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3831 SLOGE("Failed to initialize crypt_ftr");
3832 return -1;
3833 }
3834
3835 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3836 crypt_ftr->salt, crypt_ftr)) {
3837 SLOGE("Cannot create encrypted master key\n");
3838 return -1;
3839 }
3840
3841 //crypt_ftr->keysize = key_length / 8;
3842 return 0;
3843}
3844
3845int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3846 unsigned char* master_key)
3847{
3848 int rc;
3849
Paul Lawrence731a7a22015-04-28 22:14:15 +00003850 unsigned char* intermediate_key = 0;
3851 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003852
3853 if (password == 0 || *password == 0) {
3854 password = DEFAULT_PASSWORD;
3855 }
3856
Paul Lawrence731a7a22015-04-28 22:14:15 +00003857 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3858 &intermediate_key_size);
3859
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003860 int N = 1 << ftr->N_factor;
3861 int r = 1 << ftr->r_factor;
3862 int p = 1 << ftr->p_factor;
3863
3864 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3865
3866 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3867 ftr->salt, sizeof(ftr->salt), N, r, p,
3868 scrypted_intermediate_key,
3869 sizeof(scrypted_intermediate_key));
3870
3871 free(intermediate_key);
3872
3873 if (rc) {
3874 SLOGE("Can't calculate intermediate key");
3875 return rc;
3876 }
3877
3878 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3879 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00003880}
3881
3882int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3883 const unsigned char* master_key)
3884{
3885 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3886 ftr);
3887}