blob: a1f17a85765360dc2c0c83d560c9ed19aa514302 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080041#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080046#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080047#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080048#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080049#define LOG_TAG "Cryptfs"
50#include "cutils/log.h"
51#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070052#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080053#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070054#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000055#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070056#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070057#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070058#include "crypto_scrypt.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000059#include "Ext4Crypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080060#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000061#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080062#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080063#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080064
Shawn Willden8af33352015-02-24 09:51:34 -070065#include <hardware/keymaster0.h>
Shawn Willdenda6e8992015-06-03 09:40:45 -060066#include <hardware/keymaster1.h>
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070067
Mark Salyzyn3e971272014-01-21 13:27:04 -080068#define UNUSED __attribute__((unused))
69
Mark Salyzyn5eecc442014-02-12 14:16:14 -080070#define UNUSED __attribute__((unused))
71
Ajay Dudani87701e22014-09-17 21:02:52 -070072#ifdef CONFIG_HW_DISK_ENCRYPTION
73#include "cryptfs_hw.h"
74#endif
75
Ken Sumrall8f869aa2010-12-03 03:47:09 -080076#define DM_CRYPT_BUF_SIZE 4096
77
Jason parks70a4b3f2011-01-28 10:10:47 -060078#define HASH_COUNT 2000
79#define KEY_LEN_BYTES 16
80#define IV_LEN_BYTES 16
81
Ken Sumrall29d8da82011-05-18 17:20:07 -070082#define KEY_IN_FOOTER "footer"
83
Paul Lawrence3bd36d52015-06-09 13:37:44 -070084#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080085
Paul Lawrence3d99eba2015-11-20 07:07:19 -080086#define CRYPTO_BLOCK_DEVICE "userdata"
87
88#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
89
Ken Sumrall29d8da82011-05-18 17:20:07 -070090#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070091#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070092
Ken Sumralle919efe2012-09-29 17:07:41 -070093#define TABLE_LOAD_RETRIES 10
94
Shawn Willden47ba10d2014-09-03 17:07:06 -060095#define RSA_KEY_SIZE 2048
96#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
97#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060098#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070099
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700100#define RETRY_MOUNT_ATTEMPTS 10
101#define RETRY_MOUNT_DELAY_SECONDS 1
102
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800103char *me = "cryptfs";
104
Jason parks70a4b3f2011-01-28 10:10:47 -0600105static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700106static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600107static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700108static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800109
Shawn Willdenda6e8992015-06-03 09:40:45 -0600110static int keymaster_init(keymaster0_device_t **keymaster0_dev,
111 keymaster1_device_t **keymaster1_dev)
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700112{
113 int rc;
114
115 const hw_module_t* mod;
116 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
117 if (rc) {
118 ALOGE("could not find any keystore module");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600119 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700120 }
121
Shawn Willdenda6e8992015-06-03 09:40:45 -0600122 SLOGI("keymaster module name is %s", mod->name);
123 SLOGI("keymaster version is %d", mod->module_api_version);
124
125 *keymaster0_dev = NULL;
126 *keymaster1_dev = NULL;
127 if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
128 SLOGI("Found keymaster1 module, using keymaster1 API.");
129 rc = keymaster1_open(mod, keymaster1_dev);
130 } else {
131 SLOGI("Found keymaster0 module, using keymaster0 API.");
132 rc = keymaster0_open(mod, keymaster0_dev);
133 }
134
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700135 if (rc) {
136 ALOGE("could not open keymaster device in %s (%s)",
Shawn Willdenda6e8992015-06-03 09:40:45 -0600137 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
138 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700139 }
140
141 return 0;
142
Shawn Willdenda6e8992015-06-03 09:40:45 -0600143err:
144 *keymaster0_dev = NULL;
145 *keymaster1_dev = NULL;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700146 return rc;
147}
148
149/* Should we use keymaster? */
150static int keymaster_check_compatibility()
151{
Shawn Willdenda6e8992015-06-03 09:40:45 -0600152 keymaster0_device_t *keymaster0_dev = 0;
153 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700154 int rc = 0;
155
Shawn Willdenda6e8992015-06-03 09:40:45 -0600156 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700157 SLOGE("Failed to init keymaster");
158 rc = -1;
159 goto out;
160 }
161
Shawn Willdenda6e8992015-06-03 09:40:45 -0600162 if (keymaster1_dev) {
163 rc = 1;
164 goto out;
165 }
Paul Lawrence8c008392014-05-06 14:02:48 -0700166
Paul Lawrence300dae72016-03-11 11:02:52 -0800167 if (!keymaster0_dev || !keymaster0_dev->common.module) {
168 rc = -1;
169 goto out;
170 }
171
Shawn Willdenda6e8992015-06-03 09:40:45 -0600172 // TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
173 // should work.
174 if (keymaster0_dev->common.module->module_api_version
Paul Lawrence8c008392014-05-06 14:02:48 -0700175 < KEYMASTER_MODULE_API_VERSION_0_3) {
176 rc = 0;
177 goto out;
178 }
179
Shawn Willdenda6e8992015-06-03 09:40:45 -0600180 if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
181 (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700182 rc = 1;
183 }
184
185out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600186 if (keymaster1_dev) {
187 keymaster1_close(keymaster1_dev);
188 }
189 if (keymaster0_dev) {
190 keymaster0_close(keymaster0_dev);
191 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700192 return rc;
193}
194
195/* Create a new keymaster key and store it in this footer */
196static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
197{
198 uint8_t* key = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600199 keymaster0_device_t *keymaster0_dev = 0;
200 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700201
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800202 if (ftr->keymaster_blob_size) {
203 SLOGI("Already have key");
204 return 0;
205 }
206
Shawn Willdenda6e8992015-06-03 09:40:45 -0600207 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700208 SLOGE("Failed to init keymaster");
209 return -1;
210 }
211
212 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600213 size_t key_size = 0;
214 if (keymaster1_dev) {
215 keymaster_key_param_t params[] = {
216 /* Algorithm & size specifications. Stick with RSA for now. Switch to AES later. */
217 keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
218 keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
219 keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700220
Shawn Willden86af3552015-06-24 07:21:54 -0700221 /* The only allowed purpose for this key is signing. */
222 keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
223
224 /* Padding & digest specifications. */
Shawn Willdenda6e8992015-06-03 09:40:45 -0600225 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
Shawn Willdenda6e8992015-06-03 09:40:45 -0600226 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700227
Shawn Willdenda6e8992015-06-03 09:40:45 -0600228 /* Require that the key be usable in standalone mode. File system isn't available. */
229 keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
230
231 /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
232 keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
233
Shawn Willdenda6e8992015-06-03 09:40:45 -0600234 /* Rate-limit key usage attempts, to rate-limit brute force */
235 keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
236 };
237 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
238 keymaster_key_blob_t key_blob;
239 keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, &param_set,
240 &key_blob,
241 NULL /* characteristics */);
242 if (error != KM_ERROR_OK) {
243 SLOGE("Failed to generate keymaster1 key, error %d", error);
244 rc = -1;
245 goto out;
246 }
247
248 key = (uint8_t*)key_blob.key_material;
249 key_size = key_blob.key_material_size;
250 }
251 else if (keymaster0_dev) {
252 keymaster_rsa_keygen_params_t params;
253 memset(&params, '\0', sizeof(params));
254 params.public_exponent = RSA_EXPONENT;
255 params.modulus_size = RSA_KEY_SIZE;
256
257 if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, &params,
258 &key, &key_size)) {
259 SLOGE("Failed to generate keypair");
260 rc = -1;
261 goto out;
262 }
263 } else {
264 SLOGE("Cryptfs bug: keymaster_init succeeded but didn't initialize a device");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700265 rc = -1;
266 goto out;
267 }
268
269 if (key_size > KEYMASTER_BLOB_SIZE) {
270 SLOGE("Keymaster key too large for crypto footer");
271 rc = -1;
272 goto out;
273 }
274
275 memcpy(ftr->keymaster_blob, key, key_size);
276 ftr->keymaster_blob_size = key_size;
277
278out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600279 if (keymaster0_dev)
280 keymaster0_close(keymaster0_dev);
281 if (keymaster1_dev)
282 keymaster1_close(keymaster1_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700283 free(key);
284 return rc;
285}
286
Shawn Willdene17a9c42014-09-08 13:04:08 -0600287/* This signs the given object using the keymaster key. */
288static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600289 const unsigned char *object,
290 const size_t object_size,
291 unsigned char **signature,
292 size_t *signature_size)
293{
294 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600295 keymaster0_device_t *keymaster0_dev = 0;
296 keymaster1_device_t *keymaster1_dev = 0;
297 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600298 SLOGE("Failed to init keymaster");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600299 rc = -1;
300 goto out;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600301 }
302
Shawn Willden47ba10d2014-09-03 17:07:06 -0600303 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600304 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600305 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600306
Shawn Willdene17a9c42014-09-08 13:04:08 -0600307 // To sign a message with RSA, the message must satisfy two
308 // constraints:
309 //
310 // 1. The message, when interpreted as a big-endian numeric value, must
311 // be strictly less than the public modulus of the RSA key. Note
312 // that because the most significant bit of the public modulus is
313 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
314 // key), an n-bit message with most significant bit 0 always
315 // satisfies this requirement.
316 //
317 // 2. The message must have the same length in bits as the public
318 // modulus of the RSA key. This requirement isn't mathematically
319 // necessary, but is necessary to ensure consistency in
320 // implementations.
321 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600322 case KDF_SCRYPT_KEYMASTER:
323 // This ensures the most significant byte of the signed message
324 // is zero. We could have zero-padded to the left instead, but
325 // this approach is slightly more robust against changes in
326 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600327 // so) because we really should be using a proper deterministic
328 // RSA padding function, such as PKCS1.
Shawn Willdene17a9c42014-09-08 13:04:08 -0600329 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
330 SLOGI("Signing safely-padded object");
331 break;
332 default:
333 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Shawn Willdenda6e8992015-06-03 09:40:45 -0600334 rc = -1;
335 goto out;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600336 }
337
Shawn Willdenda6e8992015-06-03 09:40:45 -0600338 if (keymaster0_dev) {
339 keymaster_rsa_sign_params_t params;
340 params.digest_type = DIGEST_NONE;
341 params.padding_type = PADDING_NONE;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600342
Shawn Willdenda6e8992015-06-03 09:40:45 -0600343 rc = keymaster0_dev->sign_data(keymaster0_dev,
344 &params,
345 ftr->keymaster_blob,
346 ftr->keymaster_blob_size,
347 to_sign,
348 to_sign_size,
349 signature,
350 signature_size);
351 goto out;
352 } else if (keymaster1_dev) {
353 keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
354 keymaster_key_param_t params[] = {
355 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
356 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
357 };
358 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
359 keymaster_operation_handle_t op_handle;
360 keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
361 &param_set, NULL /* out_params */,
362 &op_handle);
Shawn Willden04170602015-06-18 12:26:59 -0600363 if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
Shawn Willdenda6e8992015-06-03 09:40:45 -0600364 // Key usage has been rate-limited. Wait a bit and try again.
365 sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
366 error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
367 &param_set, NULL /* out_params */,
368 &op_handle);
369 }
370 if (error != KM_ERROR_OK) {
371 SLOGE("Error starting keymaster signature transaction: %d", error);
372 rc = -1;
373 goto out;
374 }
375
376 keymaster_blob_t input = { to_sign, to_sign_size };
377 size_t input_consumed;
378 error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
379 &input, &input_consumed, NULL /* out_params */,
380 NULL /* output */);
381 if (error != KM_ERROR_OK) {
382 SLOGE("Error sending data to keymaster signature transaction: %d", error);
383 rc = -1;
384 goto out;
385 }
386 if (input_consumed != to_sign_size) {
387 // This should never happen. If it does, it's a bug in the keymaster implementation.
388 SLOGE("Keymaster update() did not consume all data.");
389 keymaster1_dev->abort(keymaster1_dev, op_handle);
390 rc = -1;
391 goto out;
392 }
393
394 keymaster_blob_t tmp_sig;
395 error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
396 NULL /* verify signature */, NULL /* out_params */,
397 &tmp_sig);
398 if (error != KM_ERROR_OK) {
399 SLOGE("Error finishing keymaster signature transaction: %d", error);
400 rc = -1;
401 goto out;
402 }
403
404 *signature = (uint8_t*)tmp_sig.data;
405 *signature_size = tmp_sig.data_length;
406 } else {
407 SLOGE("Cryptfs bug: keymaster_init succeded but didn't initialize a device.");
408 rc = -1;
409 goto out;
410 }
411
412 out:
413 if (keymaster1_dev)
414 keymaster1_close(keymaster1_dev);
415 if (keymaster0_dev)
416 keymaster0_close(keymaster0_dev);
417
418 return rc;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600419}
420
Paul Lawrence399317e2014-03-10 13:20:50 -0700421/* Store password when userdata is successfully decrypted and mounted.
422 * Cleared by cryptfs_clear_password
423 *
424 * To avoid a double prompt at boot, we need to store the CryptKeeper
425 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
426 * Since the entire framework is torn down and rebuilt after encryption,
427 * we have to use a daemon or similar to store the password. Since vold
428 * is secured against IPC except from system processes, it seems a reasonable
429 * place to store this.
430 *
431 * password should be cleared once it has been used.
432 *
433 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800434 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700435static char* password = 0;
436static int password_expiry_time = 0;
437static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800438
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800439extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800440
Paul Lawrence87999172014-02-20 12:21:31 -0800441enum RebootType {reboot, recovery, shutdown};
442static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700443{
Paul Lawrence87999172014-02-20 12:21:31 -0800444 switch(rt) {
445 case reboot:
446 property_set(ANDROID_RB_PROPERTY, "reboot");
447 break;
448
449 case recovery:
450 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
451 break;
452
453 case shutdown:
454 property_set(ANDROID_RB_PROPERTY, "shutdown");
455 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700456 }
Paul Lawrence87999172014-02-20 12:21:31 -0800457
Ken Sumralladfba362013-06-04 16:37:52 -0700458 sleep(20);
459
460 /* Shouldn't get here, reboot should happen before sleep times out */
461 return;
462}
463
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800464static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
465{
466 memset(io, 0, dataSize);
467 io->data_size = dataSize;
468 io->data_start = sizeof(struct dm_ioctl);
469 io->version[0] = 4;
470 io->version[1] = 0;
471 io->version[2] = 0;
472 io->flags = flags;
473 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100474 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800475 }
476}
477
Kenny Rootc4c70f12013-06-14 12:11:38 -0700478/**
479 * Gets the default device scrypt parameters for key derivation time tuning.
480 * The parameters should lead to about one second derivation time for the
481 * given device.
482 */
483static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700484 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000485 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700486
Paul Crowley63c18d32016-02-10 14:02:47 +0000487 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
488 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
489 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
490 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700491 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000492 ftr->N_factor = Nf;
493 ftr->r_factor = rf;
494 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700495}
496
Ken Sumrall3ed82362011-01-28 23:31:16 -0800497static unsigned int get_fs_size(char *dev)
498{
499 int fd, block_size;
500 struct ext4_super_block sb;
501 off64_t len;
502
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700503 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800504 SLOGE("Cannot open device to get filesystem size ");
505 return 0;
506 }
507
508 if (lseek64(fd, 1024, SEEK_SET) < 0) {
509 SLOGE("Cannot seek to superblock");
510 return 0;
511 }
512
513 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
514 SLOGE("Cannot read superblock");
515 return 0;
516 }
517
518 close(fd);
519
Daniel Rosenberge82df162014-08-15 22:19:23 +0000520 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
521 SLOGE("Not a valid ext4 superblock");
522 return 0;
523 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800524 block_size = 1024 << sb.s_log_block_size;
525 /* compute length in bytes */
526 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
527
528 /* return length in sectors */
529 return (unsigned int) (len / 512);
530}
531
Ken Sumrall160b4d62013-04-22 12:15:39 -0700532static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
533{
534 static int cached_data = 0;
535 static off64_t cached_off = 0;
536 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
537 int fd;
538 char key_loc[PROPERTY_VALUE_MAX];
539 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700540 int rc = -1;
541
542 if (!cached_data) {
543 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
544
545 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700546 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700547 SLOGE("Cannot open real block device %s\n", real_blkdev);
548 return -1;
549 }
550
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900551 unsigned long nr_sec = 0;
552 get_blkdev_size(fd, &nr_sec);
553 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700554 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
555 * encryption info footer and key, and plenty of bytes to spare for future
556 * growth.
557 */
558 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
559 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
560 cached_data = 1;
561 } else {
562 SLOGE("Cannot get size of block device %s\n", real_blkdev);
563 }
564 close(fd);
565 } else {
566 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
567 cached_off = 0;
568 cached_data = 1;
569 }
570 }
571
572 if (cached_data) {
573 if (metadata_fname) {
574 *metadata_fname = cached_metadata_fname;
575 }
576 if (off) {
577 *off = cached_off;
578 }
579 rc = 0;
580 }
581
582 return rc;
583}
584
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800585/* Set sha256 checksum in structure */
586static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
587{
588 SHA256_CTX c;
589 SHA256_Init(&c);
590 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
591 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
592 SHA256_Final(crypt_ftr->sha256, &c);
593}
594
Ken Sumralle8744072011-01-18 22:01:55 -0800595/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800596 * update the failed mount count but not change the key.
597 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700598static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800599{
600 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800601 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700602 /* starting_off is set to the SEEK_SET offset
603 * where the crypto structure starts
604 */
605 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800606 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700607 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700608 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800609
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800610 set_ftr_sha(crypt_ftr);
611
Ken Sumrall160b4d62013-04-22 12:15:39 -0700612 if (get_crypt_ftr_info(&fname, &starting_off)) {
613 SLOGE("Unable to get crypt_ftr_info\n");
614 return -1;
615 }
616 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700617 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700618 return -1;
619 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700620 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700621 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700622 return -1;
623 }
624
625 /* Seek to the start of the crypt footer */
626 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
627 SLOGE("Cannot seek to real block device footer\n");
628 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800629 }
630
631 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
632 SLOGE("Cannot write real block device footer\n");
633 goto errout;
634 }
635
Ken Sumrall3be890f2011-09-14 16:53:46 -0700636 fstat(fd, &statbuf);
637 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700638 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700639 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800640 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800641 goto errout;
642 }
643 }
644
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800645 /* Success! */
646 rc = 0;
647
648errout:
649 close(fd);
650 return rc;
651
652}
653
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800654static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
655{
656 struct crypt_mnt_ftr copy;
657 memcpy(&copy, crypt_ftr, sizeof(copy));
658 set_ftr_sha(&copy);
659 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
660}
661
Ken Sumrall160b4d62013-04-22 12:15:39 -0700662static inline int unix_read(int fd, void* buff, int len)
663{
664 return TEMP_FAILURE_RETRY(read(fd, buff, len));
665}
666
667static inline int unix_write(int fd, const void* buff, int len)
668{
669 return TEMP_FAILURE_RETRY(write(fd, buff, len));
670}
671
672static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
673{
674 memset(pdata, 0, len);
675 pdata->persist_magic = PERSIST_DATA_MAGIC;
676 pdata->persist_valid_entries = 0;
677}
678
679/* A routine to update the passed in crypt_ftr to the lastest version.
680 * fd is open read/write on the device that holds the crypto footer and persistent
681 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
682 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
683 */
684static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
685{
Kenny Root7434b312013-06-14 11:29:53 -0700686 int orig_major = crypt_ftr->major_version;
687 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700688
Kenny Root7434b312013-06-14 11:29:53 -0700689 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
690 struct crypt_persist_data *pdata;
691 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700692
Kenny Rootc4c70f12013-06-14 12:11:38 -0700693 SLOGW("upgrading crypto footer to 1.1");
694
Kenny Root7434b312013-06-14 11:29:53 -0700695 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
696 if (pdata == NULL) {
697 SLOGE("Cannot allocate persisent data\n");
698 return;
699 }
700 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
701
702 /* Need to initialize the persistent data area */
703 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
704 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100705 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700706 return;
707 }
708 /* Write all zeros to the first copy, making it invalid */
709 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
710
711 /* Write a valid but empty structure to the second copy */
712 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
713 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
714
715 /* Update the footer */
716 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
717 crypt_ftr->persist_data_offset[0] = pdata_offset;
718 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
719 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100720 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700721 }
722
Paul Lawrencef4faa572014-01-29 13:31:03 -0800723 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700724 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800725 /* But keep the old kdf_type.
726 * It will get updated later to KDF_SCRYPT after the password has been verified.
727 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700728 crypt_ftr->kdf_type = KDF_PBKDF2;
729 get_device_scrypt_params(crypt_ftr);
730 crypt_ftr->minor_version = 2;
731 }
732
Paul Lawrencef4faa572014-01-29 13:31:03 -0800733 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
734 SLOGW("upgrading crypto footer to 1.3");
735 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
736 crypt_ftr->minor_version = 3;
737 }
738
Kenny Root7434b312013-06-14 11:29:53 -0700739 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
740 if (lseek64(fd, offset, SEEK_SET) == -1) {
741 SLOGE("Cannot seek to crypt footer\n");
742 return;
743 }
744 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700745 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700746}
747
748
749static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800750{
751 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800752 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700753 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800754 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700755 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700756 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800757
Ken Sumrall160b4d62013-04-22 12:15:39 -0700758 if (get_crypt_ftr_info(&fname, &starting_off)) {
759 SLOGE("Unable to get crypt_ftr_info\n");
760 return -1;
761 }
762 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700763 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700764 return -1;
765 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700766 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700767 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700768 return -1;
769 }
770
771 /* Make sure it's 16 Kbytes in length */
772 fstat(fd, &statbuf);
773 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
774 SLOGE("footer file %s is not the expected size!\n", fname);
775 goto errout;
776 }
777
778 /* Seek to the start of the crypt footer */
779 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
780 SLOGE("Cannot seek to real block device footer\n");
781 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800782 }
783
784 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
785 SLOGE("Cannot read real block device footer\n");
786 goto errout;
787 }
788
789 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700790 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800791 goto errout;
792 }
793
Kenny Rootc96a5f82013-06-14 12:08:28 -0700794 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
795 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
796 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800797 goto errout;
798 }
799
Kenny Rootc96a5f82013-06-14 12:08:28 -0700800 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
801 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
802 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800803 }
804
Ken Sumrall160b4d62013-04-22 12:15:39 -0700805 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
806 * copy on disk before returning.
807 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700808 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700809 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800810 }
811
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800812 /* Success! */
813 rc = 0;
814
815errout:
816 close(fd);
817 return rc;
818}
819
Ken Sumrall160b4d62013-04-22 12:15:39 -0700820static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
821{
822 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
823 crypt_ftr->persist_data_offset[1]) {
824 SLOGE("Crypt_ftr persist data regions overlap");
825 return -1;
826 }
827
828 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
829 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
830 return -1;
831 }
832
833 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
834 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
835 CRYPT_FOOTER_OFFSET) {
836 SLOGE("Persistent data extends past crypto footer");
837 return -1;
838 }
839
840 return 0;
841}
842
843static int load_persistent_data(void)
844{
845 struct crypt_mnt_ftr crypt_ftr;
846 struct crypt_persist_data *pdata = NULL;
847 char encrypted_state[PROPERTY_VALUE_MAX];
848 char *fname;
849 int found = 0;
850 int fd;
851 int ret;
852 int i;
853
854 if (persist_data) {
855 /* Nothing to do, we've already loaded or initialized it */
856 return 0;
857 }
858
859
860 /* If not encrypted, just allocate an empty table and initialize it */
861 property_get("ro.crypto.state", encrypted_state, "");
862 if (strcmp(encrypted_state, "encrypted") ) {
863 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
864 if (pdata) {
865 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
866 persist_data = pdata;
867 return 0;
868 }
869 return -1;
870 }
871
872 if(get_crypt_ftr_and_key(&crypt_ftr)) {
873 return -1;
874 }
875
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700876 if ((crypt_ftr.major_version < 1)
877 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700878 SLOGE("Crypt_ftr version doesn't support persistent data");
879 return -1;
880 }
881
882 if (get_crypt_ftr_info(&fname, NULL)) {
883 return -1;
884 }
885
886 ret = validate_persistent_data_storage(&crypt_ftr);
887 if (ret) {
888 return -1;
889 }
890
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700891 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700892 if (fd < 0) {
893 SLOGE("Cannot open %s metadata file", fname);
894 return -1;
895 }
896
Paul Lawrence300dae72016-03-11 11:02:52 -0800897 pdata = malloc(crypt_ftr.persist_data_size);
898 if (pdata == NULL) {
899 SLOGE("Cannot allocate memory for persistent data");
900 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700901 }
902
903 for (i = 0; i < 2; i++) {
904 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
905 SLOGE("Cannot seek to read persistent data on %s", fname);
906 goto err2;
907 }
908 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
909 SLOGE("Error reading persistent data on iteration %d", i);
910 goto err2;
911 }
912 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
913 found = 1;
914 break;
915 }
916 }
917
918 if (!found) {
919 SLOGI("Could not find valid persistent data, creating");
920 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
921 }
922
923 /* Success */
924 persist_data = pdata;
925 close(fd);
926 return 0;
927
928err2:
929 free(pdata);
930
931err:
932 close(fd);
933 return -1;
934}
935
936static int save_persistent_data(void)
937{
938 struct crypt_mnt_ftr crypt_ftr;
939 struct crypt_persist_data *pdata;
940 char *fname;
941 off64_t write_offset;
942 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700943 int fd;
944 int ret;
945
946 if (persist_data == NULL) {
947 SLOGE("No persistent data to save");
948 return -1;
949 }
950
951 if(get_crypt_ftr_and_key(&crypt_ftr)) {
952 return -1;
953 }
954
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700955 if ((crypt_ftr.major_version < 1)
956 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700957 SLOGE("Crypt_ftr version doesn't support persistent data");
958 return -1;
959 }
960
961 ret = validate_persistent_data_storage(&crypt_ftr);
962 if (ret) {
963 return -1;
964 }
965
966 if (get_crypt_ftr_info(&fname, NULL)) {
967 return -1;
968 }
969
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700970 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700971 if (fd < 0) {
972 SLOGE("Cannot open %s metadata file", fname);
973 return -1;
974 }
975
976 pdata = malloc(crypt_ftr.persist_data_size);
977 if (pdata == NULL) {
978 SLOGE("Cannot allocate persistant data");
979 goto err;
980 }
981
982 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
983 SLOGE("Cannot seek to read persistent data on %s", fname);
984 goto err2;
985 }
986
987 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
988 SLOGE("Error reading persistent data before save");
989 goto err2;
990 }
991
992 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
993 /* The first copy is the curent valid copy, so write to
994 * the second copy and erase this one */
995 write_offset = crypt_ftr.persist_data_offset[1];
996 erase_offset = crypt_ftr.persist_data_offset[0];
997 } else {
998 /* The second copy must be the valid copy, so write to
999 * the first copy, and erase the second */
1000 write_offset = crypt_ftr.persist_data_offset[0];
1001 erase_offset = crypt_ftr.persist_data_offset[1];
1002 }
1003
1004 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001005 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001006 SLOGE("Cannot seek to write persistent data");
1007 goto err2;
1008 }
1009 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1010 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001011 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001012 SLOGE("Cannot seek to erase previous persistent data");
1013 goto err2;
1014 }
1015 fsync(fd);
1016 memset(pdata, 0, crypt_ftr.persist_data_size);
1017 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
1018 (int) crypt_ftr.persist_data_size) {
1019 SLOGE("Cannot write to erase previous persistent data");
1020 goto err2;
1021 }
1022 fsync(fd);
1023 } else {
1024 SLOGE("Cannot write to save persistent data");
1025 goto err2;
1026 }
1027
1028 /* Success */
1029 free(pdata);
1030 close(fd);
1031 return 0;
1032
1033err2:
1034 free(pdata);
1035err:
1036 close(fd);
1037 return -1;
1038}
1039
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001040/* Convert a binary key of specified length into an ascii hex string equivalent,
1041 * without the leading 0x and with null termination
1042 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001043static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001044 unsigned int keysize, char *master_key_ascii) {
1045 unsigned int i, a;
1046 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001047
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001048 for (i=0, a=0; i<keysize; i++, a+=2) {
1049 /* For each byte, write out two ascii hex digits */
1050 nibble = (master_key[i] >> 4) & 0xf;
1051 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001052
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001053 nibble = master_key[i] & 0xf;
1054 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1055 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001056
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001057 /* Add the null termination */
1058 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001059
1060}
1061
Jeff Sharkey9c484982015-03-31 10:35:33 -07001062static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
1063 const unsigned char *master_key, const char *real_blk_name,
1064 const char *name, int fd, const char *extra_params) {
Dan Albertc07fa3f2014-12-18 10:00:55 -08001065 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001066 struct dm_ioctl *io;
1067 struct dm_target_spec *tgt;
1068 char *crypt_params;
1069 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1070 int i;
1071
1072 io = (struct dm_ioctl *) buffer;
1073
1074 /* Load the mapping table for this device */
1075 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1076
1077 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1078 io->target_count = 1;
1079 tgt->status = 0;
1080 tgt->sector_start = 0;
1081 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -07001082#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001083 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1084 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1085 }
1086 else {
1087 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1088 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001089#else
1090 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1091#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001092
1093 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1094 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1095 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1096 master_key_ascii, real_blk_name, extra_params);
1097 crypt_params += strlen(crypt_params) + 1;
1098 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1099 tgt->next = crypt_params - buffer;
1100
1101 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1102 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1103 break;
1104 }
1105 usleep(500000);
1106 }
1107
1108 if (i == TABLE_LOAD_RETRIES) {
1109 /* We failed to load the table, return an error */
1110 return -1;
1111 } else {
1112 return i + 1;
1113 }
1114}
1115
1116
1117static int get_dm_crypt_version(int fd, const char *name, int *version)
1118{
1119 char buffer[DM_CRYPT_BUF_SIZE];
1120 struct dm_ioctl *io;
1121 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001122
1123 io = (struct dm_ioctl *) buffer;
1124
1125 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1126
1127 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1128 return -1;
1129 }
1130
1131 /* Iterate over the returned versions, looking for name of "crypt".
1132 * When found, get and return the version.
1133 */
1134 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1135 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001136#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001137 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001138#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001139 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001140#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001141 /* We found the crypt driver, return the version, and get out */
1142 version[0] = v->version[0];
1143 version[1] = v->version[1];
1144 version[2] = v->version[2];
1145 return 0;
1146 }
1147 v = (struct dm_target_versions *)(((char *)v) + v->next);
1148 }
1149
1150 return -1;
1151}
1152
Jeff Sharkey9c484982015-03-31 10:35:33 -07001153static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
1154 const unsigned char *master_key, const char *real_blk_name,
1155 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001158 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001159 int fd=0;
Daniel Rosenberg25a52132016-02-26 16:44:36 -08001160 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001162 int version[3];
1163 char *extra_params;
1164 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001166 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001167 SLOGE("Cannot open device-mapper\n");
1168 goto errout;
1169 }
1170
1171 io = (struct dm_ioctl *) buffer;
1172
1173 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Daniel Rosenberg25a52132016-02-26 16:44:36 -08001174 err = ioctl(fd, DM_DEV_CREATE, io);
1175 if (err) {
1176 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001177 goto errout;
1178 }
1179
1180 /* Get the device status, in particular, the name of it's device file */
1181 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1182 if (ioctl(fd, DM_DEV_STATUS, io)) {
1183 SLOGE("Cannot retrieve dm-crypt device status\n");
1184 goto errout;
1185 }
1186 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1187 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1188
Ken Sumralldb5e0262013-02-05 17:39:48 -08001189 extra_params = "";
1190 if (! get_dm_crypt_version(fd, name, version)) {
1191 /* Support for allow_discards was added in version 1.11.0 */
1192 if ((version[0] >= 2) ||
1193 ((version[0] == 1) && (version[1] >= 11))) {
1194 extra_params = "1 allow_discards";
1195 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1196 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001197 }
1198
Ken Sumralldb5e0262013-02-05 17:39:48 -08001199 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1200 fd, extra_params);
1201 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001202 SLOGE("Cannot load dm-crypt mapping table.\n");
1203 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001204 } else if (load_count > 1) {
1205 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001206 }
1207
1208 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001209 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001210
1211 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1212 SLOGE("Cannot resume the dm-crypt device\n");
1213 goto errout;
1214 }
1215
1216 /* We made it here with no errors. Woot! */
1217 retval = 0;
1218
1219errout:
1220 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1221
1222 return retval;
1223}
1224
Ken Sumrall29d8da82011-05-18 17:20:07 -07001225static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001226{
1227 int fd;
1228 char buffer[DM_CRYPT_BUF_SIZE];
1229 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230 int retval = -1;
1231
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001232 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001233 SLOGE("Cannot open device-mapper\n");
1234 goto errout;
1235 }
1236
1237 io = (struct dm_ioctl *) buffer;
1238
1239 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1240 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1241 SLOGE("Cannot remove dm-crypt device\n");
1242 goto errout;
1243 }
1244
1245 /* We made it here with no errors. Woot! */
1246 retval = 0;
1247
1248errout:
1249 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1250
1251 return retval;
1252
1253}
1254
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001255static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001256 unsigned char *ikey, void *params UNUSED)
1257{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001258 SLOGI("Using pbkdf2 for cryptfs KDF");
1259
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001261 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1262 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1263 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001264}
1265
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001266static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001267 unsigned char *ikey, void *params)
1268{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001269 SLOGI("Using scrypt for cryptfs KDF");
1270
Kenny Rootc4c70f12013-06-14 12:11:38 -07001271 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1272
1273 int N = 1 << ftr->N_factor;
1274 int r = 1 << ftr->r_factor;
1275 int p = 1 << ftr->p_factor;
1276
1277 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001278 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001279 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1280 salt, SALT_LEN, N, r, p, ikey,
1281 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001282
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001283 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001284}
1285
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001286static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1287 unsigned char *ikey, void *params)
1288{
1289 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1290
1291 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001292 size_t signature_size;
1293 unsigned char* signature;
1294 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1295
1296 int N = 1 << ftr->N_factor;
1297 int r = 1 << ftr->r_factor;
1298 int p = 1 << ftr->p_factor;
1299
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001300 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1301 salt, SALT_LEN, N, r, p, ikey,
1302 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001303
1304 if (rc) {
1305 SLOGE("scrypt failed");
1306 return -1;
1307 }
1308
Shawn Willdene17a9c42014-09-08 13:04:08 -06001309 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1310 &signature, &signature_size)) {
1311 SLOGE("Signing failed");
1312 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001313 }
1314
1315 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1316 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1317 free(signature);
1318
1319 if (rc) {
1320 SLOGE("scrypt failed");
1321 return -1;
1322 }
1323
1324 return 0;
1325}
1326
1327static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1328 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001329 unsigned char *encrypted_master_key,
1330 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001331{
1332 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1333 EVP_CIPHER_CTX e_ctx;
1334 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001335 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001336
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001337 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001338 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001339
1340 switch (crypt_ftr->kdf_type) {
1341 case KDF_SCRYPT_KEYMASTER:
1342 if (keymaster_create_key(crypt_ftr)) {
1343 SLOGE("keymaster_create_key failed");
1344 return -1;
1345 }
1346
1347 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1348 SLOGE("scrypt failed");
1349 return -1;
1350 }
1351 break;
1352
1353 case KDF_SCRYPT:
1354 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1355 SLOGE("scrypt failed");
1356 return -1;
1357 }
1358 break;
1359
1360 default:
1361 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001362 return -1;
1363 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001364
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001365 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001366 EVP_CIPHER_CTX_init(&e_ctx);
1367 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001368 SLOGE("EVP_EncryptInit failed\n");
1369 return -1;
1370 }
1371 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001372
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001374 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001375 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001376 SLOGE("EVP_EncryptUpdate failed\n");
1377 return -1;
1378 }
Adam Langley889c4f12014-09-03 14:23:13 -07001379 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001380 SLOGE("EVP_EncryptFinal failed\n");
1381 return -1;
1382 }
1383
1384 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1385 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1386 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001387 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001388
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001389 /* Store the scrypt of the intermediate key, so we can validate if it's a
1390 password error or mount error when things go wrong.
1391 Note there's no need to check for errors, since if this is incorrect, we
1392 simply won't wipe userdata, which is the correct default behavior
1393 */
1394 int N = 1 << crypt_ftr->N_factor;
1395 int r = 1 << crypt_ftr->r_factor;
1396 int p = 1 << crypt_ftr->p_factor;
1397
1398 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1399 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1400 crypt_ftr->scrypted_intermediate_key,
1401 sizeof(crypt_ftr->scrypted_intermediate_key));
1402
1403 if (rc) {
1404 SLOGE("encrypt_master_key: crypto_scrypt failed");
1405 }
1406
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001407 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001408}
1409
Paul Lawrence731a7a22015-04-28 22:14:15 +00001410static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001411 unsigned char *encrypted_master_key,
1412 unsigned char *decrypted_master_key,
1413 kdf_func kdf, void *kdf_params,
1414 unsigned char** intermediate_key,
1415 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001416{
1417 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 -08001418 EVP_CIPHER_CTX d_ctx;
1419 int decrypted_len, final_len;
1420
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001421 /* Turn the password into an intermediate key and IV that can decrypt the
1422 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001423 if (kdf(passwd, salt, ikey, kdf_params)) {
1424 SLOGE("kdf failed");
1425 return -1;
1426 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427
1428 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001429 EVP_CIPHER_CTX_init(&d_ctx);
1430 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001431 return -1;
1432 }
1433 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1434 /* Decrypt the master key */
1435 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1436 encrypted_master_key, KEY_LEN_BYTES)) {
1437 return -1;
1438 }
Adam Langley889c4f12014-09-03 14:23:13 -07001439 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001440 return -1;
1441 }
1442
1443 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1444 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001445 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001446
1447 /* Copy intermediate key if needed by params */
1448 if (intermediate_key && intermediate_key_size) {
1449 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1450 if (intermediate_key) {
1451 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1452 *intermediate_key_size = KEY_LEN_BYTES;
1453 }
1454 }
1455
1456 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001457}
1458
Kenny Rootc4c70f12013-06-14 12:11:38 -07001459static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001460{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001461 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001462 *kdf = scrypt_keymaster;
1463 *kdf_params = ftr;
1464 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001465 *kdf = scrypt;
1466 *kdf_params = ftr;
1467 } else {
1468 *kdf = pbkdf2;
1469 *kdf_params = NULL;
1470 }
1471}
1472
Paul Lawrence731a7a22015-04-28 22:14:15 +00001473static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001474 struct crypt_mnt_ftr *crypt_ftr,
1475 unsigned char** intermediate_key,
1476 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001477{
1478 kdf_func kdf;
1479 void *kdf_params;
1480 int ret;
1481
1482 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001483 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1484 decrypted_master_key, kdf, kdf_params,
1485 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001486 if (ret != 0) {
1487 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001488 }
1489
1490 return ret;
1491}
1492
1493static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1494 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001495 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001496 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001497
1498 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001499 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001500 read(fd, key_buf, sizeof(key_buf));
1501 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001502 close(fd);
1503
1504 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001505 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001506}
1507
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001508int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001509{
Greg Hackmann955653e2014-09-24 14:55:20 -07001510 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001511#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001512
1513 /* Now umount the tmpfs filesystem */
1514 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001515 if (umount(mountpoint) == 0) {
1516 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001517 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001518
1519 if (errno == EINVAL) {
1520 /* EINVAL is returned if the directory is not a mountpoint,
1521 * i.e. there is no filesystem mounted there. So just get out.
1522 */
1523 break;
1524 }
1525
1526 err = errno;
1527
1528 /* If allowed, be increasingly aggressive before the last two retries */
1529 if (kill) {
1530 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1531 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001532 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001533 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1534 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001535 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001536 }
1537 }
1538
1539 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001540 }
1541
1542 if (i < WAIT_UNMOUNT_COUNT) {
1543 SLOGD("unmounting %s succeeded\n", mountpoint);
1544 rc = 0;
1545 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001546 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001547 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001548 rc = -1;
1549 }
1550
1551 return rc;
1552}
1553
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001554#define DATA_PREP_TIMEOUT 1000
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001555static int prep_data_fs(void)
1556{
1557 int i;
1558
Jeff Sharkey47695b22016-02-01 17:02:29 -07001559 // NOTE: post_fs_data results in init calling back around to vold, so all
1560 // callers to this method must be async
1561
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001562 /* Do the prep of the /data filesystem */
1563 property_set("vold.post_fs_data_done", "0");
1564 property_set("vold.decrypt", "trigger_post_fs_data");
1565 SLOGD("Just triggered post_fs_data\n");
1566
Ken Sumrallc5872692013-05-14 15:26:31 -07001567 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001568 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001569 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001570
1571 property_get("vold.post_fs_data_done", p, "0");
1572 if (*p == '1') {
1573 break;
1574 } else {
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001575 usleep(50000);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001576 }
1577 }
1578 if (i == DATA_PREP_TIMEOUT) {
1579 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001580 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001581 return -1;
1582 } else {
1583 SLOGD("post_fs_data done\n");
1584 return 0;
1585 }
1586}
1587
Paul Lawrence74f29f12014-08-28 15:54:10 -07001588static void cryptfs_set_corrupt()
1589{
1590 // Mark the footer as bad
1591 struct crypt_mnt_ftr crypt_ftr;
1592 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1593 SLOGE("Failed to get crypto footer - panic");
1594 return;
1595 }
1596
1597 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1598 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1599 SLOGE("Failed to set crypto footer - panic");
1600 return;
1601 }
1602}
1603
1604static void cryptfs_trigger_restart_min_framework()
1605{
1606 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1607 SLOGE("Failed to mount tmpfs on data - panic");
1608 return;
1609 }
1610
1611 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1612 SLOGE("Failed to trigger post fs data - panic");
1613 return;
1614 }
1615
1616 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1617 SLOGE("Failed to trigger restart min framework - panic");
1618 return;
1619 }
1620}
1621
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001622/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001623static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001624{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001625 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001626 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001627 static int restart_successful = 0;
1628
1629 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001630 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001631 SLOGE("Encrypted filesystem not validated, aborting");
1632 return -1;
1633 }
1634
1635 if (restart_successful) {
1636 SLOGE("System already restarted with encrypted disk, aborting");
1637 return -1;
1638 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001639
Paul Lawrencef4faa572014-01-29 13:31:03 -08001640 if (restart_main) {
1641 /* Here is where we shut down the framework. The init scripts
1642 * start all services in one of three classes: core, main or late_start.
1643 * On boot, we start core and main. Now, we stop main, but not core,
1644 * as core includes vold and a few other really important things that
1645 * we need to keep running. Once main has stopped, we should be able
1646 * to umount the tmpfs /data, then mount the encrypted /data.
1647 * We then restart the class main, and also the class late_start.
1648 * At the moment, I've only put a few things in late_start that I know
1649 * are not needed to bring up the framework, and that also cause problems
1650 * with unmounting the tmpfs /data, but I hope to add add more services
1651 * to the late_start class as we optimize this to decrease the delay
1652 * till the user is asked for the password to the filesystem.
1653 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001654
Paul Lawrencef4faa572014-01-29 13:31:03 -08001655 /* The init files are setup to stop the class main when vold.decrypt is
1656 * set to trigger_reset_main.
1657 */
1658 property_set("vold.decrypt", "trigger_reset_main");
1659 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001660
Paul Lawrencef4faa572014-01-29 13:31:03 -08001661 /* Ugh, shutting down the framework is not synchronous, so until it
1662 * can be fixed, this horrible hack will wait a moment for it all to
1663 * shut down before proceeding. Without it, some devices cannot
1664 * restart the graphics services.
1665 */
1666 sleep(2);
1667 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001668
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001669 /* Now that the framework is shutdown, we should be able to umount()
1670 * the tmpfs filesystem, and mount the real one.
1671 */
1672
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001673 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1674 if (strlen(crypto_blkdev) == 0) {
1675 SLOGE("fs_crypto_blkdev not set\n");
1676 return -1;
1677 }
1678
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001679 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001680 /* If ro.crypto.readonly is set to 1, mount the decrypted
1681 * filesystem readonly. This is used when /data is mounted by
1682 * recovery mode.
1683 */
1684 char ro_prop[PROPERTY_VALUE_MAX];
1685 property_get("ro.crypto.readonly", ro_prop, "");
1686 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1687 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1688 rec->flags |= MS_RDONLY;
1689 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001690
Ken Sumralle5032c42012-04-01 23:58:44 -07001691 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001692 int retries = RETRY_MOUNT_ATTEMPTS;
1693 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001694
1695 /*
1696 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1697 * partitions in the fsck domain.
1698 */
1699 if (setexeccon(secontextFsck())){
1700 SLOGE("Failed to setexeccon");
1701 return -1;
1702 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001703 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1704 crypto_blkdev, 0))
1705 != 0) {
1706 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1707 /* TODO: invoke something similar to
1708 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1709 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1710 SLOGI("Failed to mount %s because it is busy - waiting",
1711 crypto_blkdev);
1712 if (--retries) {
1713 sleep(RETRY_MOUNT_DELAY_SECONDS);
1714 } else {
1715 /* Let's hope that a reboot clears away whatever is keeping
1716 the mount busy */
1717 cryptfs_reboot(reboot);
1718 }
1719 } else {
1720 SLOGE("Failed to mount decrypted data");
1721 cryptfs_set_corrupt();
1722 cryptfs_trigger_restart_min_framework();
1723 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001724 if (setexeccon(NULL)) {
1725 SLOGE("Failed to setexeccon");
1726 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001727 return -1;
1728 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001729 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001730 if (setexeccon(NULL)) {
1731 SLOGE("Failed to setexeccon");
1732 return -1;
1733 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001734
Ken Sumralle5032c42012-04-01 23:58:44 -07001735 property_set("vold.decrypt", "trigger_load_persist_props");
1736 /* Create necessary paths on /data */
1737 if (prep_data_fs()) {
1738 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001739 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001740
1741 /* startup service classes main and late_start */
1742 property_set("vold.decrypt", "trigger_restart_framework");
1743 SLOGD("Just triggered restart_framework\n");
1744
1745 /* Give it a few moments to get started */
1746 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001747 }
1748
Ken Sumrall0cc16632011-01-18 20:32:26 -08001749 if (rc == 0) {
1750 restart_successful = 1;
1751 }
1752
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001753 return rc;
1754}
1755
Paul Lawrencef4faa572014-01-29 13:31:03 -08001756int cryptfs_restart(void)
1757{
Paul Lawrence05335c32015-03-05 09:46:23 -08001758 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001759 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001760 SLOGE("cryptfs_restart not valid for file encryption:");
1761 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001762 }
1763
Paul Lawrencef4faa572014-01-29 13:31:03 -08001764 /* Call internal implementation forcing a restart of main service group */
1765 return cryptfs_restart_internal(1);
1766}
1767
Paul Lawrence05335c32015-03-05 09:46:23 -08001768static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001769{
1770 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001771 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001772 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001773
1774 property_get("ro.crypto.state", encrypted_state, "");
1775 if (strcmp(encrypted_state, "encrypted") ) {
1776 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001777 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001778 }
1779
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001780 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001781 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001782 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001783 }
1784
Ken Sumrall160b4d62013-04-22 12:15:39 -07001785 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001786 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001787
Ken Sumralle1a45852011-12-14 21:24:27 -08001788 /*
1789 * Only report this error if key_loc is a file and it exists.
1790 * If the device was never encrypted, and /data is not mountable for
1791 * some reason, returning 1 should prevent the UI from presenting the
1792 * a "enter password" screen, or worse, a "press button to wipe the
1793 * device" screen.
1794 */
1795 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1796 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001797 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001798 } else {
1799 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001800 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001801 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001802 }
1803
Paul Lawrence74f29f12014-08-28 15:54:10 -07001804 // Test for possible error flags
1805 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1806 SLOGE("Encryption process is partway completed\n");
1807 return CRYPTO_COMPLETE_PARTIAL;
1808 }
1809
1810 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1811 SLOGE("Encryption process was interrupted but cannot continue\n");
1812 return CRYPTO_COMPLETE_INCONSISTENT;
1813 }
1814
1815 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1816 SLOGE("Encryption is successful but data is corrupt\n");
1817 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001818 }
1819
1820 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001821 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001822}
1823
Paul Lawrencef4faa572014-01-29 13:31:03 -08001824static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1825 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001826{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001827 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001828 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001829 char crypto_blkdev[MAXPATHLEN];
1830 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001831 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001832 unsigned int orig_failed_decrypt_count;
1833 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001834 int use_keymaster = 0;
1835 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001836 unsigned char* intermediate_key = 0;
1837 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001838
Paul Lawrencef4faa572014-01-29 13:31:03 -08001839 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1840 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001841
Paul Lawrencef4faa572014-01-29 13:31:03 -08001842 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001843 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1844 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001845 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001846 rc = -1;
1847 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001848 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001849 }
1850
Paul Lawrencef4faa572014-01-29 13:31:03 -08001851 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1852
Ajay Dudani87701e22014-09-17 21:02:52 -07001853#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001854 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1855 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1856 SLOGE("Hardware encryption key does not match");
1857 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001858 }
1859#endif
1860
Paul Lawrence74f29f12014-08-28 15:54:10 -07001861 // Create crypto block device - all (non fatal) code paths
1862 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001863 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1864 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001865 SLOGE("Error creating decrypted block device\n");
1866 rc = -1;
1867 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001868 }
1869
Paul Lawrence74f29f12014-08-28 15:54:10 -07001870 /* Work out if the problem is the password or the data */
1871 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1872 scrypted_intermediate_key)];
1873 int N = 1 << crypt_ftr->N_factor;
1874 int r = 1 << crypt_ftr->r_factor;
1875 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001876
Paul Lawrence74f29f12014-08-28 15:54:10 -07001877 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1878 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1879 N, r, p, scrypted_intermediate_key,
1880 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001881
Paul Lawrence74f29f12014-08-28 15:54:10 -07001882 // Does the key match the crypto footer?
1883 if (rc == 0 && memcmp(scrypted_intermediate_key,
1884 crypt_ftr->scrypted_intermediate_key,
1885 sizeof(scrypted_intermediate_key)) == 0) {
1886 SLOGI("Password matches");
1887 rc = 0;
1888 } else {
1889 /* Try mounting the file system anyway, just in case the problem's with
1890 * the footer, not the key. */
1891 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1892 mkdir(tmp_mount_point, 0755);
1893 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1894 SLOGE("Error temp mounting decrypted block device\n");
1895 delete_crypto_blk_dev(label);
1896
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001897 rc = ++crypt_ftr->failed_decrypt_count;
1898 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001899 } else {
1900 /* Success! */
1901 SLOGI("Password did not match but decrypted drive mounted - continue");
1902 umount(tmp_mount_point);
1903 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001904 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001905 }
1906
1907 if (rc == 0) {
1908 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001909 if (orig_failed_decrypt_count != 0) {
1910 put_crypt_ftr_and_key(crypt_ftr);
1911 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001912
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001913 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001914 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001915 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001916
1917 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001918 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001919 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001920 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001921 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001922 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001923 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001924
Paul Lawrence74f29f12014-08-28 15:54:10 -07001925 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001926 use_keymaster = keymaster_check_compatibility();
1927 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001928 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001929 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1930 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1931 upgrade = 1;
1932 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001933 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001934 upgrade = 1;
1935 }
1936
1937 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001938 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1939 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001940 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001941 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001942 }
1943 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001944
1945 // Do not fail even if upgrade failed - machine is bootable
1946 // Note that if this code is ever hit, there is a *serious* problem
1947 // since KDFs should never fail. You *must* fix the kdf before
1948 // proceeding!
1949 if (rc) {
1950 SLOGW("Upgrade failed with error %d,"
1951 " but continuing with previous state",
1952 rc);
1953 rc = 0;
1954 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001955 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001956 }
1957
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001958 errout:
1959 if (intermediate_key) {
1960 memset(intermediate_key, 0, intermediate_key_size);
1961 free(intermediate_key);
1962 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001963 return rc;
1964}
1965
Ken Sumrall29d8da82011-05-18 17:20:07 -07001966/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001967 * Called by vold when it's asked to mount an encrypted external
1968 * storage volume. The incoming partition has no crypto header/footer,
1969 * as any metadata is been stored in a separate, small partition.
1970 *
1971 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001972 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001973int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1974 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001975 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001976 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001977 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001978 return -1;
1979 }
1980
1981 unsigned long nr_sec = 0;
1982 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001983 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001984
Ken Sumrall29d8da82011-05-18 17:20:07 -07001985 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001986 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001987 return -1;
1988 }
1989
Jeff Sharkey9c484982015-03-31 10:35:33 -07001990 struct crypt_mnt_ftr ext_crypt_ftr;
1991 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1992 ext_crypt_ftr.fs_size = nr_sec;
1993 ext_crypt_ftr.keysize = keysize;
1994 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001995
Jeff Sharkey9c484982015-03-31 10:35:33 -07001996 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1997 out_crypto_blkdev, label);
1998}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001999
Jeff Sharkey9c484982015-03-31 10:35:33 -07002000/*
2001 * Called by vold when it's asked to unmount an encrypted external
2002 * storage volume.
2003 */
2004int cryptfs_revert_ext_volume(const char* label) {
2005 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002006}
2007
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002008int cryptfs_crypto_complete(void)
2009{
2010 return do_crypto_complete("/data");
2011}
2012
Paul Lawrencef4faa572014-01-29 13:31:03 -08002013int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2014{
2015 char encrypted_state[PROPERTY_VALUE_MAX];
2016 property_get("ro.crypto.state", encrypted_state, "");
2017 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2018 SLOGE("encrypted fs already validated or not running with encryption,"
2019 " aborting");
2020 return -1;
2021 }
2022
2023 if (get_crypt_ftr_and_key(crypt_ftr)) {
2024 SLOGE("Error getting crypt footer and key");
2025 return -1;
2026 }
2027
2028 return 0;
2029}
2030
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002031int cryptfs_check_passwd(char *passwd)
2032{
Paul Lawrence05335c32015-03-05 09:46:23 -08002033 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00002034 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002035 SLOGE("cryptfs_check_passwd not valid for file encryption");
2036 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002037 }
2038
Paul Lawrencef4faa572014-01-29 13:31:03 -08002039 struct crypt_mnt_ftr crypt_ftr;
2040 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002041
Paul Lawrencef4faa572014-01-29 13:31:03 -08002042 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002043 if (rc) {
2044 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002045 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002046 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002047
Paul Lawrence3bd36d52015-06-09 13:37:44 -07002048 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002049 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2050 if (rc) {
2051 SLOGE("Password did not match");
2052 return rc;
2053 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002054
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002055 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2056 // Here we have a default actual password but a real password
2057 // we must test against the scrypted value
2058 // First, we must delete the crypto block device that
2059 // test_mount_encrypted_fs leaves behind as a side effect
2060 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2061 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2062 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2063 if (rc) {
2064 SLOGE("Default password did not match on reboot encryption");
2065 return rc;
2066 }
2067
2068 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2069 put_crypt_ftr_and_key(&crypt_ftr);
2070 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2071 if (rc) {
2072 SLOGE("Could not change password on reboot encryption");
2073 return rc;
2074 }
2075 }
2076
2077 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002078 cryptfs_clear_password();
2079 password = strdup(passwd);
2080 struct timespec now;
2081 clock_gettime(CLOCK_BOOTTIME, &now);
2082 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002083 }
2084
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002085 return rc;
2086}
2087
Ken Sumrall3ad90722011-10-04 20:38:29 -07002088int cryptfs_verify_passwd(char *passwd)
2089{
2090 struct crypt_mnt_ftr crypt_ftr;
2091 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002092 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002093 char encrypted_state[PROPERTY_VALUE_MAX];
2094 int rc;
2095
2096 property_get("ro.crypto.state", encrypted_state, "");
2097 if (strcmp(encrypted_state, "encrypted") ) {
2098 SLOGE("device not encrypted, aborting");
2099 return -2;
2100 }
2101
2102 if (!master_key_saved) {
2103 SLOGE("encrypted fs not yet mounted, aborting");
2104 return -1;
2105 }
2106
2107 if (!saved_mount_point) {
2108 SLOGE("encrypted fs failed to save mount point, aborting");
2109 return -1;
2110 }
2111
Ken Sumrall160b4d62013-04-22 12:15:39 -07002112 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002113 SLOGE("Error getting crypt footer and key\n");
2114 return -1;
2115 }
2116
2117 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2118 /* If the device has no password, then just say the password is valid */
2119 rc = 0;
2120 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002121 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002122 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2123 /* They match, the password is correct */
2124 rc = 0;
2125 } else {
2126 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2127 sleep(1);
2128 rc = 1;
2129 }
2130 }
2131
2132 return rc;
2133}
2134
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002135/* Initialize a crypt_mnt_ftr structure. The keysize is
2136 * defaulted to 16 bytes, and the filesystem size to 0.
2137 * Presumably, at a minimum, the caller will update the
2138 * filesystem size and crypto_type_name after calling this function.
2139 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002140static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002141{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002142 off64_t off;
2143
2144 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002145 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002146 ftr->major_version = CURRENT_MAJOR_VERSION;
2147 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002148 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002149 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002150
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002151 switch (keymaster_check_compatibility()) {
2152 case 1:
2153 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2154 break;
2155
2156 case 0:
2157 ftr->kdf_type = KDF_SCRYPT;
2158 break;
2159
2160 default:
2161 SLOGE("keymaster_check_compatibility failed");
2162 return -1;
2163 }
2164
Kenny Rootc4c70f12013-06-14 12:11:38 -07002165 get_device_scrypt_params(ftr);
2166
Ken Sumrall160b4d62013-04-22 12:15:39 -07002167 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2168 if (get_crypt_ftr_info(NULL, &off) == 0) {
2169 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2170 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2171 ftr->persist_data_size;
2172 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002173
2174 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002175}
2176
Ken Sumrall29d8da82011-05-18 17:20:07 -07002177static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002178{
Ken Sumralle550f782013-08-20 13:48:23 -07002179 const char *args[10];
2180 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2181 int num_args;
2182 int status;
2183 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002184 int rc = -1;
2185
Ken Sumrall29d8da82011-05-18 17:20:07 -07002186 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002187 args[0] = "/system/bin/make_ext4fs";
2188 args[1] = "-a";
2189 args[2] = "/data";
2190 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002191 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002192 args[4] = size_str;
2193 args[5] = crypto_blkdev;
2194 num_args = 6;
2195 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2196 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002197 } else if (type == F2FS_FS) {
2198 args[0] = "/system/bin/mkfs.f2fs";
2199 args[1] = "-t";
2200 args[2] = "-d1";
2201 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002202 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002203 args[4] = size_str;
2204 num_args = 5;
2205 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2206 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002207 } else {
2208 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2209 return -1;
2210 }
2211
Ken Sumralle550f782013-08-20 13:48:23 -07002212 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2213
2214 if (tmp != 0) {
2215 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002216 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002217 if (WIFEXITED(status)) {
2218 if (WEXITSTATUS(status)) {
2219 SLOGE("Error creating filesystem on %s, exit status %d ",
2220 crypto_blkdev, WEXITSTATUS(status));
2221 } else {
2222 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2223 rc = 0;
2224 }
2225 } else {
2226 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2227 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002228 }
2229
2230 return rc;
2231}
2232
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002233#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002234#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2235#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002236
2237/* aligned 32K writes tends to make flash happy.
2238 * SD card association recommends it.
2239 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002240#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002241#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002242#else
2243#define BLOCKS_AT_A_TIME 1024
2244#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002245
2246struct encryptGroupsData
2247{
2248 int realfd;
2249 int cryptofd;
2250 off64_t numblocks;
2251 off64_t one_pct, cur_pct, new_pct;
2252 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002253 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002254 char* real_blkdev, * crypto_blkdev;
2255 int count;
2256 off64_t offset;
2257 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002258 off64_t last_written_sector;
2259 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002260 time_t time_started;
2261 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002262};
2263
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002264static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002265{
2266 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002267
2268 if (is_used) {
2269 data->used_blocks_already_done++;
2270 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002271 if (data->tot_used_blocks) {
2272 data->new_pct = data->used_blocks_already_done / data->one_pct;
2273 } else {
2274 data->new_pct = data->blocks_already_done / data->one_pct;
2275 }
2276
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002277 if (data->new_pct > data->cur_pct) {
2278 char buf[8];
2279 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002280 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002281 property_set("vold.encrypt_progress", buf);
2282 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002283
2284 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002285 struct timespec time_now;
2286 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2287 SLOGW("Error getting time");
2288 } else {
2289 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2290 off64_t remaining_blocks = data->tot_used_blocks
2291 - data->used_blocks_already_done;
2292 int remaining_time = (int)(elapsed_time * remaining_blocks
2293 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002294
Paul Lawrence9c58a872014-09-30 09:12:51 -07002295 // Change time only if not yet set, lower, or a lot higher for
2296 // best user experience
2297 if (data->remaining_time == -1
2298 || remaining_time < data->remaining_time
2299 || remaining_time > data->remaining_time + 60) {
2300 char buf[8];
2301 snprintf(buf, sizeof(buf), "%d", remaining_time);
2302 property_set("vold.encrypt_time_remaining", buf);
2303 data->remaining_time = remaining_time;
2304 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002305 }
2306 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002307}
2308
Paul Lawrence3846be12014-09-22 11:33:54 -07002309static void log_progress(struct encryptGroupsData const* data, bool completed)
2310{
2311 // Precondition - if completed data = 0 else data != 0
2312
2313 // Track progress so we can skip logging blocks
2314 static off64_t offset = -1;
2315
2316 // Need to close existing 'Encrypting from' log?
2317 if (completed || (offset != -1 && data->offset != offset)) {
2318 SLOGI("Encrypted to sector %" PRId64,
2319 offset / info.block_size * CRYPT_SECTOR_SIZE);
2320 offset = -1;
2321 }
2322
2323 // Need to start new 'Encrypting from' log?
2324 if (!completed && offset != data->offset) {
2325 SLOGI("Encrypting from sector %" PRId64,
2326 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2327 }
2328
2329 // Update offset
2330 if (!completed) {
2331 offset = data->offset + (off64_t)data->count * info.block_size;
2332 }
2333}
2334
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002335static int flush_outstanding_data(struct encryptGroupsData* data)
2336{
2337 if (data->count == 0) {
2338 return 0;
2339 }
2340
Elliott Hughes231bdba2014-06-25 18:36:19 -07002341 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002342
2343 if (pread64(data->realfd, data->buffer,
2344 info.block_size * data->count, data->offset)
2345 <= 0) {
2346 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2347 data->real_blkdev);
2348 return -1;
2349 }
2350
2351 if (pwrite64(data->cryptofd, data->buffer,
2352 info.block_size * data->count, data->offset)
2353 <= 0) {
2354 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2355 data->crypto_blkdev);
2356 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002357 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002358 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002359 }
2360
2361 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002362 data->last_written_sector = (data->offset + data->count)
2363 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002364 return 0;
2365}
2366
2367static int encrypt_groups(struct encryptGroupsData* data)
2368{
2369 unsigned int i;
2370 u8 *block_bitmap = 0;
2371 unsigned int block;
2372 off64_t ret;
2373 int rc = -1;
2374
2375 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2376 if (!data->buffer) {
2377 SLOGE("Failed to allocate crypto buffer");
2378 goto errout;
2379 }
2380
2381 block_bitmap = malloc(info.block_size);
2382 if (!block_bitmap) {
2383 SLOGE("failed to allocate block bitmap");
2384 goto errout;
2385 }
2386
2387 for (i = 0; i < aux_info.groups; ++i) {
2388 SLOGI("Encrypting group %d", i);
2389
2390 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2391 u32 block_count = min(info.blocks_per_group,
2392 aux_info.len_blocks - first_block);
2393
2394 off64_t offset = (u64)info.block_size
2395 * aux_info.bg_desc[i].bg_block_bitmap;
2396
2397 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2398 if (ret != (int)info.block_size) {
2399 SLOGE("failed to read all of block group bitmap %d", i);
2400 goto errout;
2401 }
2402
2403 offset = (u64)info.block_size * first_block;
2404
2405 data->count = 0;
2406
2407 for (block = 0; block < block_count; block++) {
liminghaoaa08e582016-01-06 10:30:49 +08002408 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
2409 0 : bitmap_get_bit(block_bitmap, block);
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002410 update_progress(data, used);
2411 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002412 if (data->count == 0) {
2413 data->offset = offset;
2414 }
2415 data->count++;
2416 } else {
2417 if (flush_outstanding_data(data)) {
2418 goto errout;
2419 }
2420 }
2421
2422 offset += info.block_size;
2423
2424 /* Write data if we are aligned or buffer size reached */
2425 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2426 || data->count == BLOCKS_AT_A_TIME) {
2427 if (flush_outstanding_data(data)) {
2428 goto errout;
2429 }
2430 }
Paul Lawrence87999172014-02-20 12:21:31 -08002431
Paul Lawrence73d7a022014-06-09 14:10:09 -07002432 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002433 SLOGE("Stopping encryption due to low battery");
2434 rc = 0;
2435 goto errout;
2436 }
2437
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002438 }
2439 if (flush_outstanding_data(data)) {
2440 goto errout;
2441 }
2442 }
2443
Paul Lawrence87999172014-02-20 12:21:31 -08002444 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002445 rc = 0;
2446
2447errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002448 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002449 free(data->buffer);
2450 free(block_bitmap);
2451 return rc;
2452}
2453
2454static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2455 char *real_blkdev,
2456 off64_t size,
2457 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002458 off64_t tot_size,
2459 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002460{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002461 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002462 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002463 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002464
Paul Lawrence87999172014-02-20 12:21:31 -08002465 if (previously_encrypted_upto > *size_already_done) {
2466 SLOGD("Not fast encrypting since resuming part way through");
2467 return -1;
2468 }
2469
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002470 memset(&data, 0, sizeof(data));
2471 data.real_blkdev = real_blkdev;
2472 data.crypto_blkdev = crypto_blkdev;
2473
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002474 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002475 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2476 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002477 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002478 goto errout;
2479 }
2480
David Ng82fd8042015-01-21 13:55:21 -08002481 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2482 int retries = RETRY_MOUNT_ATTEMPTS;
2483 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2484 if (--retries) {
2485 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2486 crypto_blkdev, errno, strerror(errno));
2487 sleep(RETRY_MOUNT_DELAY_SECONDS);
2488 } else {
2489 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2490 crypto_blkdev, errno, strerror(errno));
2491 rc = ENABLE_INPLACE_ERR_DEV;
2492 goto errout;
2493 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002494 }
2495
2496 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002497 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002498 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002499 goto errout;
2500 }
2501
2502 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002503 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002504 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002505 goto errout;
2506 }
2507
2508 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2509 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2510 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2511
JP Abgrall7fc1de82014-10-10 18:43:41 -07002512 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002513
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002514 data.tot_used_blocks = data.numblocks;
2515 for (i = 0; i < aux_info.groups; ++i) {
2516 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2517 }
2518
2519 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002520 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002521
2522 struct timespec time_started = {0};
2523 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2524 SLOGW("Error getting time at start");
2525 // Note - continue anyway - we'll run with 0
2526 }
2527 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002528 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002529
2530 rc = encrypt_groups(&data);
2531 if (rc) {
2532 SLOGE("Error encrypting groups");
2533 goto errout;
2534 }
2535
Paul Lawrence87999172014-02-20 12:21:31 -08002536 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002537 rc = 0;
2538
2539errout:
2540 close(data.realfd);
2541 close(data.cryptofd);
2542
2543 return rc;
2544}
2545
Paul Lawrence3846be12014-09-22 11:33:54 -07002546static void log_progress_f2fs(u64 block, bool completed)
2547{
2548 // Precondition - if completed data = 0 else data != 0
2549
2550 // Track progress so we can skip logging blocks
2551 static u64 last_block = (u64)-1;
2552
2553 // Need to close existing 'Encrypting from' log?
2554 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2555 SLOGI("Encrypted to block %" PRId64, last_block);
2556 last_block = -1;
2557 }
2558
2559 // Need to start new 'Encrypting from' log?
2560 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2561 SLOGI("Encrypting from block %" PRId64, block);
2562 }
2563
2564 // Update offset
2565 if (!completed) {
2566 last_block = block;
2567 }
2568}
2569
Daniel Rosenberge82df162014-08-15 22:19:23 +00002570static int encrypt_one_block_f2fs(u64 pos, void *data)
2571{
2572 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2573
2574 priv_dat->blocks_already_done = pos - 1;
2575 update_progress(priv_dat, 1);
2576
2577 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2578
2579 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002580 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002581 return -1;
2582 }
2583
2584 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002585 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002586 return -1;
2587 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002588 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002589 }
2590
2591 return 0;
2592}
2593
2594static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2595 char *real_blkdev,
2596 off64_t size,
2597 off64_t *size_already_done,
2598 off64_t tot_size,
2599 off64_t previously_encrypted_upto)
2600{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002601 struct encryptGroupsData data;
2602 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002603 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002604 if (previously_encrypted_upto > *size_already_done) {
2605 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002606 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002607 }
2608 memset(&data, 0, sizeof(data));
2609 data.real_blkdev = real_blkdev;
2610 data.crypto_blkdev = crypto_blkdev;
2611 data.realfd = -1;
2612 data.cryptofd = -1;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002613 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002614 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002615 real_blkdev);
2616 goto errout;
2617 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002618 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002619 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002620 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002621 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002622 goto errout;
2623 }
2624
2625 f2fs_info = generate_f2fs_info(data.realfd);
2626 if (!f2fs_info)
2627 goto errout;
2628
2629 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2630 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2631 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2632
2633 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2634
2635 data.one_pct = data.tot_used_blocks / 100;
2636 data.cur_pct = 0;
2637 data.time_started = time(NULL);
2638 data.remaining_time = -1;
2639
2640 data.buffer = malloc(f2fs_info->block_size);
2641 if (!data.buffer) {
2642 SLOGE("Failed to allocate crypto buffer");
2643 goto errout;
2644 }
2645
2646 data.count = 0;
2647
2648 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2649 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2650
2651 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002652 SLOGE("Error in running over f2fs blocks");
2653 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002654 goto errout;
2655 }
2656
2657 *size_already_done += size;
2658 rc = 0;
2659
2660errout:
2661 if (rc)
2662 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2663
Paul Lawrence3846be12014-09-22 11:33:54 -07002664 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002665 free(f2fs_info);
2666 free(data.buffer);
2667 close(data.realfd);
2668 close(data.cryptofd);
2669
2670 return rc;
2671}
2672
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002673static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2674 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002675 off64_t tot_size,
2676 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002677{
2678 int realfd, cryptofd;
2679 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002680 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002681 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002682 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002683 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002684
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002685 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002686 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002687 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002688 }
2689
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002690 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002691 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2692 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002693 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002694 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002695 }
2696
2697 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2698 * The size passed in is the number of 512 byte sectors in the filesystem.
2699 * So compute the number of whole 4K blocks we should read/write,
2700 * and the remainder.
2701 */
2702 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2703 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002704 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2705 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002706
2707 SLOGE("Encrypting filesystem in place...");
2708
Paul Lawrence87999172014-02-20 12:21:31 -08002709 i = previously_encrypted_upto + 1 - *size_already_done;
2710
2711 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2712 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2713 goto errout;
2714 }
2715
2716 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2717 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2718 goto errout;
2719 }
2720
2721 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2722 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2723 SLOGE("Error reading initial sectors from real_blkdev %s for "
2724 "inplace encrypt\n", crypto_blkdev);
2725 goto errout;
2726 }
2727 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2728 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2729 "inplace encrypt\n", crypto_blkdev);
2730 goto errout;
2731 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002732 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002733 }
2734 }
2735
Ken Sumrall29d8da82011-05-18 17:20:07 -07002736 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002737 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002738 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002739 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002740 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002741 if (new_pct > cur_pct) {
2742 char buf[8];
2743
2744 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002745 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002746 property_set("vold.encrypt_progress", buf);
2747 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002748 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002749 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002750 goto errout;
2751 }
2752 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002753 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2754 goto errout;
2755 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002756 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002757 CRYPT_SECTORS_PER_BUFSIZE,
2758 i * CRYPT_SECTORS_PER_BUFSIZE);
2759 }
2760
Paul Lawrence73d7a022014-06-09 14:10:09 -07002761 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002762 SLOGE("Stopping encryption due to low battery");
2763 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2764 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002765 goto errout;
2766 }
2767 }
2768
2769 /* Do any remaining sectors */
2770 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002771 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2772 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002773 goto errout;
2774 }
Paul Lawrence87999172014-02-20 12:21:31 -08002775 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2776 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002777 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002778 } else {
2779 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002780 }
2781 }
2782
Ken Sumrall29d8da82011-05-18 17:20:07 -07002783 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002784 rc = 0;
2785
2786errout:
2787 close(realfd);
2788 close(cryptofd);
2789
2790 return rc;
2791}
2792
JP Abgrall7fc1de82014-10-10 18:43:41 -07002793/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002794static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2795 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002796 off64_t tot_size,
2797 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002798{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002799 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002800 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002801 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002802 }
2803
2804 if (*size_already_done + size < previously_encrypted_upto) {
2805 *size_already_done += size;
2806 return 0;
2807 }
2808
Daniel Rosenberge82df162014-08-15 22:19:23 +00002809 /* TODO: identify filesystem type.
2810 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2811 * then we will drop down to cryptfs_enable_inplace_f2fs.
2812 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002813 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002814 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002815 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002816 return 0;
2817 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002818 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002819
JP Abgrall7fc1de82014-10-10 18:43:41 -07002820 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002821 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002822 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002823 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002824 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002825 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002826
JP Abgrall7fc1de82014-10-10 18:43:41 -07002827 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002828 size, size_already_done, tot_size,
2829 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002830 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2831
2832 /* Hack for b/17898962, the following is the symptom... */
2833 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2834 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2835 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2836 return ENABLE_INPLACE_ERR_DEV;
2837 }
2838 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002839}
2840
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002841#define CRYPTO_ENABLE_WIPE 1
2842#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002843
2844#define FRAMEWORK_BOOT_WAIT 60
2845
Paul Lawrence87999172014-02-20 12:21:31 -08002846static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2847{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002848 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002849 if (fd == -1) {
2850 SLOGE("Error opening file %s", filename);
2851 return -1;
2852 }
2853
2854 char block[CRYPT_INPLACE_BUFSIZE];
2855 memset(block, 0, sizeof(block));
2856 if (unix_read(fd, block, sizeof(block)) < 0) {
2857 SLOGE("Error reading file %s", filename);
2858 close(fd);
2859 return -1;
2860 }
2861
2862 close(fd);
2863
2864 SHA256_CTX c;
2865 SHA256_Init(&c);
2866 SHA256_Update(&c, block, sizeof(block));
2867 SHA256_Final(buf, &c);
2868
2869 return 0;
2870}
2871
JP Abgrall62c7af32014-06-16 13:01:23 -07002872static int get_fs_type(struct fstab_rec *rec)
2873{
2874 if (!strcmp(rec->fs_type, "ext4")) {
2875 return EXT4_FS;
2876 } else if (!strcmp(rec->fs_type, "f2fs")) {
2877 return F2FS_FS;
2878 } else {
2879 return -1;
2880 }
2881}
2882
Paul Lawrence87999172014-02-20 12:21:31 -08002883static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2884 char *crypto_blkdev, char *real_blkdev,
2885 int previously_encrypted_upto)
2886{
2887 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002888 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002889
Paul Lawrence73d7a022014-06-09 14:10:09 -07002890 if (!is_battery_ok_to_start()) {
2891 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002892 return 0;
2893 }
2894
2895 /* The size of the userdata partition, and add in the vold volumes below */
2896 tot_encryption_size = crypt_ftr->fs_size;
2897
2898 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002899 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2900 int fs_type = get_fs_type(rec);
2901 if (fs_type < 0) {
2902 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2903 return -1;
2904 }
2905 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002906 } else if (how == CRYPTO_ENABLE_INPLACE) {
2907 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2908 crypt_ftr->fs_size, &cur_encryption_done,
2909 tot_encryption_size,
2910 previously_encrypted_upto);
2911
JP Abgrall7fc1de82014-10-10 18:43:41 -07002912 if (rc == ENABLE_INPLACE_ERR_DEV) {
2913 /* Hack for b/17898962 */
2914 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2915 cryptfs_reboot(reboot);
2916 }
2917
Paul Lawrence73d7a022014-06-09 14:10:09 -07002918 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002919 crypt_ftr->encrypted_upto = cur_encryption_done;
2920 }
2921
Paul Lawrence73d7a022014-06-09 14:10:09 -07002922 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002923 /* The inplace routine never actually sets the progress to 100% due
2924 * to the round down nature of integer division, so set it here */
2925 property_set("vold.encrypt_progress", "100");
2926 }
2927 } else {
2928 /* Shouldn't happen */
2929 SLOGE("cryptfs_enable: internal error, unknown option\n");
2930 rc = -1;
2931 }
2932
2933 return rc;
2934}
2935
Paul Lawrence13486032014-02-03 13:28:11 -08002936int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002937 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002938{
2939 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002940 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002941 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002942 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002943 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002944 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002945 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002946 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002947 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002948 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002949 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002950 bool rebootEncryption = false;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002951
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002952 if (!strcmp(howarg, "wipe")) {
2953 how = CRYPTO_ENABLE_WIPE;
2954 } else if (! strcmp(howarg, "inplace")) {
2955 how = CRYPTO_ENABLE_INPLACE;
2956 } else {
2957 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002958 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002959 }
2960
Paul Lawrence87999172014-02-20 12:21:31 -08002961 if (how == CRYPTO_ENABLE_INPLACE
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002962 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2963 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2964 /* An encryption was underway and was interrupted */
2965 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2966 crypt_ftr.encrypted_upto = 0;
2967 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002968
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002969 /* At this point, we are in an inconsistent state. Until we successfully
2970 complete encryption, a reboot will leave us broken. So mark the
2971 encryption failed in case that happens.
2972 On successfully completing encryption, remove this flag */
2973 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002974
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002975 put_crypt_ftr_and_key(&crypt_ftr);
2976 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2977 if (!check_ftr_sha(&crypt_ftr)) {
2978 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2979 put_crypt_ftr_and_key(&crypt_ftr);
2980 goto error_unencrypted;
2981 }
2982
2983 /* Doing a reboot-encryption*/
2984 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2985 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2986 rebootEncryption = true;
2987 }
Paul Lawrence87999172014-02-20 12:21:31 -08002988 }
2989
2990 property_get("ro.crypto.state", encrypted_state, "");
2991 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2992 SLOGE("Device is already running encrypted, aborting");
2993 goto error_unencrypted;
2994 }
2995
2996 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2997 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002998 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002999
Ken Sumrall3ed82362011-01-28 23:31:16 -08003000 /* Get the size of the real block device */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003001 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09003002 if (fd == -1) {
3003 SLOGE("Cannot open block device %s\n", real_blkdev);
3004 goto error_unencrypted;
3005 }
3006 unsigned long nr_sec;
3007 get_blkdev_size(fd, &nr_sec);
3008 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003009 SLOGE("Cannot get size of block device %s\n", real_blkdev);
3010 goto error_unencrypted;
3011 }
3012 close(fd);
3013
3014 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003015 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003016 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00003017 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00003018 if (fs_size_sec == 0)
3019 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3020
Paul Lawrence87999172014-02-20 12:21:31 -08003021 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003022
3023 if (fs_size_sec > max_fs_size_sec) {
3024 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3025 goto error_unencrypted;
3026 }
3027 }
3028
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003029 /* Get a wakelock as this may take a while, and we don't want the
3030 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3031 * wants to keep the screen on, it can grab a full wakelock.
3032 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003033 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003034 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3035
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003036 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003037 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003038 */
3039 property_set("vold.decrypt", "trigger_shutdown_framework");
3040 SLOGD("Just asked init to shut down class main\n");
3041
Jeff Sharkey9c484982015-03-31 10:35:33 -07003042 /* Ask vold to unmount all devices that it manages */
3043 if (vold_unmountAll()) {
3044 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003045 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003046
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003047 /* no_ui means we are being called from init, not settings.
3048 Now we always reboot from settings, so !no_ui means reboot
3049 */
3050 bool onlyCreateHeader = false;
3051 if (!no_ui) {
3052 /* Try fallback, which is to reboot and try there */
3053 onlyCreateHeader = true;
3054 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
3055 if (breadcrumb == 0) {
3056 SLOGE("Failed to create breadcrumb file");
3057 goto error_shutting_down;
3058 }
3059 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003060 }
3061
3062 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003063 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003064 /* Now that /data is unmounted, we need to mount a tmpfs
3065 * /data, set a property saying we're doing inplace encryption,
3066 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003067 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003068 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003069 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003070 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003071 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003072 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003073
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003074 /* restart the framework. */
3075 /* Create necessary paths on /data */
3076 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003077 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003078 }
3079
Ken Sumrall92736ef2012-10-17 20:57:14 -07003080 /* Ugh, shutting down the framework is not synchronous, so until it
3081 * can be fixed, this horrible hack will wait a moment for it all to
3082 * shut down before proceeding. Without it, some devices cannot
3083 * restart the graphics services.
3084 */
3085 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003086 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003087
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003088 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003089 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003090 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003091 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3092 goto error_shutting_down;
3093 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003094
Paul Lawrence87999172014-02-20 12:21:31 -08003095 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3096 crypt_ftr.fs_size = nr_sec
3097 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3098 } else {
3099 crypt_ftr.fs_size = nr_sec;
3100 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003101 /* At this point, we are in an inconsistent state. Until we successfully
3102 complete encryption, a reboot will leave us broken. So mark the
3103 encryption failed in case that happens.
3104 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003105 if (onlyCreateHeader) {
3106 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
3107 } else {
3108 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3109 }
Paul Lawrence87999172014-02-20 12:21:31 -08003110 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003111#ifndef CONFIG_HW_DISK_ENCRYPTION
3112 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3113#else
3114 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3115
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003116 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003117 if (!rc) {
3118 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3119 }
3120
3121 rc = set_hw_device_encryption_key(passwd,
3122 (char*) crypt_ftr.crypto_type_name);
3123 if (!rc) {
3124 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3125 goto error_shutting_down;
3126 }
3127#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003128
Paul Lawrence87999172014-02-20 12:21:31 -08003129 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003130 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
3131 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08003132 SLOGE("Cannot create encrypted master key\n");
3133 goto error_shutting_down;
3134 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003135
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003136 /* Replace scrypted intermediate key if we are preparing for a reboot */
3137 if (onlyCreateHeader) {
3138 unsigned char fake_master_key[KEY_LEN_BYTES];
3139 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
3140 memset(fake_master_key, 0, sizeof(fake_master_key));
3141 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
3142 encrypted_fake_master_key, &crypt_ftr);
3143 }
3144
Paul Lawrence87999172014-02-20 12:21:31 -08003145 /* Write the key to the end of the partition */
3146 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003147
Paul Lawrence87999172014-02-20 12:21:31 -08003148 /* If any persistent data has been remembered, save it.
3149 * If none, create a valid empty table and save that.
3150 */
3151 if (!persist_data) {
3152 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3153 if (pdata) {
3154 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3155 persist_data = pdata;
3156 }
3157 }
3158 if (persist_data) {
3159 save_persistent_data();
3160 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003161 }
3162
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003163 if (onlyCreateHeader) {
3164 sleep(2);
3165 cryptfs_reboot(reboot);
3166 }
3167
3168 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
Ajay Dudani87701e22014-09-17 21:02:52 -07003169 /* startup service classes main and late_start */
3170 property_set("vold.decrypt", "trigger_restart_min_framework");
3171 SLOGD("Just triggered restart_min_framework\n");
3172
3173 /* OK, the framework is restarted and will soon be showing a
3174 * progress bar. Time to setup an encrypted mapping, and
3175 * either write a new filesystem, or encrypt in place updating
3176 * the progress bar as we work.
3177 */
3178 }
3179
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003180 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003181 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003182 CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003183
Paul Lawrence87999172014-02-20 12:21:31 -08003184 /* If we are continuing, check checksums match */
3185 rc = 0;
3186 if (previously_encrypted_upto) {
3187 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3188 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003189
Paul Lawrence87999172014-02-20 12:21:31 -08003190 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3191 sizeof(hash_first_block)) != 0) {
3192 SLOGE("Checksums do not match - trigger wipe");
3193 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003194 }
3195 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003196
Paul Lawrence87999172014-02-20 12:21:31 -08003197 if (!rc) {
3198 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3199 crypto_blkdev, real_blkdev,
3200 previously_encrypted_upto);
3201 }
3202
3203 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003204 if (!rc && how == CRYPTO_ENABLE_INPLACE
3205 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003206 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3207 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003208 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003209 SLOGE("Error calculating checksum for continuing encryption");
3210 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003211 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003212 }
3213
3214 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003215 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003216
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003217 if (! rc) {
3218 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003219 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003220
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003221 if (how == CRYPTO_ENABLE_INPLACE
3222 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003223 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3224 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003225 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003226 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003227
Paul Lawrence6bfed202014-07-28 12:47:22 -07003228 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003229
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003230 if (how == CRYPTO_ENABLE_WIPE
3231 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003232 char value[PROPERTY_VALUE_MAX];
3233 property_get("ro.crypto.state", value, "");
3234 if (!strcmp(value, "")) {
3235 /* default encryption - continue first boot sequence */
3236 property_set("ro.crypto.state", "encrypted");
Paul Lawrence4ed45262016-03-10 15:44:21 -08003237 property_set("ro.crypto.type", "block");
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003238 release_wake_lock(lockid);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003239 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
3240 // Bring up cryptkeeper that will check the password and set it
3241 property_set("vold.decrypt", "trigger_shutdown_framework");
3242 sleep(2);
3243 property_set("vold.encrypt_progress", "");
3244 cryptfs_trigger_restart_min_framework();
3245 } else {
3246 cryptfs_check_passwd(DEFAULT_PASSWORD);
3247 cryptfs_restart_internal(1);
3248 }
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003249 return 0;
3250 } else {
3251 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003252 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003253 }
Paul Lawrence87999172014-02-20 12:21:31 -08003254 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003255 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003256 cryptfs_reboot(shutdown);
3257 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003258 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003259 char value[PROPERTY_VALUE_MAX];
3260
Ken Sumrall319369a2012-06-27 16:30:18 -07003261 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003262 if (!strcmp(value, "1")) {
3263 /* wipe data if encryption failed */
3264 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3265 mkdir("/cache/recovery", 0700);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003266 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003267 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003268 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3269 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003270 close(fd);
3271 } else {
3272 SLOGE("could not open /cache/recovery/command\n");
3273 }
Paul Lawrence87999172014-02-20 12:21:31 -08003274 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003275 } else {
3276 /* set property to trigger dialog */
3277 property_set("vold.encrypt_progress", "error_partially_encrypted");
3278 release_wake_lock(lockid);
3279 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003280 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003281 }
3282
Ken Sumrall3ed82362011-01-28 23:31:16 -08003283 /* hrm, the encrypt step claims success, but the reboot failed.
3284 * This should not happen.
3285 * Set the property and return. Hope the framework can deal with it.
3286 */
3287 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003288 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003289 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003290
3291error_unencrypted:
3292 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003293 if (lockid[0]) {
3294 release_wake_lock(lockid);
3295 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003296 return -1;
3297
3298error_shutting_down:
3299 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3300 * but the framework is stopped and not restarted to show the error, so it's up to
3301 * vold to restart the system.
3302 */
3303 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003304 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003305
3306 /* shouldn't get here */
3307 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003308 if (lockid[0]) {
3309 release_wake_lock(lockid);
3310 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003311 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003312}
3313
Paul Lawrence569649f2015-09-09 12:13:00 -07003314int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003315{
Paul Lawrence569649f2015-09-09 12:13:00 -07003316 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003317}
3318
Paul Lawrence569649f2015-09-09 12:13:00 -07003319int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003320{
3321 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07003322 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003323}
3324
3325int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003326{
Paul Crowley38132a12016-02-09 09:50:32 +00003327 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003328 SLOGE("cryptfs_changepw not valid for file encryption");
3329 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003330 }
3331
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003332 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003333 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003334
3335 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003336 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003337 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003338 return -1;
3339 }
3340
Paul Lawrencef4faa572014-01-29 13:31:03 -08003341 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3342 SLOGE("Invalid crypt_type %d", crypt_type);
3343 return -1;
3344 }
3345
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003346 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003347 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003348 SLOGE("Error getting crypt footer and key");
3349 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003350 }
3351
Paul Lawrencef4faa572014-01-29 13:31:03 -08003352 crypt_ftr.crypt_type = crypt_type;
3353
JP Abgrall933216c2015-02-11 13:44:32 -08003354 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003355 : newpw,
3356 crypt_ftr.salt,
3357 saved_master_key,
3358 crypt_ftr.master_key,
3359 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003360 if (rc) {
3361 SLOGE("Encrypt master key failed: %d", rc);
3362 return -1;
3363 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003364 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003365 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003366
Ajay Dudani87701e22014-09-17 21:02:52 -07003367#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003368 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3369 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3370 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3371 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3372 if (!rc)
3373 return -1;
3374 } else {
3375 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3376 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3377 if (!rc)
3378 return -1;
3379 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003380 }
3381#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003382 return 0;
3383}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003384
Rubin Xu85c01f92014-10-13 12:49:54 +01003385static unsigned int persist_get_max_entries(int encrypted) {
3386 struct crypt_mnt_ftr crypt_ftr;
3387 unsigned int dsize;
3388 unsigned int max_persistent_entries;
3389
3390 /* If encrypted, use the values from the crypt_ftr, otherwise
3391 * use the values for the current spec.
3392 */
3393 if (encrypted) {
3394 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3395 return -1;
3396 }
3397 dsize = crypt_ftr.persist_data_size;
3398 } else {
3399 dsize = CRYPT_PERSIST_DATA_SIZE;
3400 }
3401
3402 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3403 sizeof(struct crypt_persist_entry);
3404
3405 return max_persistent_entries;
3406}
3407
3408static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003409{
3410 unsigned int i;
3411
3412 if (persist_data == NULL) {
3413 return -1;
3414 }
3415 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3416 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3417 /* We found it! */
3418 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3419 return 0;
3420 }
3421 }
3422
3423 return -1;
3424}
3425
Rubin Xu85c01f92014-10-13 12:49:54 +01003426static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003427{
3428 unsigned int i;
3429 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003430 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003431
3432 if (persist_data == NULL) {
3433 return -1;
3434 }
3435
Rubin Xu85c01f92014-10-13 12:49:54 +01003436 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003437
3438 num = persist_data->persist_valid_entries;
3439
3440 for (i = 0; i < num; i++) {
3441 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3442 /* We found an existing entry, update it! */
3443 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3444 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3445 return 0;
3446 }
3447 }
3448
3449 /* We didn't find it, add it to the end, if there is room */
3450 if (persist_data->persist_valid_entries < max_persistent_entries) {
3451 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3452 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3453 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3454 persist_data->persist_valid_entries++;
3455 return 0;
3456 }
3457
3458 return -1;
3459}
3460
Rubin Xu85c01f92014-10-13 12:49:54 +01003461/**
3462 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3463 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3464 */
3465static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003466 unsigned int field_len;
3467 unsigned int key_index;
3468 field_len = strlen(field);
3469
3470 if (index == 0) {
3471 // The first key in a multi-entry field is just the filedname itself.
3472 if (!strcmp(key, field)) {
3473 return 1;
3474 }
3475 }
3476 // Match key against "%s_%d" % (field, index)
3477 if (strlen(key) < field_len + 1 + 1) {
3478 // Need at least a '_' and a digit.
3479 return 0;
3480 }
3481 if (strncmp(key, field, field_len)) {
3482 // If the key does not begin with field, it's not a match.
3483 return 0;
3484 }
3485 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3486 return 0;
3487 }
3488 return key_index >= index;
3489}
3490
3491/*
3492 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3493 * remaining entries starting from index will be deleted.
3494 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3495 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3496 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3497 *
3498 */
3499static int persist_del_keys(const char *fieldname, unsigned index)
3500{
3501 unsigned int i;
3502 unsigned int j;
3503 unsigned int num;
3504
3505 if (persist_data == NULL) {
3506 return PERSIST_DEL_KEY_ERROR_OTHER;
3507 }
3508
3509 num = persist_data->persist_valid_entries;
3510
3511 j = 0; // points to the end of non-deleted entries.
3512 // Filter out to-be-deleted entries in place.
3513 for (i = 0; i < num; i++) {
3514 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3515 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3516 j++;
3517 }
3518 }
3519
3520 if (j < num) {
3521 persist_data->persist_valid_entries = j;
3522 // Zeroise the remaining entries
3523 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3524 return PERSIST_DEL_KEY_OK;
3525 } else {
3526 // Did not find an entry matching the given fieldname
3527 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3528 }
3529}
3530
3531static int persist_count_keys(const char *fieldname)
3532{
3533 unsigned int i;
3534 unsigned int count;
3535
3536 if (persist_data == NULL) {
3537 return -1;
3538 }
3539
3540 count = 0;
3541 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3542 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3543 count++;
3544 }
3545 }
3546
3547 return count;
3548}
3549
Ken Sumrall160b4d62013-04-22 12:15:39 -07003550/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003551int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003552{
Paul Crowley38132a12016-02-09 09:50:32 +00003553 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003554 SLOGE("Cannot get field when file encrypted");
3555 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003556 }
3557
Ken Sumrall160b4d62013-04-22 12:15:39 -07003558 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003559 /* CRYPTO_GETFIELD_OK is success,
3560 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3561 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3562 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003563 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003564 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3565 int i;
3566 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003567
3568 if (persist_data == NULL) {
3569 load_persistent_data();
3570 if (persist_data == NULL) {
3571 SLOGE("Getfield error, cannot load persistent data");
3572 goto out;
3573 }
3574 }
3575
Rubin Xu85c01f92014-10-13 12:49:54 +01003576 // Read value from persistent entries. If the original value is split into multiple entries,
3577 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003578 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003579 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3580 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3581 // value too small
3582 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3583 goto out;
3584 }
3585 rc = CRYPTO_GETFIELD_OK;
3586
3587 for (i = 1; /* break explicitly */; i++) {
3588 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3589 (int) sizeof(temp_field)) {
3590 // If the fieldname is very long, we stop as soon as it begins to overflow the
3591 // maximum field length. At this point we have in fact fully read out the original
3592 // value because cryptfs_setfield would not allow fields with longer names to be
3593 // written in the first place.
3594 break;
3595 }
3596 if (!persist_get_key(temp_field, temp_value)) {
3597 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3598 // value too small.
3599 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3600 goto out;
3601 }
3602 } else {
3603 // Exhaust all entries.
3604 break;
3605 }
3606 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003607 } else {
3608 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003609 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003610 }
3611
3612out:
3613 return rc;
3614}
3615
3616/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003617int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003618{
Paul Crowley38132a12016-02-09 09:50:32 +00003619 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003620 SLOGE("Cannot set field when file encrypted");
3621 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003622 }
3623
Ken Sumrall160b4d62013-04-22 12:15:39 -07003624 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003625 /* 0 is success, negative values are error */
3626 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003627 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003628 unsigned int field_id;
3629 char temp_field[PROPERTY_KEY_MAX];
3630 unsigned int num_entries;
3631 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003632
3633 if (persist_data == NULL) {
3634 load_persistent_data();
3635 if (persist_data == NULL) {
3636 SLOGE("Setfield error, cannot load persistent data");
3637 goto out;
3638 }
3639 }
3640
3641 property_get("ro.crypto.state", encrypted_state, "");
3642 if (!strcmp(encrypted_state, "encrypted") ) {
3643 encrypted = 1;
3644 }
3645
Rubin Xu85c01f92014-10-13 12:49:54 +01003646 // Compute the number of entries required to store value, each entry can store up to
3647 // (PROPERTY_VALUE_MAX - 1) chars
3648 if (strlen(value) == 0) {
3649 // Empty value also needs one entry to store.
3650 num_entries = 1;
3651 } else {
3652 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3653 }
3654
3655 max_keylen = strlen(fieldname);
3656 if (num_entries > 1) {
3657 // Need an extra "_%d" suffix.
3658 max_keylen += 1 + log10(num_entries);
3659 }
3660 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3661 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003662 goto out;
3663 }
3664
Rubin Xu85c01f92014-10-13 12:49:54 +01003665 // Make sure we have enough space to write the new value
3666 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3667 persist_get_max_entries(encrypted)) {
3668 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3669 goto out;
3670 }
3671
3672 // Now that we know persist_data has enough space for value, let's delete the old field first
3673 // to make up space.
3674 persist_del_keys(fieldname, 0);
3675
3676 if (persist_set_key(fieldname, value, encrypted)) {
3677 // fail to set key, should not happen as we have already checked the available space
3678 SLOGE("persist_set_key() error during setfield()");
3679 goto out;
3680 }
3681
3682 for (field_id = 1; field_id < num_entries; field_id++) {
3683 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3684
3685 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3686 // fail to set key, should not happen as we have already checked the available space.
3687 SLOGE("persist_set_key() error during setfield()");
3688 goto out;
3689 }
3690 }
3691
Ken Sumrall160b4d62013-04-22 12:15:39 -07003692 /* If we are running encrypted, save the persistent data now */
3693 if (encrypted) {
3694 if (save_persistent_data()) {
3695 SLOGE("Setfield error, cannot save persistent data");
3696 goto out;
3697 }
3698 }
3699
Rubin Xu85c01f92014-10-13 12:49:54 +01003700 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003701
3702out:
3703 return rc;
3704}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003705
3706/* Checks userdata. Attempt to mount the volume if default-
3707 * encrypted.
3708 * On success trigger next init phase and return 0.
3709 * Currently do not handle failure - see TODO below.
3710 */
3711int cryptfs_mount_default_encrypted(void)
3712{
3713 char decrypt_state[PROPERTY_VALUE_MAX];
3714 property_get("vold.decrypt", decrypt_state, "0");
3715 if (!strcmp(decrypt_state, "0")) {
3716 SLOGE("Not encrypted - should not call here");
3717 } else {
3718 int crypt_type = cryptfs_get_password_type();
3719 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3720 SLOGE("Bad crypt type - error");
3721 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3722 SLOGD("Password is not default - "
3723 "starting min framework to prompt");
3724 property_set("vold.decrypt", "trigger_restart_min_framework");
3725 return 0;
3726 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3727 SLOGD("Password is default - restarting filesystem");
3728 cryptfs_restart_internal(0);
3729 return 0;
3730 } else {
3731 SLOGE("Encrypted, default crypt type but can't decrypt");
3732 }
3733 }
3734
Paul Lawrence6bfed202014-07-28 12:47:22 -07003735 /** Corrupt. Allow us to boot into framework, which will detect bad
3736 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003737 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003738 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003739 return 0;
3740}
3741
3742/* Returns type of the password, default, pattern, pin or password.
3743 */
3744int cryptfs_get_password_type(void)
3745{
Paul Crowley38132a12016-02-09 09:50:32 +00003746 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003747 SLOGE("cryptfs_get_password_type not valid for file encryption");
3748 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003749 }
3750
Paul Lawrencef4faa572014-01-29 13:31:03 -08003751 struct crypt_mnt_ftr crypt_ftr;
3752
3753 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3754 SLOGE("Error getting crypt footer and key\n");
3755 return -1;
3756 }
3757
Paul Lawrence6bfed202014-07-28 12:47:22 -07003758 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3759 return -1;
3760 }
3761
Paul Lawrencef4faa572014-01-29 13:31:03 -08003762 return crypt_ftr.crypt_type;
3763}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003764
Paul Lawrence05335c32015-03-05 09:46:23 -08003765const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003766{
Paul Crowley38132a12016-02-09 09:50:32 +00003767 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003768 SLOGE("cryptfs_get_password not valid for file encryption");
3769 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003770 }
3771
Paul Lawrence399317e2014-03-10 13:20:50 -07003772 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003773 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003774 if (now.tv_sec < password_expiry_time) {
3775 return password;
3776 } else {
3777 cryptfs_clear_password();
3778 return 0;
3779 }
3780}
3781
3782void cryptfs_clear_password()
3783{
3784 if (password) {
3785 size_t len = strlen(password);
3786 memset(password, 0, len);
3787 free(password);
3788 password = 0;
3789 password_expiry_time = 0;
3790 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003791}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003792
3793int cryptfs_enable_file()
3794{
Paul Crowley38132a12016-02-09 09:50:32 +00003795 return e4crypt_initialize_global_de();
Paul Lawrence731a7a22015-04-28 22:14:15 +00003796}
3797
Paul Lawrence0c247462015-10-29 10:30:57 -07003798int cryptfs_isConvertibleToFBE()
3799{
3800 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3801 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
3802}
3803
Paul Lawrence731a7a22015-04-28 22:14:15 +00003804int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3805{
3806 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3807 SLOGE("Failed to initialize crypt_ftr");
3808 return -1;
3809 }
3810
3811 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3812 crypt_ftr->salt, crypt_ftr)) {
3813 SLOGE("Cannot create encrypted master key\n");
3814 return -1;
3815 }
3816
3817 //crypt_ftr->keysize = key_length / 8;
3818 return 0;
3819}
3820
3821int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3822 unsigned char* master_key)
3823{
3824 int rc;
3825
Paul Lawrence731a7a22015-04-28 22:14:15 +00003826 unsigned char* intermediate_key = 0;
3827 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003828
3829 if (password == 0 || *password == 0) {
3830 password = DEFAULT_PASSWORD;
3831 }
3832
Paul Lawrence731a7a22015-04-28 22:14:15 +00003833 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3834 &intermediate_key_size);
3835
Paul Lawrence300dae72016-03-11 11:02:52 -08003836 if (rc) {
3837 SLOGE("Can't calculate intermediate key");
3838 return rc;
3839 }
3840
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003841 int N = 1 << ftr->N_factor;
3842 int r = 1 << ftr->r_factor;
3843 int p = 1 << ftr->p_factor;
3844
3845 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3846
3847 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3848 ftr->salt, sizeof(ftr->salt), N, r, p,
3849 scrypted_intermediate_key,
3850 sizeof(scrypted_intermediate_key));
3851
3852 free(intermediate_key);
3853
3854 if (rc) {
Paul Lawrence300dae72016-03-11 11:02:52 -08003855 SLOGE("Can't scrypt intermediate key");
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003856 return rc;
3857 }
3858
3859 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3860 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00003861}
3862
3863int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3864 const unsigned char* master_key)
3865{
3866 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3867 ftr);
3868}