blob: 7ca05b0f976a431a8d07156372dbb3c94d5af332 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080041#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080046#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080047#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080048#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080049#define LOG_TAG "Cryptfs"
50#include "cutils/log.h"
51#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070052#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080053#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070054#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070055#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070056#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070057#include "crypto_scrypt.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000058#include "Ext4Crypt.h"
59#include "ext4_crypt_init_extensions.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
Ken Sumrall29d8da82011-05-18 17:20:07 -070086#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070087#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070088
Ken Sumralle919efe2012-09-29 17:07:41 -070089#define TABLE_LOAD_RETRIES 10
90
Shawn Willden47ba10d2014-09-03 17:07:06 -060091#define RSA_KEY_SIZE 2048
92#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
93#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060094#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070095
Paul Lawrence8e3f4512014-09-08 10:11:17 -070096#define RETRY_MOUNT_ATTEMPTS 10
97#define RETRY_MOUNT_DELAY_SECONDS 1
98
Ken Sumrall8f869aa2010-12-03 03:47:09 -080099char *me = "cryptfs";
100
Jason parks70a4b3f2011-01-28 10:10:47 -0600101static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700102static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600103static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700104static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800105
Shawn Willdenda6e8992015-06-03 09:40:45 -0600106static int keymaster_init(keymaster0_device_t **keymaster0_dev,
107 keymaster1_device_t **keymaster1_dev)
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700108{
109 int rc;
110
111 const hw_module_t* mod;
112 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
113 if (rc) {
114 ALOGE("could not find any keystore module");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600115 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700116 }
117
Shawn Willdenda6e8992015-06-03 09:40:45 -0600118 SLOGI("keymaster module name is %s", mod->name);
119 SLOGI("keymaster version is %d", mod->module_api_version);
120
121 *keymaster0_dev = NULL;
122 *keymaster1_dev = NULL;
123 if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
124 SLOGI("Found keymaster1 module, using keymaster1 API.");
125 rc = keymaster1_open(mod, keymaster1_dev);
126 } else {
127 SLOGI("Found keymaster0 module, using keymaster0 API.");
128 rc = keymaster0_open(mod, keymaster0_dev);
129 }
130
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700131 if (rc) {
132 ALOGE("could not open keymaster device in %s (%s)",
Shawn Willdenda6e8992015-06-03 09:40:45 -0600133 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
134 goto err;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700135 }
136
137 return 0;
138
Shawn Willdenda6e8992015-06-03 09:40:45 -0600139err:
140 *keymaster0_dev = NULL;
141 *keymaster1_dev = NULL;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700142 return rc;
143}
144
145/* Should we use keymaster? */
146static int keymaster_check_compatibility()
147{
Shawn Willdenda6e8992015-06-03 09:40:45 -0600148 keymaster0_device_t *keymaster0_dev = 0;
149 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700150 int rc = 0;
151
Shawn Willdenda6e8992015-06-03 09:40:45 -0600152 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700153 SLOGE("Failed to init keymaster");
154 rc = -1;
155 goto out;
156 }
157
Shawn Willdenda6e8992015-06-03 09:40:45 -0600158 if (keymaster1_dev) {
159 rc = 1;
160 goto out;
161 }
Paul Lawrence8c008392014-05-06 14:02:48 -0700162
Shawn Willdenda6e8992015-06-03 09:40:45 -0600163 // TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
164 // should work.
165 if (keymaster0_dev->common.module->module_api_version
Paul Lawrence8c008392014-05-06 14:02:48 -0700166 < KEYMASTER_MODULE_API_VERSION_0_3) {
167 rc = 0;
168 goto out;
169 }
170
Shawn Willdenda6e8992015-06-03 09:40:45 -0600171 if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
172 (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700173 rc = 1;
174 }
175
176out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600177 if (keymaster1_dev) {
178 keymaster1_close(keymaster1_dev);
179 }
180 if (keymaster0_dev) {
181 keymaster0_close(keymaster0_dev);
182 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700183 return rc;
184}
185
186/* Create a new keymaster key and store it in this footer */
187static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
188{
189 uint8_t* key = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600190 keymaster0_device_t *keymaster0_dev = 0;
191 keymaster1_device_t *keymaster1_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700192
Shawn Willdenda6e8992015-06-03 09:40:45 -0600193 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700194 SLOGE("Failed to init keymaster");
195 return -1;
196 }
197
198 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600199 size_t key_size = 0;
200 if (keymaster1_dev) {
201 keymaster_key_param_t params[] = {
202 /* Algorithm & size specifications. Stick with RSA for now. Switch to AES later. */
203 keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
204 keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
205 keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700206
Shawn Willden86af3552015-06-24 07:21:54 -0700207 /* The only allowed purpose for this key is signing. */
208 keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
209
210 /* Padding & digest specifications. */
Shawn Willdenda6e8992015-06-03 09:40:45 -0600211 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
Shawn Willdenda6e8992015-06-03 09:40:45 -0600212 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700213
Shawn Willdenda6e8992015-06-03 09:40:45 -0600214 /* Require that the key be usable in standalone mode. File system isn't available. */
215 keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
216
217 /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
218 keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
219
Shawn Willdenda6e8992015-06-03 09:40:45 -0600220 /* Rate-limit key usage attempts, to rate-limit brute force */
221 keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
222 };
223 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
224 keymaster_key_blob_t key_blob;
225 keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, &param_set,
226 &key_blob,
227 NULL /* characteristics */);
228 if (error != KM_ERROR_OK) {
229 SLOGE("Failed to generate keymaster1 key, error %d", error);
230 rc = -1;
231 goto out;
232 }
233
234 key = (uint8_t*)key_blob.key_material;
235 key_size = key_blob.key_material_size;
236 }
237 else if (keymaster0_dev) {
238 keymaster_rsa_keygen_params_t params;
239 memset(&params, '\0', sizeof(params));
240 params.public_exponent = RSA_EXPONENT;
241 params.modulus_size = RSA_KEY_SIZE;
242
243 if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, &params,
244 &key, &key_size)) {
245 SLOGE("Failed to generate keypair");
246 rc = -1;
247 goto out;
248 }
249 } else {
250 SLOGE("Cryptfs bug: keymaster_init succeeded but didn't initialize a device");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700251 rc = -1;
252 goto out;
253 }
254
255 if (key_size > KEYMASTER_BLOB_SIZE) {
256 SLOGE("Keymaster key too large for crypto footer");
257 rc = -1;
258 goto out;
259 }
260
261 memcpy(ftr->keymaster_blob, key, key_size);
262 ftr->keymaster_blob_size = key_size;
263
264out:
Shawn Willdenda6e8992015-06-03 09:40:45 -0600265 if (keymaster0_dev)
266 keymaster0_close(keymaster0_dev);
267 if (keymaster1_dev)
268 keymaster1_close(keymaster1_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700269 free(key);
270 return rc;
271}
272
Shawn Willdene17a9c42014-09-08 13:04:08 -0600273/* This signs the given object using the keymaster key. */
274static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600275 const unsigned char *object,
276 const size_t object_size,
277 unsigned char **signature,
278 size_t *signature_size)
279{
280 int rc = 0;
Shawn Willdenda6e8992015-06-03 09:40:45 -0600281 keymaster0_device_t *keymaster0_dev = 0;
282 keymaster1_device_t *keymaster1_dev = 0;
283 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600284 SLOGE("Failed to init keymaster");
Shawn Willdenda6e8992015-06-03 09:40:45 -0600285 rc = -1;
286 goto out;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600287 }
288
Shawn Willden47ba10d2014-09-03 17:07:06 -0600289 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600290 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600291 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600292
Shawn Willdene17a9c42014-09-08 13:04:08 -0600293 // To sign a message with RSA, the message must satisfy two
294 // constraints:
295 //
296 // 1. The message, when interpreted as a big-endian numeric value, must
297 // be strictly less than the public modulus of the RSA key. Note
298 // that because the most significant bit of the public modulus is
299 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
300 // key), an n-bit message with most significant bit 0 always
301 // satisfies this requirement.
302 //
303 // 2. The message must have the same length in bits as the public
304 // modulus of the RSA key. This requirement isn't mathematically
305 // necessary, but is necessary to ensure consistency in
306 // implementations.
307 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600308 case KDF_SCRYPT_KEYMASTER:
309 // This ensures the most significant byte of the signed message
310 // is zero. We could have zero-padded to the left instead, but
311 // this approach is slightly more robust against changes in
312 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600313 // so) because we really should be using a proper deterministic
314 // RSA padding function, such as PKCS1.
Shawn Willdene17a9c42014-09-08 13:04:08 -0600315 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
316 SLOGI("Signing safely-padded object");
317 break;
318 default:
319 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Shawn Willdenda6e8992015-06-03 09:40:45 -0600320 rc = -1;
321 goto out;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600322 }
323
Shawn Willdenda6e8992015-06-03 09:40:45 -0600324 if (keymaster0_dev) {
325 keymaster_rsa_sign_params_t params;
326 params.digest_type = DIGEST_NONE;
327 params.padding_type = PADDING_NONE;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600328
Shawn Willdenda6e8992015-06-03 09:40:45 -0600329 rc = keymaster0_dev->sign_data(keymaster0_dev,
330 &params,
331 ftr->keymaster_blob,
332 ftr->keymaster_blob_size,
333 to_sign,
334 to_sign_size,
335 signature,
336 signature_size);
337 goto out;
338 } else if (keymaster1_dev) {
339 keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
340 keymaster_key_param_t params[] = {
341 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
342 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
343 };
344 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
345 keymaster_operation_handle_t op_handle;
346 keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
347 &param_set, NULL /* out_params */,
348 &op_handle);
Shawn Willden04170602015-06-18 12:26:59 -0600349 if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
Shawn Willdenda6e8992015-06-03 09:40:45 -0600350 // Key usage has been rate-limited. Wait a bit and try again.
351 sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
352 error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
353 &param_set, NULL /* out_params */,
354 &op_handle);
355 }
356 if (error != KM_ERROR_OK) {
357 SLOGE("Error starting keymaster signature transaction: %d", error);
358 rc = -1;
359 goto out;
360 }
361
362 keymaster_blob_t input = { to_sign, to_sign_size };
363 size_t input_consumed;
364 error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
365 &input, &input_consumed, NULL /* out_params */,
366 NULL /* output */);
367 if (error != KM_ERROR_OK) {
368 SLOGE("Error sending data to keymaster signature transaction: %d", error);
369 rc = -1;
370 goto out;
371 }
372 if (input_consumed != to_sign_size) {
373 // This should never happen. If it does, it's a bug in the keymaster implementation.
374 SLOGE("Keymaster update() did not consume all data.");
375 keymaster1_dev->abort(keymaster1_dev, op_handle);
376 rc = -1;
377 goto out;
378 }
379
380 keymaster_blob_t tmp_sig;
381 error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
382 NULL /* verify signature */, NULL /* out_params */,
383 &tmp_sig);
384 if (error != KM_ERROR_OK) {
385 SLOGE("Error finishing keymaster signature transaction: %d", error);
386 rc = -1;
387 goto out;
388 }
389
390 *signature = (uint8_t*)tmp_sig.data;
391 *signature_size = tmp_sig.data_length;
392 } else {
393 SLOGE("Cryptfs bug: keymaster_init succeded but didn't initialize a device.");
394 rc = -1;
395 goto out;
396 }
397
398 out:
399 if (keymaster1_dev)
400 keymaster1_close(keymaster1_dev);
401 if (keymaster0_dev)
402 keymaster0_close(keymaster0_dev);
403
404 return rc;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600405}
406
Paul Lawrence399317e2014-03-10 13:20:50 -0700407/* Store password when userdata is successfully decrypted and mounted.
408 * Cleared by cryptfs_clear_password
409 *
410 * To avoid a double prompt at boot, we need to store the CryptKeeper
411 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
412 * Since the entire framework is torn down and rebuilt after encryption,
413 * we have to use a daemon or similar to store the password. Since vold
414 * is secured against IPC except from system processes, it seems a reasonable
415 * place to store this.
416 *
417 * password should be cleared once it has been used.
418 *
419 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800420 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700421static char* password = 0;
422static int password_expiry_time = 0;
423static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800424
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800425extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800426
Paul Lawrence87999172014-02-20 12:21:31 -0800427enum RebootType {reboot, recovery, shutdown};
428static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700429{
Paul Lawrence87999172014-02-20 12:21:31 -0800430 switch(rt) {
431 case reboot:
432 property_set(ANDROID_RB_PROPERTY, "reboot");
433 break;
434
435 case recovery:
436 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
437 break;
438
439 case shutdown:
440 property_set(ANDROID_RB_PROPERTY, "shutdown");
441 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700442 }
Paul Lawrence87999172014-02-20 12:21:31 -0800443
Ken Sumralladfba362013-06-04 16:37:52 -0700444 sleep(20);
445
446 /* Shouldn't get here, reboot should happen before sleep times out */
447 return;
448}
449
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800450static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
451{
452 memset(io, 0, dataSize);
453 io->data_size = dataSize;
454 io->data_start = sizeof(struct dm_ioctl);
455 io->version[0] = 4;
456 io->version[1] = 0;
457 io->version[2] = 0;
458 io->flags = flags;
459 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100460 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800461 }
462}
463
Kenny Rootc4c70f12013-06-14 12:11:38 -0700464/**
465 * Gets the default device scrypt parameters for key derivation time tuning.
466 * The parameters should lead to about one second derivation time for the
467 * given device.
468 */
469static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
470 const int default_params[] = SCRYPT_DEFAULTS;
471 int params[] = SCRYPT_DEFAULTS;
472 char paramstr[PROPERTY_VALUE_MAX];
473 char *token;
474 char *saveptr;
475 int i;
476
477 property_get(SCRYPT_PROP, paramstr, "");
478 if (paramstr[0] != '\0') {
479 /*
480 * The token we're looking for should be three integers separated by
481 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
482 */
Kenny Root2947e342013-08-14 15:54:49 -0700483 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
484 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700485 i++, token = strtok_r(NULL, ":", &saveptr)) {
486 char *endptr;
487 params[i] = strtol(token, &endptr, 10);
488
489 /*
490 * Check that there was a valid number and it's 8-bit. If not,
491 * break out and the end check will take the default values.
492 */
493 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
494 break;
495 }
496 }
497
498 /*
499 * If there were not enough tokens or a token was malformed (not an
500 * integer), it will end up here and the default parameters can be
501 * taken.
502 */
503 if ((i != 3) || (token != NULL)) {
504 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
505 memcpy(params, default_params, sizeof(params));
506 }
507 }
508
509 ftr->N_factor = params[0];
510 ftr->r_factor = params[1];
511 ftr->p_factor = params[2];
512}
513
Ken Sumrall3ed82362011-01-28 23:31:16 -0800514static unsigned int get_fs_size(char *dev)
515{
516 int fd, block_size;
517 struct ext4_super_block sb;
518 off64_t len;
519
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700520 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800521 SLOGE("Cannot open device to get filesystem size ");
522 return 0;
523 }
524
525 if (lseek64(fd, 1024, SEEK_SET) < 0) {
526 SLOGE("Cannot seek to superblock");
527 return 0;
528 }
529
530 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
531 SLOGE("Cannot read superblock");
532 return 0;
533 }
534
535 close(fd);
536
Daniel Rosenberge82df162014-08-15 22:19:23 +0000537 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
538 SLOGE("Not a valid ext4 superblock");
539 return 0;
540 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800541 block_size = 1024 << sb.s_log_block_size;
542 /* compute length in bytes */
543 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
544
545 /* return length in sectors */
546 return (unsigned int) (len / 512);
547}
548
Ken Sumrall160b4d62013-04-22 12:15:39 -0700549static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
550{
551 static int cached_data = 0;
552 static off64_t cached_off = 0;
553 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
554 int fd;
555 char key_loc[PROPERTY_VALUE_MAX];
556 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700557 int rc = -1;
558
559 if (!cached_data) {
560 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
561
562 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700563 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700564 SLOGE("Cannot open real block device %s\n", real_blkdev);
565 return -1;
566 }
567
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900568 unsigned long nr_sec = 0;
569 get_blkdev_size(fd, &nr_sec);
570 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700571 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
572 * encryption info footer and key, and plenty of bytes to spare for future
573 * growth.
574 */
575 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
576 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
577 cached_data = 1;
578 } else {
579 SLOGE("Cannot get size of block device %s\n", real_blkdev);
580 }
581 close(fd);
582 } else {
583 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
584 cached_off = 0;
585 cached_data = 1;
586 }
587 }
588
589 if (cached_data) {
590 if (metadata_fname) {
591 *metadata_fname = cached_metadata_fname;
592 }
593 if (off) {
594 *off = cached_off;
595 }
596 rc = 0;
597 }
598
599 return rc;
600}
601
Ken Sumralle8744072011-01-18 22:01:55 -0800602/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800603 * update the failed mount count but not change the key.
604 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700605static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800606{
607 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800608 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700609 /* starting_off is set to the SEEK_SET offset
610 * where the crypto structure starts
611 */
612 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800613 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700614 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700615 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800616
Ken Sumrall160b4d62013-04-22 12:15:39 -0700617 if (get_crypt_ftr_info(&fname, &starting_off)) {
618 SLOGE("Unable to get crypt_ftr_info\n");
619 return -1;
620 }
621 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700622 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700623 return -1;
624 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700625 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700626 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700627 return -1;
628 }
629
630 /* Seek to the start of the crypt footer */
631 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
632 SLOGE("Cannot seek to real block device footer\n");
633 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800634 }
635
636 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
637 SLOGE("Cannot write real block device footer\n");
638 goto errout;
639 }
640
Ken Sumrall3be890f2011-09-14 16:53:46 -0700641 fstat(fd, &statbuf);
642 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700643 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700644 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800645 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800646 goto errout;
647 }
648 }
649
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800650 /* Success! */
651 rc = 0;
652
653errout:
654 close(fd);
655 return rc;
656
657}
658
Ken Sumrall160b4d62013-04-22 12:15:39 -0700659static inline int unix_read(int fd, void* buff, int len)
660{
661 return TEMP_FAILURE_RETRY(read(fd, buff, len));
662}
663
664static inline int unix_write(int fd, const void* buff, int len)
665{
666 return TEMP_FAILURE_RETRY(write(fd, buff, len));
667}
668
669static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
670{
671 memset(pdata, 0, len);
672 pdata->persist_magic = PERSIST_DATA_MAGIC;
673 pdata->persist_valid_entries = 0;
674}
675
676/* A routine to update the passed in crypt_ftr to the lastest version.
677 * fd is open read/write on the device that holds the crypto footer and persistent
678 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
679 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
680 */
681static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
682{
Kenny Root7434b312013-06-14 11:29:53 -0700683 int orig_major = crypt_ftr->major_version;
684 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700685
Kenny Root7434b312013-06-14 11:29:53 -0700686 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
687 struct crypt_persist_data *pdata;
688 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700689
Kenny Rootc4c70f12013-06-14 12:11:38 -0700690 SLOGW("upgrading crypto footer to 1.1");
691
Kenny Root7434b312013-06-14 11:29:53 -0700692 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
693 if (pdata == NULL) {
694 SLOGE("Cannot allocate persisent data\n");
695 return;
696 }
697 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
698
699 /* Need to initialize the persistent data area */
700 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
701 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100702 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700703 return;
704 }
705 /* Write all zeros to the first copy, making it invalid */
706 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
707
708 /* Write a valid but empty structure to the second copy */
709 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
710 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
711
712 /* Update the footer */
713 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
714 crypt_ftr->persist_data_offset[0] = pdata_offset;
715 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
716 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100717 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700718 }
719
Paul Lawrencef4faa572014-01-29 13:31:03 -0800720 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700721 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800722 /* But keep the old kdf_type.
723 * It will get updated later to KDF_SCRYPT after the password has been verified.
724 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700725 crypt_ftr->kdf_type = KDF_PBKDF2;
726 get_device_scrypt_params(crypt_ftr);
727 crypt_ftr->minor_version = 2;
728 }
729
Paul Lawrencef4faa572014-01-29 13:31:03 -0800730 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
731 SLOGW("upgrading crypto footer to 1.3");
732 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
733 crypt_ftr->minor_version = 3;
734 }
735
Kenny Root7434b312013-06-14 11:29:53 -0700736 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
737 if (lseek64(fd, offset, SEEK_SET) == -1) {
738 SLOGE("Cannot seek to crypt footer\n");
739 return;
740 }
741 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700742 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700743}
744
745
746static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800747{
748 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800749 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700750 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800751 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700752 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700753 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800754
Ken Sumrall160b4d62013-04-22 12:15:39 -0700755 if (get_crypt_ftr_info(&fname, &starting_off)) {
756 SLOGE("Unable to get crypt_ftr_info\n");
757 return -1;
758 }
759 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700760 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700761 return -1;
762 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700763 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700764 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700765 return -1;
766 }
767
768 /* Make sure it's 16 Kbytes in length */
769 fstat(fd, &statbuf);
770 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
771 SLOGE("footer file %s is not the expected size!\n", fname);
772 goto errout;
773 }
774
775 /* Seek to the start of the crypt footer */
776 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
777 SLOGE("Cannot seek to real block device footer\n");
778 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800779 }
780
781 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
782 SLOGE("Cannot read real block device footer\n");
783 goto errout;
784 }
785
786 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700787 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800788 goto errout;
789 }
790
Kenny Rootc96a5f82013-06-14 12:08:28 -0700791 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
792 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
793 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800794 goto errout;
795 }
796
Kenny Rootc96a5f82013-06-14 12:08:28 -0700797 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
798 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
799 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800800 }
801
Ken Sumrall160b4d62013-04-22 12:15:39 -0700802 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
803 * copy on disk before returning.
804 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700805 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700806 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800807 }
808
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800809 /* Success! */
810 rc = 0;
811
812errout:
813 close(fd);
814 return rc;
815}
816
Ken Sumrall160b4d62013-04-22 12:15:39 -0700817static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
818{
819 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
820 crypt_ftr->persist_data_offset[1]) {
821 SLOGE("Crypt_ftr persist data regions overlap");
822 return -1;
823 }
824
825 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
826 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
827 return -1;
828 }
829
830 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
831 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
832 CRYPT_FOOTER_OFFSET) {
833 SLOGE("Persistent data extends past crypto footer");
834 return -1;
835 }
836
837 return 0;
838}
839
840static int load_persistent_data(void)
841{
842 struct crypt_mnt_ftr crypt_ftr;
843 struct crypt_persist_data *pdata = NULL;
844 char encrypted_state[PROPERTY_VALUE_MAX];
845 char *fname;
846 int found = 0;
847 int fd;
848 int ret;
849 int i;
850
851 if (persist_data) {
852 /* Nothing to do, we've already loaded or initialized it */
853 return 0;
854 }
855
856
857 /* If not encrypted, just allocate an empty table and initialize it */
858 property_get("ro.crypto.state", encrypted_state, "");
859 if (strcmp(encrypted_state, "encrypted") ) {
860 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
861 if (pdata) {
862 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
863 persist_data = pdata;
864 return 0;
865 }
866 return -1;
867 }
868
869 if(get_crypt_ftr_and_key(&crypt_ftr)) {
870 return -1;
871 }
872
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700873 if ((crypt_ftr.major_version < 1)
874 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700875 SLOGE("Crypt_ftr version doesn't support persistent data");
876 return -1;
877 }
878
879 if (get_crypt_ftr_info(&fname, NULL)) {
880 return -1;
881 }
882
883 ret = validate_persistent_data_storage(&crypt_ftr);
884 if (ret) {
885 return -1;
886 }
887
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700888 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700889 if (fd < 0) {
890 SLOGE("Cannot open %s metadata file", fname);
891 return -1;
892 }
893
894 if (persist_data == NULL) {
895 pdata = malloc(crypt_ftr.persist_data_size);
896 if (pdata == NULL) {
897 SLOGE("Cannot allocate memory for persistent data");
898 goto err;
899 }
900 }
901
902 for (i = 0; i < 2; i++) {
903 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
904 SLOGE("Cannot seek to read persistent data on %s", fname);
905 goto err2;
906 }
907 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
908 SLOGE("Error reading persistent data on iteration %d", i);
909 goto err2;
910 }
911 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
912 found = 1;
913 break;
914 }
915 }
916
917 if (!found) {
918 SLOGI("Could not find valid persistent data, creating");
919 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
920 }
921
922 /* Success */
923 persist_data = pdata;
924 close(fd);
925 return 0;
926
927err2:
928 free(pdata);
929
930err:
931 close(fd);
932 return -1;
933}
934
935static int save_persistent_data(void)
936{
937 struct crypt_mnt_ftr crypt_ftr;
938 struct crypt_persist_data *pdata;
939 char *fname;
940 off64_t write_offset;
941 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700942 int fd;
943 int ret;
944
945 if (persist_data == NULL) {
946 SLOGE("No persistent data to save");
947 return -1;
948 }
949
950 if(get_crypt_ftr_and_key(&crypt_ftr)) {
951 return -1;
952 }
953
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700954 if ((crypt_ftr.major_version < 1)
955 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700956 SLOGE("Crypt_ftr version doesn't support persistent data");
957 return -1;
958 }
959
960 ret = validate_persistent_data_storage(&crypt_ftr);
961 if (ret) {
962 return -1;
963 }
964
965 if (get_crypt_ftr_info(&fname, NULL)) {
966 return -1;
967 }
968
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700969 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700970 if (fd < 0) {
971 SLOGE("Cannot open %s metadata file", fname);
972 return -1;
973 }
974
975 pdata = malloc(crypt_ftr.persist_data_size);
976 if (pdata == NULL) {
977 SLOGE("Cannot allocate persistant data");
978 goto err;
979 }
980
981 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
982 SLOGE("Cannot seek to read persistent data on %s", fname);
983 goto err2;
984 }
985
986 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
987 SLOGE("Error reading persistent data before save");
988 goto err2;
989 }
990
991 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
992 /* The first copy is the curent valid copy, so write to
993 * the second copy and erase this one */
994 write_offset = crypt_ftr.persist_data_offset[1];
995 erase_offset = crypt_ftr.persist_data_offset[0];
996 } else {
997 /* The second copy must be the valid copy, so write to
998 * the first copy, and erase the second */
999 write_offset = crypt_ftr.persist_data_offset[0];
1000 erase_offset = crypt_ftr.persist_data_offset[1];
1001 }
1002
1003 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001004 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001005 SLOGE("Cannot seek to write persistent data");
1006 goto err2;
1007 }
1008 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1009 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001010 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001011 SLOGE("Cannot seek to erase previous persistent data");
1012 goto err2;
1013 }
1014 fsync(fd);
1015 memset(pdata, 0, crypt_ftr.persist_data_size);
1016 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
1017 (int) crypt_ftr.persist_data_size) {
1018 SLOGE("Cannot write to erase previous persistent data");
1019 goto err2;
1020 }
1021 fsync(fd);
1022 } else {
1023 SLOGE("Cannot write to save persistent data");
1024 goto err2;
1025 }
1026
1027 /* Success */
1028 free(pdata);
1029 close(fd);
1030 return 0;
1031
1032err2:
1033 free(pdata);
1034err:
1035 close(fd);
1036 return -1;
1037}
1038
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001039/* Convert a binary key of specified length into an ascii hex string equivalent,
1040 * without the leading 0x and with null termination
1041 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001042static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001043 unsigned int keysize, char *master_key_ascii) {
1044 unsigned int i, a;
1045 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001046
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001047 for (i=0, a=0; i<keysize; i++, a+=2) {
1048 /* For each byte, write out two ascii hex digits */
1049 nibble = (master_key[i] >> 4) & 0xf;
1050 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001051
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001052 nibble = master_key[i] & 0xf;
1053 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1054 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001055
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001056 /* Add the null termination */
1057 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001058
1059}
1060
Jeff Sharkey9c484982015-03-31 10:35:33 -07001061static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
1062 const unsigned char *master_key, const char *real_blk_name,
1063 const char *name, int fd, const char *extra_params) {
Dan Albertc07fa3f2014-12-18 10:00:55 -08001064 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001065 struct dm_ioctl *io;
1066 struct dm_target_spec *tgt;
1067 char *crypt_params;
1068 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1069 int i;
1070
1071 io = (struct dm_ioctl *) buffer;
1072
1073 /* Load the mapping table for this device */
1074 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1075
1076 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1077 io->target_count = 1;
1078 tgt->status = 0;
1079 tgt->sector_start = 0;
1080 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -07001081#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001082 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1083 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1084 }
1085 else {
1086 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1087 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001088#else
1089 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1090#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001091
1092 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1093 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1094 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1095 master_key_ascii, real_blk_name, extra_params);
1096 crypt_params += strlen(crypt_params) + 1;
1097 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1098 tgt->next = crypt_params - buffer;
1099
1100 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1101 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1102 break;
1103 }
1104 usleep(500000);
1105 }
1106
1107 if (i == TABLE_LOAD_RETRIES) {
1108 /* We failed to load the table, return an error */
1109 return -1;
1110 } else {
1111 return i + 1;
1112 }
1113}
1114
1115
1116static int get_dm_crypt_version(int fd, const char *name, int *version)
1117{
1118 char buffer[DM_CRYPT_BUF_SIZE];
1119 struct dm_ioctl *io;
1120 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001121
1122 io = (struct dm_ioctl *) buffer;
1123
1124 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1125
1126 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1127 return -1;
1128 }
1129
1130 /* Iterate over the returned versions, looking for name of "crypt".
1131 * When found, get and return the version.
1132 */
1133 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1134 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001135#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001136 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001137#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001138 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001139#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001140 /* We found the crypt driver, return the version, and get out */
1141 version[0] = v->version[0];
1142 version[1] = v->version[1];
1143 version[2] = v->version[2];
1144 return 0;
1145 }
1146 v = (struct dm_target_versions *)(((char *)v) + v->next);
1147 }
1148
1149 return -1;
1150}
1151
Jeff Sharkey9c484982015-03-31 10:35:33 -07001152static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
1153 const unsigned char *master_key, const char *real_blk_name,
1154 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001155 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001158 int fd=0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001159 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001160 int version[3];
1161 char *extra_params;
1162 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001163
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001164 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165 SLOGE("Cannot open device-mapper\n");
1166 goto errout;
1167 }
1168
1169 io = (struct dm_ioctl *) buffer;
1170
1171 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1172 if (ioctl(fd, DM_DEV_CREATE, io)) {
1173 SLOGE("Cannot create dm-crypt device\n");
1174 goto errout;
1175 }
1176
1177 /* Get the device status, in particular, the name of it's device file */
1178 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1179 if (ioctl(fd, DM_DEV_STATUS, io)) {
1180 SLOGE("Cannot retrieve dm-crypt device status\n");
1181 goto errout;
1182 }
1183 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1184 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1185
Ken Sumralldb5e0262013-02-05 17:39:48 -08001186 extra_params = "";
1187 if (! get_dm_crypt_version(fd, name, version)) {
1188 /* Support for allow_discards was added in version 1.11.0 */
1189 if ((version[0] >= 2) ||
1190 ((version[0] == 1) && (version[1] >= 11))) {
1191 extra_params = "1 allow_discards";
1192 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1193 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001194 }
1195
Ken Sumralldb5e0262013-02-05 17:39:48 -08001196 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1197 fd, extra_params);
1198 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001199 SLOGE("Cannot load dm-crypt mapping table.\n");
1200 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001201 } else if (load_count > 1) {
1202 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001203 }
1204
1205 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001206 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207
1208 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1209 SLOGE("Cannot resume the dm-crypt device\n");
1210 goto errout;
1211 }
1212
1213 /* We made it here with no errors. Woot! */
1214 retval = 0;
1215
1216errout:
1217 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1218
1219 return retval;
1220}
1221
Ken Sumrall29d8da82011-05-18 17:20:07 -07001222static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223{
1224 int fd;
1225 char buffer[DM_CRYPT_BUF_SIZE];
1226 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001227 int retval = -1;
1228
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001229 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230 SLOGE("Cannot open device-mapper\n");
1231 goto errout;
1232 }
1233
1234 io = (struct dm_ioctl *) buffer;
1235
1236 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1237 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1238 SLOGE("Cannot remove dm-crypt device\n");
1239 goto errout;
1240 }
1241
1242 /* We made it here with no errors. Woot! */
1243 retval = 0;
1244
1245errout:
1246 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1247
1248 return retval;
1249
1250}
1251
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001252static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001253 unsigned char *ikey, void *params UNUSED)
1254{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001255 SLOGI("Using pbkdf2 for cryptfs KDF");
1256
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001257 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001258 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1259 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1260 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001261}
1262
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001263static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001264 unsigned char *ikey, void *params)
1265{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001266 SLOGI("Using scrypt for cryptfs KDF");
1267
Kenny Rootc4c70f12013-06-14 12:11:38 -07001268 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1269
1270 int N = 1 << ftr->N_factor;
1271 int r = 1 << ftr->r_factor;
1272 int p = 1 << ftr->p_factor;
1273
1274 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001275 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001276 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1277 salt, SALT_LEN, N, r, p, ikey,
1278 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001279
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001280 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001281}
1282
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001283static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1284 unsigned char *ikey, void *params)
1285{
1286 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1287
1288 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001289 size_t signature_size;
1290 unsigned char* signature;
1291 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1292
1293 int N = 1 << ftr->N_factor;
1294 int r = 1 << ftr->r_factor;
1295 int p = 1 << ftr->p_factor;
1296
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001297 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1298 salt, SALT_LEN, N, r, p, ikey,
1299 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001300
1301 if (rc) {
1302 SLOGE("scrypt failed");
1303 return -1;
1304 }
1305
Shawn Willdene17a9c42014-09-08 13:04:08 -06001306 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1307 &signature, &signature_size)) {
1308 SLOGE("Signing failed");
1309 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001310 }
1311
1312 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1313 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1314 free(signature);
1315
1316 if (rc) {
1317 SLOGE("scrypt failed");
1318 return -1;
1319 }
1320
1321 return 0;
1322}
1323
1324static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1325 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001326 unsigned char *encrypted_master_key,
1327 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001328{
1329 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1330 EVP_CIPHER_CTX e_ctx;
1331 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001332 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001333
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001334 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001335 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001336
1337 switch (crypt_ftr->kdf_type) {
1338 case KDF_SCRYPT_KEYMASTER:
1339 if (keymaster_create_key(crypt_ftr)) {
1340 SLOGE("keymaster_create_key failed");
1341 return -1;
1342 }
1343
1344 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1345 SLOGE("scrypt failed");
1346 return -1;
1347 }
1348 break;
1349
1350 case KDF_SCRYPT:
1351 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1352 SLOGE("scrypt failed");
1353 return -1;
1354 }
1355 break;
1356
1357 default:
1358 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001359 return -1;
1360 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001361
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001362 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001363 EVP_CIPHER_CTX_init(&e_ctx);
1364 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001365 SLOGE("EVP_EncryptInit failed\n");
1366 return -1;
1367 }
1368 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001369
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001370 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001371 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001372 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373 SLOGE("EVP_EncryptUpdate failed\n");
1374 return -1;
1375 }
Adam Langley889c4f12014-09-03 14:23:13 -07001376 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001377 SLOGE("EVP_EncryptFinal failed\n");
1378 return -1;
1379 }
1380
1381 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1382 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1383 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001384 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001385
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001386 /* Store the scrypt of the intermediate key, so we can validate if it's a
1387 password error or mount error when things go wrong.
1388 Note there's no need to check for errors, since if this is incorrect, we
1389 simply won't wipe userdata, which is the correct default behavior
1390 */
1391 int N = 1 << crypt_ftr->N_factor;
1392 int r = 1 << crypt_ftr->r_factor;
1393 int p = 1 << crypt_ftr->p_factor;
1394
1395 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1396 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1397 crypt_ftr->scrypted_intermediate_key,
1398 sizeof(crypt_ftr->scrypted_intermediate_key));
1399
1400 if (rc) {
1401 SLOGE("encrypt_master_key: crypto_scrypt failed");
1402 }
1403
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001404 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001405}
1406
Paul Lawrence731a7a22015-04-28 22:14:15 +00001407static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001408 unsigned char *encrypted_master_key,
1409 unsigned char *decrypted_master_key,
1410 kdf_func kdf, void *kdf_params,
1411 unsigned char** intermediate_key,
1412 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413{
1414 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001415 EVP_CIPHER_CTX d_ctx;
1416 int decrypted_len, final_len;
1417
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001418 /* Turn the password into an intermediate key and IV that can decrypt the
1419 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001420 if (kdf(passwd, salt, ikey, kdf_params)) {
1421 SLOGE("kdf failed");
1422 return -1;
1423 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001424
1425 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001426 EVP_CIPHER_CTX_init(&d_ctx);
1427 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428 return -1;
1429 }
1430 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1431 /* Decrypt the master key */
1432 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1433 encrypted_master_key, KEY_LEN_BYTES)) {
1434 return -1;
1435 }
Adam Langley889c4f12014-09-03 14:23:13 -07001436 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001437 return -1;
1438 }
1439
1440 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1441 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001442 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001443
1444 /* Copy intermediate key if needed by params */
1445 if (intermediate_key && intermediate_key_size) {
1446 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1447 if (intermediate_key) {
1448 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1449 *intermediate_key_size = KEY_LEN_BYTES;
1450 }
1451 }
1452
1453 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001454}
1455
Kenny Rootc4c70f12013-06-14 12:11:38 -07001456static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001457{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001458 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001459 *kdf = scrypt_keymaster;
1460 *kdf_params = ftr;
1461 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001462 *kdf = scrypt;
1463 *kdf_params = ftr;
1464 } else {
1465 *kdf = pbkdf2;
1466 *kdf_params = NULL;
1467 }
1468}
1469
Paul Lawrence731a7a22015-04-28 22:14:15 +00001470static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001471 struct crypt_mnt_ftr *crypt_ftr,
1472 unsigned char** intermediate_key,
1473 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001474{
1475 kdf_func kdf;
1476 void *kdf_params;
1477 int ret;
1478
1479 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001480 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1481 decrypted_master_key, kdf, kdf_params,
1482 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001483 if (ret != 0) {
1484 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001485 }
1486
1487 return ret;
1488}
1489
1490static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1491 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001492 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001493 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001494
1495 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001496 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001497 read(fd, key_buf, sizeof(key_buf));
1498 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001499 close(fd);
1500
1501 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001502 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001503}
1504
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001505int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001506{
Greg Hackmann955653e2014-09-24 14:55:20 -07001507 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001508#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001509
1510 /* Now umount the tmpfs filesystem */
1511 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001512 if (umount(mountpoint) == 0) {
1513 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001514 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001515
1516 if (errno == EINVAL) {
1517 /* EINVAL is returned if the directory is not a mountpoint,
1518 * i.e. there is no filesystem mounted there. So just get out.
1519 */
1520 break;
1521 }
1522
1523 err = errno;
1524
1525 /* If allowed, be increasingly aggressive before the last two retries */
1526 if (kill) {
1527 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1528 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001529 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001530 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1531 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001532 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001533 }
1534 }
1535
1536 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001537 }
1538
1539 if (i < WAIT_UNMOUNT_COUNT) {
1540 SLOGD("unmounting %s succeeded\n", mountpoint);
1541 rc = 0;
1542 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001543 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001544 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001545 rc = -1;
1546 }
1547
1548 return rc;
1549}
1550
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001551#define DATA_PREP_TIMEOUT 1000
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001552static int prep_data_fs(void)
1553{
1554 int i;
1555
1556 /* Do the prep of the /data filesystem */
1557 property_set("vold.post_fs_data_done", "0");
1558 property_set("vold.decrypt", "trigger_post_fs_data");
1559 SLOGD("Just triggered post_fs_data\n");
1560
Ken Sumrallc5872692013-05-14 15:26:31 -07001561 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001562 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001563 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001564
1565 property_get("vold.post_fs_data_done", p, "0");
1566 if (*p == '1') {
1567 break;
1568 } else {
Paul Lawrenceb1ef4662015-06-11 11:15:29 -07001569 usleep(50000);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001570 }
1571 }
1572 if (i == DATA_PREP_TIMEOUT) {
1573 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001574 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001575 return -1;
1576 } else {
1577 SLOGD("post_fs_data done\n");
1578 return 0;
1579 }
1580}
1581
Paul Lawrence74f29f12014-08-28 15:54:10 -07001582static void cryptfs_set_corrupt()
1583{
1584 // Mark the footer as bad
1585 struct crypt_mnt_ftr crypt_ftr;
1586 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1587 SLOGE("Failed to get crypto footer - panic");
1588 return;
1589 }
1590
1591 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1592 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1593 SLOGE("Failed to set crypto footer - panic");
1594 return;
1595 }
1596}
1597
1598static void cryptfs_trigger_restart_min_framework()
1599{
1600 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1601 SLOGE("Failed to mount tmpfs on data - panic");
1602 return;
1603 }
1604
1605 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1606 SLOGE("Failed to trigger post fs data - panic");
1607 return;
1608 }
1609
1610 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1611 SLOGE("Failed to trigger restart min framework - panic");
1612 return;
1613 }
1614}
1615
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001616/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001617static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001618{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001619 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001620 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001621 static int restart_successful = 0;
1622
1623 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001624 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001625 SLOGE("Encrypted filesystem not validated, aborting");
1626 return -1;
1627 }
1628
1629 if (restart_successful) {
1630 SLOGE("System already restarted with encrypted disk, aborting");
1631 return -1;
1632 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001633
Paul Lawrencef4faa572014-01-29 13:31:03 -08001634 if (restart_main) {
1635 /* Here is where we shut down the framework. The init scripts
1636 * start all services in one of three classes: core, main or late_start.
1637 * On boot, we start core and main. Now, we stop main, but not core,
1638 * as core includes vold and a few other really important things that
1639 * we need to keep running. Once main has stopped, we should be able
1640 * to umount the tmpfs /data, then mount the encrypted /data.
1641 * We then restart the class main, and also the class late_start.
1642 * At the moment, I've only put a few things in late_start that I know
1643 * are not needed to bring up the framework, and that also cause problems
1644 * with unmounting the tmpfs /data, but I hope to add add more services
1645 * to the late_start class as we optimize this to decrease the delay
1646 * till the user is asked for the password to the filesystem.
1647 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001648
Paul Lawrencef4faa572014-01-29 13:31:03 -08001649 /* The init files are setup to stop the class main when vold.decrypt is
1650 * set to trigger_reset_main.
1651 */
1652 property_set("vold.decrypt", "trigger_reset_main");
1653 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001654
Paul Lawrencef4faa572014-01-29 13:31:03 -08001655 /* Ugh, shutting down the framework is not synchronous, so until it
1656 * can be fixed, this horrible hack will wait a moment for it all to
1657 * shut down before proceeding. Without it, some devices cannot
1658 * restart the graphics services.
1659 */
1660 sleep(2);
1661 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001662
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001663 /* Now that the framework is shutdown, we should be able to umount()
1664 * the tmpfs filesystem, and mount the real one.
1665 */
1666
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001667 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1668 if (strlen(crypto_blkdev) == 0) {
1669 SLOGE("fs_crypto_blkdev not set\n");
1670 return -1;
1671 }
1672
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001673 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001674 /* If ro.crypto.readonly is set to 1, mount the decrypted
1675 * filesystem readonly. This is used when /data is mounted by
1676 * recovery mode.
1677 */
1678 char ro_prop[PROPERTY_VALUE_MAX];
1679 property_get("ro.crypto.readonly", ro_prop, "");
1680 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1681 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1682 rec->flags |= MS_RDONLY;
1683 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001684
Ken Sumralle5032c42012-04-01 23:58:44 -07001685 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001686 int retries = RETRY_MOUNT_ATTEMPTS;
1687 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001688
1689 /*
1690 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1691 * partitions in the fsck domain.
1692 */
1693 if (setexeccon(secontextFsck())){
1694 SLOGE("Failed to setexeccon");
1695 return -1;
1696 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001697 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1698 crypto_blkdev, 0))
1699 != 0) {
1700 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1701 /* TODO: invoke something similar to
1702 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1703 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1704 SLOGI("Failed to mount %s because it is busy - waiting",
1705 crypto_blkdev);
1706 if (--retries) {
1707 sleep(RETRY_MOUNT_DELAY_SECONDS);
1708 } else {
1709 /* Let's hope that a reboot clears away whatever is keeping
1710 the mount busy */
1711 cryptfs_reboot(reboot);
1712 }
1713 } else {
1714 SLOGE("Failed to mount decrypted data");
1715 cryptfs_set_corrupt();
1716 cryptfs_trigger_restart_min_framework();
1717 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001718 if (setexeccon(NULL)) {
1719 SLOGE("Failed to setexeccon");
1720 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001721 return -1;
1722 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001723 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001724 if (setexeccon(NULL)) {
1725 SLOGE("Failed to setexeccon");
1726 return -1;
1727 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001728
Ken Sumralle5032c42012-04-01 23:58:44 -07001729 property_set("vold.decrypt", "trigger_load_persist_props");
1730 /* Create necessary paths on /data */
1731 if (prep_data_fs()) {
1732 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001733 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001734
1735 /* startup service classes main and late_start */
1736 property_set("vold.decrypt", "trigger_restart_framework");
1737 SLOGD("Just triggered restart_framework\n");
1738
1739 /* Give it a few moments to get started */
1740 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001741 }
1742
Ken Sumrall0cc16632011-01-18 20:32:26 -08001743 if (rc == 0) {
1744 restart_successful = 1;
1745 }
1746
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001747 return rc;
1748}
1749
Paul Lawrencef4faa572014-01-29 13:31:03 -08001750int cryptfs_restart(void)
1751{
Paul Lawrence05335c32015-03-05 09:46:23 -08001752 SLOGI("cryptfs_restart");
1753 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
1754 struct fstab_rec* rec;
1755 int rc;
1756
1757 if (e4crypt_restart(DATA_MNT_POINT)) {
1758 SLOGE("Can't unmount e4crypt temp volume\n");
1759 return -1;
1760 }
1761
1762 rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1763 if (!rec) {
1764 SLOGE("Can't get fstab record for %s\n", DATA_MNT_POINT);
1765 return -1;
1766 }
1767
1768 rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, rec->blk_device, 0);
1769 if (rc) {
1770 SLOGE("Can't mount %s\n", DATA_MNT_POINT);
1771 return rc;
1772 }
1773
1774 property_set("vold.decrypt", "trigger_restart_framework");
1775 return 0;
1776 }
1777
Paul Lawrencef4faa572014-01-29 13:31:03 -08001778 /* Call internal implementation forcing a restart of main service group */
1779 return cryptfs_restart_internal(1);
1780}
1781
Paul Lawrence05335c32015-03-05 09:46:23 -08001782static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001783{
1784 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001785 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001786 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001787
1788 property_get("ro.crypto.state", encrypted_state, "");
1789 if (strcmp(encrypted_state, "encrypted") ) {
1790 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001791 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001792 }
1793
Paul Lawrence05335c32015-03-05 09:46:23 -08001794 if (e4crypt_crypto_complete(mount_point) == 0) {
1795 return CRYPTO_COMPLETE_ENCRYPTED;
1796 }
1797
Ken Sumrall160b4d62013-04-22 12:15:39 -07001798 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001799 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001800
Ken Sumralle1a45852011-12-14 21:24:27 -08001801 /*
1802 * Only report this error if key_loc is a file and it exists.
1803 * If the device was never encrypted, and /data is not mountable for
1804 * some reason, returning 1 should prevent the UI from presenting the
1805 * a "enter password" screen, or worse, a "press button to wipe the
1806 * device" screen.
1807 */
1808 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1809 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001810 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001811 } else {
1812 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001813 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001814 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001815 }
1816
Paul Lawrence74f29f12014-08-28 15:54:10 -07001817 // Test for possible error flags
1818 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1819 SLOGE("Encryption process is partway completed\n");
1820 return CRYPTO_COMPLETE_PARTIAL;
1821 }
1822
1823 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1824 SLOGE("Encryption process was interrupted but cannot continue\n");
1825 return CRYPTO_COMPLETE_INCONSISTENT;
1826 }
1827
1828 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1829 SLOGE("Encryption is successful but data is corrupt\n");
1830 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001831 }
1832
1833 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001834 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001835}
1836
Paul Lawrencef4faa572014-01-29 13:31:03 -08001837static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1838 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001839{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001840 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001841 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001842 char crypto_blkdev[MAXPATHLEN];
1843 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001844 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001845 unsigned int orig_failed_decrypt_count;
1846 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001847 int use_keymaster = 0;
1848 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001849 unsigned char* intermediate_key = 0;
1850 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001851
Paul Lawrencef4faa572014-01-29 13:31:03 -08001852 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1853 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001854
Paul Lawrencef4faa572014-01-29 13:31:03 -08001855 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001856 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1857 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001858 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001859 rc = -1;
1860 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001861 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001862 }
1863
Paul Lawrencef4faa572014-01-29 13:31:03 -08001864 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1865
Ajay Dudani87701e22014-09-17 21:02:52 -07001866#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001867 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1868 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1869 SLOGE("Hardware encryption key does not match");
1870 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001871 }
1872#endif
1873
Paul Lawrence74f29f12014-08-28 15:54:10 -07001874 // Create crypto block device - all (non fatal) code paths
1875 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001876 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1877 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001878 SLOGE("Error creating decrypted block device\n");
1879 rc = -1;
1880 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001881 }
1882
Paul Lawrence74f29f12014-08-28 15:54:10 -07001883 /* Work out if the problem is the password or the data */
1884 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1885 scrypted_intermediate_key)];
1886 int N = 1 << crypt_ftr->N_factor;
1887 int r = 1 << crypt_ftr->r_factor;
1888 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001889
Paul Lawrence74f29f12014-08-28 15:54:10 -07001890 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1891 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1892 N, r, p, scrypted_intermediate_key,
1893 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001894
Paul Lawrence74f29f12014-08-28 15:54:10 -07001895 // Does the key match the crypto footer?
1896 if (rc == 0 && memcmp(scrypted_intermediate_key,
1897 crypt_ftr->scrypted_intermediate_key,
1898 sizeof(scrypted_intermediate_key)) == 0) {
1899 SLOGI("Password matches");
1900 rc = 0;
1901 } else {
1902 /* Try mounting the file system anyway, just in case the problem's with
1903 * the footer, not the key. */
1904 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1905 mkdir(tmp_mount_point, 0755);
1906 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1907 SLOGE("Error temp mounting decrypted block device\n");
1908 delete_crypto_blk_dev(label);
1909
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001910 rc = ++crypt_ftr->failed_decrypt_count;
1911 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001912 } else {
1913 /* Success! */
1914 SLOGI("Password did not match but decrypted drive mounted - continue");
1915 umount(tmp_mount_point);
1916 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001917 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001918 }
1919
1920 if (rc == 0) {
1921 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001922 if (orig_failed_decrypt_count != 0) {
1923 put_crypt_ftr_and_key(crypt_ftr);
1924 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001925
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001926 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001927 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001928 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001929
1930 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001931 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001932 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001933 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001934 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001935 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001936 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001937
Paul Lawrence74f29f12014-08-28 15:54:10 -07001938 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001939 use_keymaster = keymaster_check_compatibility();
1940 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001941 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001942 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1943 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1944 upgrade = 1;
1945 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001946 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001947 upgrade = 1;
1948 }
1949
1950 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001951 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1952 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001953 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001954 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001955 }
1956 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001957
1958 // Do not fail even if upgrade failed - machine is bootable
1959 // Note that if this code is ever hit, there is a *serious* problem
1960 // since KDFs should never fail. You *must* fix the kdf before
1961 // proceeding!
1962 if (rc) {
1963 SLOGW("Upgrade failed with error %d,"
1964 " but continuing with previous state",
1965 rc);
1966 rc = 0;
1967 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001968 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001969 }
1970
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001971 errout:
1972 if (intermediate_key) {
1973 memset(intermediate_key, 0, intermediate_key_size);
1974 free(intermediate_key);
1975 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001976 return rc;
1977}
1978
Ken Sumrall29d8da82011-05-18 17:20:07 -07001979/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001980 * Called by vold when it's asked to mount an encrypted external
1981 * storage volume. The incoming partition has no crypto header/footer,
1982 * as any metadata is been stored in a separate, small partition.
1983 *
1984 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001985 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001986int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1987 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001988 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001989 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001990 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001991 return -1;
1992 }
1993
1994 unsigned long nr_sec = 0;
1995 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001996 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001997
Ken Sumrall29d8da82011-05-18 17:20:07 -07001998 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001999 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002000 return -1;
2001 }
2002
Jeff Sharkey9c484982015-03-31 10:35:33 -07002003 struct crypt_mnt_ftr ext_crypt_ftr;
2004 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2005 ext_crypt_ftr.fs_size = nr_sec;
2006 ext_crypt_ftr.keysize = keysize;
2007 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002008
Jeff Sharkey9c484982015-03-31 10:35:33 -07002009 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
2010 out_crypto_blkdev, label);
2011}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002012
Jeff Sharkey9c484982015-03-31 10:35:33 -07002013/*
2014 * Called by vold when it's asked to unmount an encrypted external
2015 * storage volume.
2016 */
2017int cryptfs_revert_ext_volume(const char* label) {
2018 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002019}
2020
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002021int cryptfs_crypto_complete(void)
2022{
2023 return do_crypto_complete("/data");
2024}
2025
Paul Lawrencef4faa572014-01-29 13:31:03 -08002026int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2027{
2028 char encrypted_state[PROPERTY_VALUE_MAX];
2029 property_get("ro.crypto.state", encrypted_state, "");
2030 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2031 SLOGE("encrypted fs already validated or not running with encryption,"
2032 " aborting");
2033 return -1;
2034 }
2035
2036 if (get_crypt_ftr_and_key(crypt_ftr)) {
2037 SLOGE("Error getting crypt footer and key");
2038 return -1;
2039 }
2040
2041 return 0;
2042}
2043
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002044int cryptfs_check_passwd(char *passwd)
2045{
Paul Lawrence05335c32015-03-05 09:46:23 -08002046 SLOGI("cryptfs_check_passwd");
2047 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
2048 return e4crypt_check_passwd(DATA_MNT_POINT, passwd);
2049 }
2050
Paul Lawrencef4faa572014-01-29 13:31:03 -08002051 struct crypt_mnt_ftr crypt_ftr;
2052 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002053
Paul Lawrencef4faa572014-01-29 13:31:03 -08002054 rc = check_unmounted_and_get_ftr(&crypt_ftr);
2055 if (rc)
2056 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002057
Paul Lawrence3bd36d52015-06-09 13:37:44 -07002058 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2059 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002060
2061 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002062 cryptfs_clear_password();
2063 password = strdup(passwd);
2064 struct timespec now;
2065 clock_gettime(CLOCK_BOOTTIME, &now);
2066 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002067 }
2068
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002069 return rc;
2070}
2071
Ken Sumrall3ad90722011-10-04 20:38:29 -07002072int cryptfs_verify_passwd(char *passwd)
2073{
2074 struct crypt_mnt_ftr crypt_ftr;
2075 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002076 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002077 char encrypted_state[PROPERTY_VALUE_MAX];
2078 int rc;
2079
2080 property_get("ro.crypto.state", encrypted_state, "");
2081 if (strcmp(encrypted_state, "encrypted") ) {
2082 SLOGE("device not encrypted, aborting");
2083 return -2;
2084 }
2085
2086 if (!master_key_saved) {
2087 SLOGE("encrypted fs not yet mounted, aborting");
2088 return -1;
2089 }
2090
2091 if (!saved_mount_point) {
2092 SLOGE("encrypted fs failed to save mount point, aborting");
2093 return -1;
2094 }
2095
Ken Sumrall160b4d62013-04-22 12:15:39 -07002096 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002097 SLOGE("Error getting crypt footer and key\n");
2098 return -1;
2099 }
2100
2101 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2102 /* If the device has no password, then just say the password is valid */
2103 rc = 0;
2104 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002105 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002106 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2107 /* They match, the password is correct */
2108 rc = 0;
2109 } else {
2110 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2111 sleep(1);
2112 rc = 1;
2113 }
2114 }
2115
2116 return rc;
2117}
2118
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002119/* Initialize a crypt_mnt_ftr structure. The keysize is
2120 * defaulted to 16 bytes, and the filesystem size to 0.
2121 * Presumably, at a minimum, the caller will update the
2122 * filesystem size and crypto_type_name after calling this function.
2123 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002124static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002125{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002126 off64_t off;
2127
2128 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002129 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002130 ftr->major_version = CURRENT_MAJOR_VERSION;
2131 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002132 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002133 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002134
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002135 switch (keymaster_check_compatibility()) {
2136 case 1:
2137 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2138 break;
2139
2140 case 0:
2141 ftr->kdf_type = KDF_SCRYPT;
2142 break;
2143
2144 default:
2145 SLOGE("keymaster_check_compatibility failed");
2146 return -1;
2147 }
2148
Kenny Rootc4c70f12013-06-14 12:11:38 -07002149 get_device_scrypt_params(ftr);
2150
Ken Sumrall160b4d62013-04-22 12:15:39 -07002151 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2152 if (get_crypt_ftr_info(NULL, &off) == 0) {
2153 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2154 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2155 ftr->persist_data_size;
2156 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002157
2158 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002159}
2160
Ken Sumrall29d8da82011-05-18 17:20:07 -07002161static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002162{
Ken Sumralle550f782013-08-20 13:48:23 -07002163 const char *args[10];
2164 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2165 int num_args;
2166 int status;
2167 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002168 int rc = -1;
2169
Ken Sumrall29d8da82011-05-18 17:20:07 -07002170 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002171 args[0] = "/system/bin/make_ext4fs";
2172 args[1] = "-a";
2173 args[2] = "/data";
2174 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002175 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002176 args[4] = size_str;
2177 args[5] = crypto_blkdev;
2178 num_args = 6;
2179 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2180 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002181 } else if (type == F2FS_FS) {
2182 args[0] = "/system/bin/mkfs.f2fs";
2183 args[1] = "-t";
2184 args[2] = "-d1";
2185 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002186 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002187 args[4] = size_str;
2188 num_args = 5;
2189 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2190 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002191 } else {
2192 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2193 return -1;
2194 }
2195
Ken Sumralle550f782013-08-20 13:48:23 -07002196 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2197
2198 if (tmp != 0) {
2199 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002200 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002201 if (WIFEXITED(status)) {
2202 if (WEXITSTATUS(status)) {
2203 SLOGE("Error creating filesystem on %s, exit status %d ",
2204 crypto_blkdev, WEXITSTATUS(status));
2205 } else {
2206 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2207 rc = 0;
2208 }
2209 } else {
2210 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2211 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002212 }
2213
2214 return rc;
2215}
2216
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002217#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002218#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2219#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002220
2221/* aligned 32K writes tends to make flash happy.
2222 * SD card association recommends it.
2223 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002224#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002225#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002226#else
2227#define BLOCKS_AT_A_TIME 1024
2228#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002229
2230struct encryptGroupsData
2231{
2232 int realfd;
2233 int cryptofd;
2234 off64_t numblocks;
2235 off64_t one_pct, cur_pct, new_pct;
2236 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002237 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002238 char* real_blkdev, * crypto_blkdev;
2239 int count;
2240 off64_t offset;
2241 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002242 off64_t last_written_sector;
2243 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002244 time_t time_started;
2245 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002246};
2247
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002248static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002249{
2250 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002251
2252 if (is_used) {
2253 data->used_blocks_already_done++;
2254 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002255 if (data->tot_used_blocks) {
2256 data->new_pct = data->used_blocks_already_done / data->one_pct;
2257 } else {
2258 data->new_pct = data->blocks_already_done / data->one_pct;
2259 }
2260
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002261 if (data->new_pct > data->cur_pct) {
2262 char buf[8];
2263 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002264 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002265 property_set("vold.encrypt_progress", buf);
2266 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002267
2268 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002269 struct timespec time_now;
2270 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2271 SLOGW("Error getting time");
2272 } else {
2273 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2274 off64_t remaining_blocks = data->tot_used_blocks
2275 - data->used_blocks_already_done;
2276 int remaining_time = (int)(elapsed_time * remaining_blocks
2277 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002278
Paul Lawrence9c58a872014-09-30 09:12:51 -07002279 // Change time only if not yet set, lower, or a lot higher for
2280 // best user experience
2281 if (data->remaining_time == -1
2282 || remaining_time < data->remaining_time
2283 || remaining_time > data->remaining_time + 60) {
2284 char buf[8];
2285 snprintf(buf, sizeof(buf), "%d", remaining_time);
2286 property_set("vold.encrypt_time_remaining", buf);
2287 data->remaining_time = remaining_time;
2288 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002289 }
2290 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002291}
2292
Paul Lawrence3846be12014-09-22 11:33:54 -07002293static void log_progress(struct encryptGroupsData const* data, bool completed)
2294{
2295 // Precondition - if completed data = 0 else data != 0
2296
2297 // Track progress so we can skip logging blocks
2298 static off64_t offset = -1;
2299
2300 // Need to close existing 'Encrypting from' log?
2301 if (completed || (offset != -1 && data->offset != offset)) {
2302 SLOGI("Encrypted to sector %" PRId64,
2303 offset / info.block_size * CRYPT_SECTOR_SIZE);
2304 offset = -1;
2305 }
2306
2307 // Need to start new 'Encrypting from' log?
2308 if (!completed && offset != data->offset) {
2309 SLOGI("Encrypting from sector %" PRId64,
2310 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2311 }
2312
2313 // Update offset
2314 if (!completed) {
2315 offset = data->offset + (off64_t)data->count * info.block_size;
2316 }
2317}
2318
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002319static int flush_outstanding_data(struct encryptGroupsData* data)
2320{
2321 if (data->count == 0) {
2322 return 0;
2323 }
2324
Elliott Hughes231bdba2014-06-25 18:36:19 -07002325 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002326
2327 if (pread64(data->realfd, data->buffer,
2328 info.block_size * data->count, data->offset)
2329 <= 0) {
2330 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2331 data->real_blkdev);
2332 return -1;
2333 }
2334
2335 if (pwrite64(data->cryptofd, data->buffer,
2336 info.block_size * data->count, data->offset)
2337 <= 0) {
2338 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2339 data->crypto_blkdev);
2340 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002341 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002342 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002343 }
2344
2345 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002346 data->last_written_sector = (data->offset + data->count)
2347 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002348 return 0;
2349}
2350
2351static int encrypt_groups(struct encryptGroupsData* data)
2352{
2353 unsigned int i;
2354 u8 *block_bitmap = 0;
2355 unsigned int block;
2356 off64_t ret;
2357 int rc = -1;
2358
2359 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2360 if (!data->buffer) {
2361 SLOGE("Failed to allocate crypto buffer");
2362 goto errout;
2363 }
2364
2365 block_bitmap = malloc(info.block_size);
2366 if (!block_bitmap) {
2367 SLOGE("failed to allocate block bitmap");
2368 goto errout;
2369 }
2370
2371 for (i = 0; i < aux_info.groups; ++i) {
2372 SLOGI("Encrypting group %d", i);
2373
2374 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2375 u32 block_count = min(info.blocks_per_group,
2376 aux_info.len_blocks - first_block);
2377
2378 off64_t offset = (u64)info.block_size
2379 * aux_info.bg_desc[i].bg_block_bitmap;
2380
2381 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2382 if (ret != (int)info.block_size) {
2383 SLOGE("failed to read all of block group bitmap %d", i);
2384 goto errout;
2385 }
2386
2387 offset = (u64)info.block_size * first_block;
2388
2389 data->count = 0;
2390
2391 for (block = 0; block < block_count; block++) {
liminghaoaa08e582016-01-06 10:30:49 +08002392 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
2393 0 : bitmap_get_bit(block_bitmap, block);
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002394 update_progress(data, used);
2395 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002396 if (data->count == 0) {
2397 data->offset = offset;
2398 }
2399 data->count++;
2400 } else {
2401 if (flush_outstanding_data(data)) {
2402 goto errout;
2403 }
2404 }
2405
2406 offset += info.block_size;
2407
2408 /* Write data if we are aligned or buffer size reached */
2409 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2410 || data->count == BLOCKS_AT_A_TIME) {
2411 if (flush_outstanding_data(data)) {
2412 goto errout;
2413 }
2414 }
Paul Lawrence87999172014-02-20 12:21:31 -08002415
Paul Lawrence73d7a022014-06-09 14:10:09 -07002416 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002417 SLOGE("Stopping encryption due to low battery");
2418 rc = 0;
2419 goto errout;
2420 }
2421
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002422 }
2423 if (flush_outstanding_data(data)) {
2424 goto errout;
2425 }
2426 }
2427
Paul Lawrence87999172014-02-20 12:21:31 -08002428 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002429 rc = 0;
2430
2431errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002432 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002433 free(data->buffer);
2434 free(block_bitmap);
2435 return rc;
2436}
2437
2438static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2439 char *real_blkdev,
2440 off64_t size,
2441 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002442 off64_t tot_size,
2443 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002444{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002445 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002446 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002447 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002448
Paul Lawrence87999172014-02-20 12:21:31 -08002449 if (previously_encrypted_upto > *size_already_done) {
2450 SLOGD("Not fast encrypting since resuming part way through");
2451 return -1;
2452 }
2453
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002454 memset(&data, 0, sizeof(data));
2455 data.real_blkdev = real_blkdev;
2456 data.crypto_blkdev = crypto_blkdev;
2457
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002458 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002459 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2460 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002461 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002462 goto errout;
2463 }
2464
David Ng82fd8042015-01-21 13:55:21 -08002465 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2466 int retries = RETRY_MOUNT_ATTEMPTS;
2467 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2468 if (--retries) {
2469 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2470 crypto_blkdev, errno, strerror(errno));
2471 sleep(RETRY_MOUNT_DELAY_SECONDS);
2472 } else {
2473 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2474 crypto_blkdev, errno, strerror(errno));
2475 rc = ENABLE_INPLACE_ERR_DEV;
2476 goto errout;
2477 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002478 }
2479
2480 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002481 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002482 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002483 goto errout;
2484 }
2485
2486 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002487 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002488 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002489 goto errout;
2490 }
2491
2492 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2493 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2494 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2495
JP Abgrall7fc1de82014-10-10 18:43:41 -07002496 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002497
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002498 data.tot_used_blocks = data.numblocks;
2499 for (i = 0; i < aux_info.groups; ++i) {
2500 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2501 }
2502
2503 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002504 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002505
2506 struct timespec time_started = {0};
2507 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2508 SLOGW("Error getting time at start");
2509 // Note - continue anyway - we'll run with 0
2510 }
2511 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002512 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002513
2514 rc = encrypt_groups(&data);
2515 if (rc) {
2516 SLOGE("Error encrypting groups");
2517 goto errout;
2518 }
2519
Paul Lawrence87999172014-02-20 12:21:31 -08002520 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002521 rc = 0;
2522
2523errout:
2524 close(data.realfd);
2525 close(data.cryptofd);
2526
2527 return rc;
2528}
2529
Paul Lawrence3846be12014-09-22 11:33:54 -07002530static void log_progress_f2fs(u64 block, bool completed)
2531{
2532 // Precondition - if completed data = 0 else data != 0
2533
2534 // Track progress so we can skip logging blocks
2535 static u64 last_block = (u64)-1;
2536
2537 // Need to close existing 'Encrypting from' log?
2538 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2539 SLOGI("Encrypted to block %" PRId64, last_block);
2540 last_block = -1;
2541 }
2542
2543 // Need to start new 'Encrypting from' log?
2544 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2545 SLOGI("Encrypting from block %" PRId64, block);
2546 }
2547
2548 // Update offset
2549 if (!completed) {
2550 last_block = block;
2551 }
2552}
2553
Daniel Rosenberge82df162014-08-15 22:19:23 +00002554static int encrypt_one_block_f2fs(u64 pos, void *data)
2555{
2556 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2557
2558 priv_dat->blocks_already_done = pos - 1;
2559 update_progress(priv_dat, 1);
2560
2561 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2562
2563 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002564 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002565 return -1;
2566 }
2567
2568 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002569 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002570 return -1;
2571 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002572 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002573 }
2574
2575 return 0;
2576}
2577
2578static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2579 char *real_blkdev,
2580 off64_t size,
2581 off64_t *size_already_done,
2582 off64_t tot_size,
2583 off64_t previously_encrypted_upto)
2584{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002585 struct encryptGroupsData data;
2586 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002587 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002588 if (previously_encrypted_upto > *size_already_done) {
2589 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002590 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002591 }
2592 memset(&data, 0, sizeof(data));
2593 data.real_blkdev = real_blkdev;
2594 data.crypto_blkdev = crypto_blkdev;
2595 data.realfd = -1;
2596 data.cryptofd = -1;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002597 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002598 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002599 real_blkdev);
2600 goto errout;
2601 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002602 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002603 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002604 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002605 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002606 goto errout;
2607 }
2608
2609 f2fs_info = generate_f2fs_info(data.realfd);
2610 if (!f2fs_info)
2611 goto errout;
2612
2613 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2614 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2615 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2616
2617 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2618
2619 data.one_pct = data.tot_used_blocks / 100;
2620 data.cur_pct = 0;
2621 data.time_started = time(NULL);
2622 data.remaining_time = -1;
2623
2624 data.buffer = malloc(f2fs_info->block_size);
2625 if (!data.buffer) {
2626 SLOGE("Failed to allocate crypto buffer");
2627 goto errout;
2628 }
2629
2630 data.count = 0;
2631
2632 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2633 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2634
2635 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002636 SLOGE("Error in running over f2fs blocks");
2637 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002638 goto errout;
2639 }
2640
2641 *size_already_done += size;
2642 rc = 0;
2643
2644errout:
2645 if (rc)
2646 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2647
Paul Lawrence3846be12014-09-22 11:33:54 -07002648 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002649 free(f2fs_info);
2650 free(data.buffer);
2651 close(data.realfd);
2652 close(data.cryptofd);
2653
2654 return rc;
2655}
2656
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002657static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2658 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002659 off64_t tot_size,
2660 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002661{
2662 int realfd, cryptofd;
2663 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002664 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002665 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002666 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002667 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002668
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002669 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002670 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002671 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002672 }
2673
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002674 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002675 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2676 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002677 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002678 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002679 }
2680
2681 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2682 * The size passed in is the number of 512 byte sectors in the filesystem.
2683 * So compute the number of whole 4K blocks we should read/write,
2684 * and the remainder.
2685 */
2686 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2687 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002688 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2689 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002690
2691 SLOGE("Encrypting filesystem in place...");
2692
Paul Lawrence87999172014-02-20 12:21:31 -08002693 i = previously_encrypted_upto + 1 - *size_already_done;
2694
2695 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2696 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2697 goto errout;
2698 }
2699
2700 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2701 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2702 goto errout;
2703 }
2704
2705 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2706 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2707 SLOGE("Error reading initial sectors from real_blkdev %s for "
2708 "inplace encrypt\n", crypto_blkdev);
2709 goto errout;
2710 }
2711 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2712 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2713 "inplace encrypt\n", crypto_blkdev);
2714 goto errout;
2715 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002716 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002717 }
2718 }
2719
Ken Sumrall29d8da82011-05-18 17:20:07 -07002720 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002721 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002722 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002723 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002724 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002725 if (new_pct > cur_pct) {
2726 char buf[8];
2727
2728 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002729 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002730 property_set("vold.encrypt_progress", buf);
2731 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002732 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002733 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002734 goto errout;
2735 }
2736 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002737 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2738 goto errout;
2739 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002740 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002741 CRYPT_SECTORS_PER_BUFSIZE,
2742 i * CRYPT_SECTORS_PER_BUFSIZE);
2743 }
2744
Paul Lawrence73d7a022014-06-09 14:10:09 -07002745 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002746 SLOGE("Stopping encryption due to low battery");
2747 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2748 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002749 goto errout;
2750 }
2751 }
2752
2753 /* Do any remaining sectors */
2754 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002755 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2756 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002757 goto errout;
2758 }
Paul Lawrence87999172014-02-20 12:21:31 -08002759 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2760 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002761 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002762 } else {
2763 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002764 }
2765 }
2766
Ken Sumrall29d8da82011-05-18 17:20:07 -07002767 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002768 rc = 0;
2769
2770errout:
2771 close(realfd);
2772 close(cryptofd);
2773
2774 return rc;
2775}
2776
JP Abgrall7fc1de82014-10-10 18:43:41 -07002777/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002778static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2779 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002780 off64_t tot_size,
2781 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002782{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002783 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002784 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002785 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002786 }
2787
2788 if (*size_already_done + size < previously_encrypted_upto) {
2789 *size_already_done += size;
2790 return 0;
2791 }
2792
Daniel Rosenberge82df162014-08-15 22:19:23 +00002793 /* TODO: identify filesystem type.
2794 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2795 * then we will drop down to cryptfs_enable_inplace_f2fs.
2796 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002797 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002798 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002799 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002800 return 0;
2801 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002802 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002803
JP Abgrall7fc1de82014-10-10 18:43:41 -07002804 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002805 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002806 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002807 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002808 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002809 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002810
JP Abgrall7fc1de82014-10-10 18:43:41 -07002811 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002812 size, size_already_done, tot_size,
2813 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002814 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2815
2816 /* Hack for b/17898962, the following is the symptom... */
2817 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2818 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2819 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2820 return ENABLE_INPLACE_ERR_DEV;
2821 }
2822 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002823}
2824
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002825#define CRYPTO_ENABLE_WIPE 1
2826#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002827
2828#define FRAMEWORK_BOOT_WAIT 60
2829
Paul Lawrence87999172014-02-20 12:21:31 -08002830static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2831{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002832 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002833 if (fd == -1) {
2834 SLOGE("Error opening file %s", filename);
2835 return -1;
2836 }
2837
2838 char block[CRYPT_INPLACE_BUFSIZE];
2839 memset(block, 0, sizeof(block));
2840 if (unix_read(fd, block, sizeof(block)) < 0) {
2841 SLOGE("Error reading file %s", filename);
2842 close(fd);
2843 return -1;
2844 }
2845
2846 close(fd);
2847
2848 SHA256_CTX c;
2849 SHA256_Init(&c);
2850 SHA256_Update(&c, block, sizeof(block));
2851 SHA256_Final(buf, &c);
2852
2853 return 0;
2854}
2855
JP Abgrall62c7af32014-06-16 13:01:23 -07002856static int get_fs_type(struct fstab_rec *rec)
2857{
2858 if (!strcmp(rec->fs_type, "ext4")) {
2859 return EXT4_FS;
2860 } else if (!strcmp(rec->fs_type, "f2fs")) {
2861 return F2FS_FS;
2862 } else {
2863 return -1;
2864 }
2865}
2866
Paul Lawrence87999172014-02-20 12:21:31 -08002867static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2868 char *crypto_blkdev, char *real_blkdev,
2869 int previously_encrypted_upto)
2870{
2871 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002872 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002873
Paul Lawrence73d7a022014-06-09 14:10:09 -07002874 if (!is_battery_ok_to_start()) {
2875 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002876 return 0;
2877 }
2878
2879 /* The size of the userdata partition, and add in the vold volumes below */
2880 tot_encryption_size = crypt_ftr->fs_size;
2881
2882 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002883 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2884 int fs_type = get_fs_type(rec);
2885 if (fs_type < 0) {
2886 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2887 return -1;
2888 }
2889 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002890 } else if (how == CRYPTO_ENABLE_INPLACE) {
2891 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2892 crypt_ftr->fs_size, &cur_encryption_done,
2893 tot_encryption_size,
2894 previously_encrypted_upto);
2895
JP Abgrall7fc1de82014-10-10 18:43:41 -07002896 if (rc == ENABLE_INPLACE_ERR_DEV) {
2897 /* Hack for b/17898962 */
2898 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2899 cryptfs_reboot(reboot);
2900 }
2901
Paul Lawrence73d7a022014-06-09 14:10:09 -07002902 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002903 crypt_ftr->encrypted_upto = cur_encryption_done;
2904 }
2905
Paul Lawrence73d7a022014-06-09 14:10:09 -07002906 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002907 /* The inplace routine never actually sets the progress to 100% due
2908 * to the round down nature of integer division, so set it here */
2909 property_set("vold.encrypt_progress", "100");
2910 }
2911 } else {
2912 /* Shouldn't happen */
2913 SLOGE("cryptfs_enable: internal error, unknown option\n");
2914 rc = -1;
2915 }
2916
2917 return rc;
2918}
2919
Paul Lawrence13486032014-02-03 13:28:11 -08002920int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
Paul Lawrence569649f2015-09-09 12:13:00 -07002921 int no_ui)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002922{
2923 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002924 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002925 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002926 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002927 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002928 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002929 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002930 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002931 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002932 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002933 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002934
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002935 if (!strcmp(howarg, "wipe")) {
2936 how = CRYPTO_ENABLE_WIPE;
2937 } else if (! strcmp(howarg, "inplace")) {
2938 how = CRYPTO_ENABLE_INPLACE;
2939 } else {
2940 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002941 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002942 }
2943
Paul Lawrence87999172014-02-20 12:21:31 -08002944 /* See if an encryption was underway and interrupted */
2945 if (how == CRYPTO_ENABLE_INPLACE
2946 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2947 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2948 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2949 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002950 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2951
2952 /* At this point, we are in an inconsistent state. Until we successfully
2953 complete encryption, a reboot will leave us broken. So mark the
2954 encryption failed in case that happens.
2955 On successfully completing encryption, remove this flag */
2956 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2957
2958 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002959 }
2960
2961 property_get("ro.crypto.state", encrypted_state, "");
2962 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2963 SLOGE("Device is already running encrypted, aborting");
2964 goto error_unencrypted;
2965 }
2966
2967 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2968 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002969 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002970
Ken Sumrall3ed82362011-01-28 23:31:16 -08002971 /* Get the size of the real block device */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002972 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002973 if (fd == -1) {
2974 SLOGE("Cannot open block device %s\n", real_blkdev);
2975 goto error_unencrypted;
2976 }
2977 unsigned long nr_sec;
2978 get_blkdev_size(fd, &nr_sec);
2979 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002980 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2981 goto error_unencrypted;
2982 }
2983 close(fd);
2984
2985 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002986 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002987 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002988 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002989 if (fs_size_sec == 0)
2990 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2991
Paul Lawrence87999172014-02-20 12:21:31 -08002992 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002993
2994 if (fs_size_sec > max_fs_size_sec) {
2995 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2996 goto error_unencrypted;
2997 }
2998 }
2999
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003000 /* Get a wakelock as this may take a while, and we don't want the
3001 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3002 * wants to keep the screen on, it can grab a full wakelock.
3003 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003004 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003005 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3006
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003007 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003008 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003009 */
3010 property_set("vold.decrypt", "trigger_shutdown_framework");
3011 SLOGD("Just asked init to shut down class main\n");
3012
Jeff Sharkey9c484982015-03-31 10:35:33 -07003013 /* Ask vold to unmount all devices that it manages */
3014 if (vold_unmountAll()) {
3015 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003016 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003017
3018 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003019 if (wait_and_unmount(DATA_MNT_POINT, false)) {
Paul Lawrence569649f2015-09-09 12:13:00 -07003020 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003021 }
3022
3023 /* Do extra work for a better UX when doing the long inplace encryption */
3024 if (how == CRYPTO_ENABLE_INPLACE) {
3025 /* Now that /data is unmounted, we need to mount a tmpfs
3026 * /data, set a property saying we're doing inplace encryption,
3027 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003028 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003029 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003030 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003031 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003032 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003033 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003034
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003035 /* restart the framework. */
3036 /* Create necessary paths on /data */
3037 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003038 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003039 }
3040
Ken Sumrall92736ef2012-10-17 20:57:14 -07003041 /* Ugh, shutting down the framework is not synchronous, so until it
3042 * can be fixed, this horrible hack will wait a moment for it all to
3043 * shut down before proceeding. Without it, some devices cannot
3044 * restart the graphics services.
3045 */
3046 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003047 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003048
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003049 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003050 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003051 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003052 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3053 goto error_shutting_down;
3054 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003055
Paul Lawrence87999172014-02-20 12:21:31 -08003056 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3057 crypt_ftr.fs_size = nr_sec
3058 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3059 } else {
3060 crypt_ftr.fs_size = nr_sec;
3061 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003062 /* At this point, we are in an inconsistent state. Until we successfully
3063 complete encryption, a reboot will leave us broken. So mark the
3064 encryption failed in case that happens.
3065 On successfully completing encryption, remove this flag */
3066 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003067 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003068#ifndef CONFIG_HW_DISK_ENCRYPTION
3069 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3070#else
3071 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3072
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003073 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003074 if (!rc) {
3075 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3076 }
3077
3078 rc = set_hw_device_encryption_key(passwd,
3079 (char*) crypt_ftr.crypto_type_name);
3080 if (!rc) {
3081 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3082 goto error_shutting_down;
3083 }
3084#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003085
Paul Lawrence87999172014-02-20 12:21:31 -08003086 /* Make an encrypted master key */
3087 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3088 SLOGE("Cannot create encrypted master key\n");
3089 goto error_shutting_down;
3090 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003091
Paul Lawrence87999172014-02-20 12:21:31 -08003092 /* Write the key to the end of the partition */
3093 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003094
Paul Lawrence87999172014-02-20 12:21:31 -08003095 /* If any persistent data has been remembered, save it.
3096 * If none, create a valid empty table and save that.
3097 */
3098 if (!persist_data) {
3099 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3100 if (pdata) {
3101 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3102 persist_data = pdata;
3103 }
3104 }
3105 if (persist_data) {
3106 save_persistent_data();
3107 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003108 }
3109
Paul Lawrence569649f2015-09-09 12:13:00 -07003110 if (how == CRYPTO_ENABLE_INPLACE && !no_ui) {
Ajay Dudani87701e22014-09-17 21:02:52 -07003111 /* startup service classes main and late_start */
3112 property_set("vold.decrypt", "trigger_restart_min_framework");
3113 SLOGD("Just triggered restart_min_framework\n");
3114
3115 /* OK, the framework is restarted and will soon be showing a
3116 * progress bar. Time to setup an encrypted mapping, and
3117 * either write a new filesystem, or encrypt in place updating
3118 * the progress bar as we work.
3119 */
3120 }
3121
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003122 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003123 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3124 "userdata");
3125
Paul Lawrence87999172014-02-20 12:21:31 -08003126 /* If we are continuing, check checksums match */
3127 rc = 0;
3128 if (previously_encrypted_upto) {
3129 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3130 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003131
Paul Lawrence87999172014-02-20 12:21:31 -08003132 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3133 sizeof(hash_first_block)) != 0) {
3134 SLOGE("Checksums do not match - trigger wipe");
3135 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003136 }
3137 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003138
Paul Lawrence87999172014-02-20 12:21:31 -08003139 if (!rc) {
3140 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3141 crypto_blkdev, real_blkdev,
3142 previously_encrypted_upto);
3143 }
3144
3145 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003146 if (!rc && how == CRYPTO_ENABLE_INPLACE
3147 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003148 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3149 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003150 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003151 SLOGE("Error calculating checksum for continuing encryption");
3152 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003153 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003154 }
3155
3156 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003157 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003158
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003159 if (! rc) {
3160 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003161 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003162
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003163 if (how == CRYPTO_ENABLE_INPLACE
3164 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003165 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3166 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003167 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003168 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003169
Paul Lawrence6bfed202014-07-28 12:47:22 -07003170 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003171
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003172 if (how == CRYPTO_ENABLE_WIPE
3173 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003174 char value[PROPERTY_VALUE_MAX];
3175 property_get("ro.crypto.state", value, "");
3176 if (!strcmp(value, "")) {
3177 /* default encryption - continue first boot sequence */
3178 property_set("ro.crypto.state", "encrypted");
3179 release_wake_lock(lockid);
3180 cryptfs_check_passwd(DEFAULT_PASSWORD);
3181 cryptfs_restart_internal(1);
3182 return 0;
3183 } else {
3184 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003185 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003186 }
Paul Lawrence87999172014-02-20 12:21:31 -08003187 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003188 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003189 cryptfs_reboot(shutdown);
3190 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003191 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003192 char value[PROPERTY_VALUE_MAX];
3193
Ken Sumrall319369a2012-06-27 16:30:18 -07003194 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003195 if (!strcmp(value, "1")) {
3196 /* wipe data if encryption failed */
3197 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3198 mkdir("/cache/recovery", 0700);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003199 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003200 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003201 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3202 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003203 close(fd);
3204 } else {
3205 SLOGE("could not open /cache/recovery/command\n");
3206 }
Paul Lawrence87999172014-02-20 12:21:31 -08003207 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003208 } else {
3209 /* set property to trigger dialog */
3210 property_set("vold.encrypt_progress", "error_partially_encrypted");
3211 release_wake_lock(lockid);
3212 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003213 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003214 }
3215
Ken Sumrall3ed82362011-01-28 23:31:16 -08003216 /* hrm, the encrypt step claims success, but the reboot failed.
3217 * This should not happen.
3218 * Set the property and return. Hope the framework can deal with it.
3219 */
3220 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003221 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003222 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003223
3224error_unencrypted:
3225 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003226 if (lockid[0]) {
3227 release_wake_lock(lockid);
3228 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003229 return -1;
3230
3231error_shutting_down:
3232 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3233 * but the framework is stopped and not restarted to show the error, so it's up to
3234 * vold to restart the system.
3235 */
3236 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003237 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003238
3239 /* shouldn't get here */
3240 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003241 if (lockid[0]) {
3242 release_wake_lock(lockid);
3243 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003244 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003245}
3246
Paul Lawrence569649f2015-09-09 12:13:00 -07003247int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003248{
Paul Lawrence569649f2015-09-09 12:13:00 -07003249 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003250}
3251
Paul Lawrence569649f2015-09-09 12:13:00 -07003252int cryptfs_enable_default(char *howarg, int no_ui)
Paul Lawrence13486032014-02-03 13:28:11 -08003253{
3254 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
Paul Lawrence569649f2015-09-09 12:13:00 -07003255 DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003256}
3257
3258int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003259{
Paul Lawrence05335c32015-03-05 09:46:23 -08003260 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
Paul Lawrencef733ae62015-07-07 15:43:14 -07003261 return e4crypt_change_password(DATA_MNT_POINT, crypt_type,
3262 crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3263 : newpw);
Paul Lawrence05335c32015-03-05 09:46:23 -08003264 }
3265
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003266 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003267 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003268
3269 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003270 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003271 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003272 return -1;
3273 }
3274
Paul Lawrencef4faa572014-01-29 13:31:03 -08003275 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3276 SLOGE("Invalid crypt_type %d", crypt_type);
3277 return -1;
3278 }
3279
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003280 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003281 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003282 SLOGE("Error getting crypt footer and key");
3283 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003284 }
3285
Paul Lawrencef4faa572014-01-29 13:31:03 -08003286 crypt_ftr.crypt_type = crypt_type;
3287
JP Abgrall933216c2015-02-11 13:44:32 -08003288 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003289 : newpw,
3290 crypt_ftr.salt,
3291 saved_master_key,
3292 crypt_ftr.master_key,
3293 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003294 if (rc) {
3295 SLOGE("Encrypt master key failed: %d", rc);
3296 return -1;
3297 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003298 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003299 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003300
Ajay Dudani87701e22014-09-17 21:02:52 -07003301#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003302 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3303 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3304 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3305 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3306 if (!rc)
3307 return -1;
3308 } else {
3309 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3310 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3311 if (!rc)
3312 return -1;
3313 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003314 }
3315#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003316 return 0;
3317}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003318
Rubin Xu85c01f92014-10-13 12:49:54 +01003319static unsigned int persist_get_max_entries(int encrypted) {
3320 struct crypt_mnt_ftr crypt_ftr;
3321 unsigned int dsize;
3322 unsigned int max_persistent_entries;
3323
3324 /* If encrypted, use the values from the crypt_ftr, otherwise
3325 * use the values for the current spec.
3326 */
3327 if (encrypted) {
3328 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3329 return -1;
3330 }
3331 dsize = crypt_ftr.persist_data_size;
3332 } else {
3333 dsize = CRYPT_PERSIST_DATA_SIZE;
3334 }
3335
3336 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3337 sizeof(struct crypt_persist_entry);
3338
3339 return max_persistent_entries;
3340}
3341
3342static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003343{
3344 unsigned int i;
3345
3346 if (persist_data == NULL) {
3347 return -1;
3348 }
3349 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3350 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3351 /* We found it! */
3352 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3353 return 0;
3354 }
3355 }
3356
3357 return -1;
3358}
3359
Rubin Xu85c01f92014-10-13 12:49:54 +01003360static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003361{
3362 unsigned int i;
3363 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003364 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003365
3366 if (persist_data == NULL) {
3367 return -1;
3368 }
3369
Rubin Xu85c01f92014-10-13 12:49:54 +01003370 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003371
3372 num = persist_data->persist_valid_entries;
3373
3374 for (i = 0; i < num; i++) {
3375 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3376 /* We found an existing entry, update it! */
3377 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3378 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3379 return 0;
3380 }
3381 }
3382
3383 /* We didn't find it, add it to the end, if there is room */
3384 if (persist_data->persist_valid_entries < max_persistent_entries) {
3385 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3386 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3387 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3388 persist_data->persist_valid_entries++;
3389 return 0;
3390 }
3391
3392 return -1;
3393}
3394
Rubin Xu85c01f92014-10-13 12:49:54 +01003395/**
3396 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3397 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3398 */
3399static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003400 unsigned int field_len;
3401 unsigned int key_index;
3402 field_len = strlen(field);
3403
3404 if (index == 0) {
3405 // The first key in a multi-entry field is just the filedname itself.
3406 if (!strcmp(key, field)) {
3407 return 1;
3408 }
3409 }
3410 // Match key against "%s_%d" % (field, index)
3411 if (strlen(key) < field_len + 1 + 1) {
3412 // Need at least a '_' and a digit.
3413 return 0;
3414 }
3415 if (strncmp(key, field, field_len)) {
3416 // If the key does not begin with field, it's not a match.
3417 return 0;
3418 }
3419 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3420 return 0;
3421 }
3422 return key_index >= index;
3423}
3424
3425/*
3426 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3427 * remaining entries starting from index will be deleted.
3428 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3429 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3430 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3431 *
3432 */
3433static int persist_del_keys(const char *fieldname, unsigned index)
3434{
3435 unsigned int i;
3436 unsigned int j;
3437 unsigned int num;
3438
3439 if (persist_data == NULL) {
3440 return PERSIST_DEL_KEY_ERROR_OTHER;
3441 }
3442
3443 num = persist_data->persist_valid_entries;
3444
3445 j = 0; // points to the end of non-deleted entries.
3446 // Filter out to-be-deleted entries in place.
3447 for (i = 0; i < num; i++) {
3448 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3449 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3450 j++;
3451 }
3452 }
3453
3454 if (j < num) {
3455 persist_data->persist_valid_entries = j;
3456 // Zeroise the remaining entries
3457 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3458 return PERSIST_DEL_KEY_OK;
3459 } else {
3460 // Did not find an entry matching the given fieldname
3461 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3462 }
3463}
3464
3465static int persist_count_keys(const char *fieldname)
3466{
3467 unsigned int i;
3468 unsigned int count;
3469
3470 if (persist_data == NULL) {
3471 return -1;
3472 }
3473
3474 count = 0;
3475 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3476 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3477 count++;
3478 }
3479 }
3480
3481 return count;
3482}
3483
Ken Sumrall160b4d62013-04-22 12:15:39 -07003484/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003485int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003486{
Paul Lawrence368d7942015-04-15 14:12:00 -07003487 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3488 return e4crypt_get_field(DATA_MNT_POINT, fieldname, value, len);
3489 }
3490
Ken Sumrall160b4d62013-04-22 12:15:39 -07003491 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003492 /* CRYPTO_GETFIELD_OK is success,
3493 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3494 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3495 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003496 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003497 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3498 int i;
3499 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003500
3501 if (persist_data == NULL) {
3502 load_persistent_data();
3503 if (persist_data == NULL) {
3504 SLOGE("Getfield error, cannot load persistent data");
3505 goto out;
3506 }
3507 }
3508
Rubin Xu85c01f92014-10-13 12:49:54 +01003509 // Read value from persistent entries. If the original value is split into multiple entries,
3510 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003511 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003512 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3513 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3514 // value too small
3515 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3516 goto out;
3517 }
3518 rc = CRYPTO_GETFIELD_OK;
3519
3520 for (i = 1; /* break explicitly */; i++) {
3521 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3522 (int) sizeof(temp_field)) {
3523 // If the fieldname is very long, we stop as soon as it begins to overflow the
3524 // maximum field length. At this point we have in fact fully read out the original
3525 // value because cryptfs_setfield would not allow fields with longer names to be
3526 // written in the first place.
3527 break;
3528 }
3529 if (!persist_get_key(temp_field, temp_value)) {
3530 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3531 // value too small.
3532 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3533 goto out;
3534 }
3535 } else {
3536 // Exhaust all entries.
3537 break;
3538 }
3539 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003540 } else {
3541 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003542 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003543 }
3544
3545out:
3546 return rc;
3547}
3548
3549/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003550int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003551{
Paul Lawrence368d7942015-04-15 14:12:00 -07003552 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3553 return e4crypt_set_field(DATA_MNT_POINT, fieldname, value);
3554 }
3555
Ken Sumrall160b4d62013-04-22 12:15:39 -07003556 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003557 /* 0 is success, negative values are error */
3558 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003559 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003560 unsigned int field_id;
3561 char temp_field[PROPERTY_KEY_MAX];
3562 unsigned int num_entries;
3563 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003564
3565 if (persist_data == NULL) {
3566 load_persistent_data();
3567 if (persist_data == NULL) {
3568 SLOGE("Setfield error, cannot load persistent data");
3569 goto out;
3570 }
3571 }
3572
3573 property_get("ro.crypto.state", encrypted_state, "");
3574 if (!strcmp(encrypted_state, "encrypted") ) {
3575 encrypted = 1;
3576 }
3577
Rubin Xu85c01f92014-10-13 12:49:54 +01003578 // Compute the number of entries required to store value, each entry can store up to
3579 // (PROPERTY_VALUE_MAX - 1) chars
3580 if (strlen(value) == 0) {
3581 // Empty value also needs one entry to store.
3582 num_entries = 1;
3583 } else {
3584 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3585 }
3586
3587 max_keylen = strlen(fieldname);
3588 if (num_entries > 1) {
3589 // Need an extra "_%d" suffix.
3590 max_keylen += 1 + log10(num_entries);
3591 }
3592 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3593 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003594 goto out;
3595 }
3596
Rubin Xu85c01f92014-10-13 12:49:54 +01003597 // Make sure we have enough space to write the new value
3598 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3599 persist_get_max_entries(encrypted)) {
3600 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3601 goto out;
3602 }
3603
3604 // Now that we know persist_data has enough space for value, let's delete the old field first
3605 // to make up space.
3606 persist_del_keys(fieldname, 0);
3607
3608 if (persist_set_key(fieldname, value, encrypted)) {
3609 // fail to set key, should not happen as we have already checked the available space
3610 SLOGE("persist_set_key() error during setfield()");
3611 goto out;
3612 }
3613
3614 for (field_id = 1; field_id < num_entries; field_id++) {
3615 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3616
3617 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3618 // fail to set key, should not happen as we have already checked the available space.
3619 SLOGE("persist_set_key() error during setfield()");
3620 goto out;
3621 }
3622 }
3623
Ken Sumrall160b4d62013-04-22 12:15:39 -07003624 /* If we are running encrypted, save the persistent data now */
3625 if (encrypted) {
3626 if (save_persistent_data()) {
3627 SLOGE("Setfield error, cannot save persistent data");
3628 goto out;
3629 }
3630 }
3631
Rubin Xu85c01f92014-10-13 12:49:54 +01003632 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003633
3634out:
3635 return rc;
3636}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003637
3638/* Checks userdata. Attempt to mount the volume if default-
3639 * encrypted.
3640 * On success trigger next init phase and return 0.
3641 * Currently do not handle failure - see TODO below.
3642 */
3643int cryptfs_mount_default_encrypted(void)
3644{
3645 char decrypt_state[PROPERTY_VALUE_MAX];
3646 property_get("vold.decrypt", decrypt_state, "0");
3647 if (!strcmp(decrypt_state, "0")) {
3648 SLOGE("Not encrypted - should not call here");
3649 } else {
3650 int crypt_type = cryptfs_get_password_type();
3651 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3652 SLOGE("Bad crypt type - error");
3653 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3654 SLOGD("Password is not default - "
3655 "starting min framework to prompt");
3656 property_set("vold.decrypt", "trigger_restart_min_framework");
3657 return 0;
3658 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3659 SLOGD("Password is default - restarting filesystem");
3660 cryptfs_restart_internal(0);
3661 return 0;
3662 } else {
3663 SLOGE("Encrypted, default crypt type but can't decrypt");
3664 }
3665 }
3666
Paul Lawrence6bfed202014-07-28 12:47:22 -07003667 /** Corrupt. Allow us to boot into framework, which will detect bad
3668 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003669 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003670 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003671 return 0;
3672}
3673
3674/* Returns type of the password, default, pattern, pin or password.
3675 */
3676int cryptfs_get_password_type(void)
3677{
Paul Lawrence05335c32015-03-05 09:46:23 -08003678 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3679 return e4crypt_get_password_type(DATA_MNT_POINT);
3680 }
3681
Paul Lawrencef4faa572014-01-29 13:31:03 -08003682 struct crypt_mnt_ftr crypt_ftr;
3683
3684 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3685 SLOGE("Error getting crypt footer and key\n");
3686 return -1;
3687 }
3688
Paul Lawrence6bfed202014-07-28 12:47:22 -07003689 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3690 return -1;
3691 }
3692
Paul Lawrencef4faa572014-01-29 13:31:03 -08003693 return crypt_ftr.crypt_type;
3694}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003695
Paul Lawrence05335c32015-03-05 09:46:23 -08003696const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003697{
Paul Lawrence05335c32015-03-05 09:46:23 -08003698 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3699 return e4crypt_get_password(DATA_MNT_POINT);
3700 }
3701
Paul Lawrence399317e2014-03-10 13:20:50 -07003702 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003703 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003704 if (now.tv_sec < password_expiry_time) {
3705 return password;
3706 } else {
3707 cryptfs_clear_password();
3708 return 0;
3709 }
3710}
3711
3712void cryptfs_clear_password()
3713{
Paul Lawrence86c942a2015-05-06 13:53:43 -07003714 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3715 e4crypt_clear_password(DATA_MNT_POINT);
3716 }
3717
Paul Lawrence399317e2014-03-10 13:20:50 -07003718 if (password) {
3719 size_t len = strlen(password);
3720 memset(password, 0, len);
3721 free(password);
3722 password = 0;
3723 password_expiry_time = 0;
3724 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003725}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003726
3727int cryptfs_enable_file()
3728{
3729 return e4crypt_enable(DATA_MNT_POINT);
3730}
3731
3732int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3733{
3734 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3735 SLOGE("Failed to initialize crypt_ftr");
3736 return -1;
3737 }
3738
3739 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3740 crypt_ftr->salt, crypt_ftr)) {
3741 SLOGE("Cannot create encrypted master key\n");
3742 return -1;
3743 }
3744
3745 //crypt_ftr->keysize = key_length / 8;
3746 return 0;
3747}
3748
3749int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3750 unsigned char* master_key)
3751{
3752 int rc;
3753
Paul Lawrence731a7a22015-04-28 22:14:15 +00003754 unsigned char* intermediate_key = 0;
3755 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003756
3757 if (password == 0 || *password == 0) {
3758 password = DEFAULT_PASSWORD;
3759 }
3760
Paul Lawrence731a7a22015-04-28 22:14:15 +00003761 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3762 &intermediate_key_size);
3763
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003764 int N = 1 << ftr->N_factor;
3765 int r = 1 << ftr->r_factor;
3766 int p = 1 << ftr->p_factor;
3767
3768 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3769
3770 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3771 ftr->salt, sizeof(ftr->salt), N, r, p,
3772 scrypted_intermediate_key,
3773 sizeof(scrypted_intermediate_key));
3774
3775 free(intermediate_key);
3776
3777 if (rc) {
3778 SLOGE("Can't calculate intermediate key");
3779 return rc;
3780 }
3781
3782 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3783 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00003784}
3785
3786int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3787 const unsigned char* master_key)
3788{
3789 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3790 ftr);
3791}