OSDN Git Service

vold: Fix fsck on public volumes
[android-x86/system-vold.git] / cryptfs.c
1 /*
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>
24 #include <sys/wait.h>
25 #include <sys/stat.h>
26 #include <ctype.h>
27 #include <fcntl.h>
28 #include <inttypes.h>
29 #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>
39 #include <openssl/sha.h>
40 #include <errno.h>
41 #include <ext4.h>
42 #include <linux/kdev_t.h>
43 #include <fs_mgr.h>
44 #include <time.h>
45 #include <math.h>
46 #include "cryptfs.h"
47 #define LOG_TAG "Cryptfs"
48 #include "cutils/log.h"
49 #include "cutils/properties.h"
50 #include "cutils/android_reboot.h"
51 #include "hardware_legacy/power.h"
52 #include <logwrap/logwrap.h>
53 #include "VolumeManager.h"
54 #include "VoldUtil.h"
55 #include "crypto_scrypt.h"
56 #include "Ext4Crypt.h"
57 #include "ext4_crypt_init_extensions.h"
58 #include "ext4_utils.h"
59 #include "f2fs_sparseblock.h"
60 #include "CheckBattery.h"
61 #include "Process.h"
62
63 #include <hardware/keymaster0.h>
64 #include <hardware/keymaster1.h>
65
66 #define UNUSED __attribute__((unused))
67
68 #define UNUSED __attribute__((unused))
69
70 #ifdef CONFIG_HW_DISK_ENCRYPTION
71 #include "cryptfs_hw.h"
72 #endif
73
74 #define DM_CRYPT_BUF_SIZE 4096
75
76 #define HASH_COUNT 2000
77 #define KEY_LEN_BYTES 16
78 #define IV_LEN_BYTES 16
79
80 #define KEY_IN_FOOTER  "footer"
81
82 #define DEFAULT_PASSWORD "default_password"
83
84 #define EXT4_FS 1
85 #define F2FS_FS 2
86
87 #define TABLE_LOAD_RETRIES 10
88
89 #define RSA_KEY_SIZE 2048
90 #define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
91 #define RSA_EXPONENT 0x10001
92 #define KEYMASTER_CRYPTFS_RATE_LIMIT 1  // Maximum one try per second
93
94 #define RETRY_MOUNT_ATTEMPTS 10
95 #define RETRY_MOUNT_DELAY_SECONDS 1
96
97 char *me = "cryptfs";
98
99 static unsigned char saved_master_key[KEY_LEN_BYTES];
100 static char *saved_mount_point;
101 static int  master_key_saved = 0;
102 static struct crypt_persist_data *persist_data = NULL;
103
104 static int previous_type;
105
106 #ifdef MINIVOLD
107 inline int release_wake_lock(const char* id) { return 0; }
108 inline int acquire_wake_lock(int lock, const char* id) { return 0; }
109 #endif
110
111 #ifdef CONFIG_HW_DISK_ENCRYPTION
112 static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
113                             unsigned char *ikey, void *params);
114
115 static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
116                                   unsigned char* salt,
117                                   const struct crypt_mnt_ftr *ftr)
118 {
119     /* if newpw updated, return 0
120      * if newpw not updated return -1
121      */
122     int rc = -1;
123
124     if (should_use_keymaster()) {
125         if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
126             SLOGE("scrypt failed");
127         } else {
128             rc = 0;
129         }
130     }
131
132     return rc;
133 }
134 #endif
135
136 #ifndef MINIVOLD // no HALs in recovery...
137 static int keymaster_init(keymaster0_device_t **keymaster0_dev,
138                           keymaster1_device_t **keymaster1_dev)
139 {
140     int rc;
141
142     const hw_module_t* mod;
143     rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
144     if (rc) {
145         ALOGE("could not find any keystore module");
146         goto err;
147     }
148
149     SLOGI("keymaster module name is %s", mod->name);
150     SLOGI("keymaster version is %d", mod->module_api_version);
151
152     *keymaster0_dev = NULL;
153     *keymaster1_dev = NULL;
154     if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
155         SLOGI("Found keymaster1 module, using keymaster1 API.");
156         rc = keymaster1_open(mod, keymaster1_dev);
157     } else {
158         SLOGI("Found keymaster0 module, using keymaster0 API.");
159         rc = keymaster0_open(mod, keymaster0_dev);
160     }
161
162     if (rc) {
163         ALOGE("could not open keymaster device in %s (%s)",
164               KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
165         goto err;
166     }
167
168     return 0;
169
170 err:
171     *keymaster0_dev = NULL;
172     *keymaster1_dev = NULL;
173     return rc;
174 }
175 #endif
176
177 /* Should we use keymaster? */
178 static int keymaster_check_compatibility()
179 {
180 #ifdef MINIVOLD
181     return -1;
182 #else
183     keymaster0_device_t *keymaster0_dev = 0;
184     keymaster1_device_t *keymaster1_dev = 0;
185     int rc = 0;
186
187     if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
188         SLOGE("Failed to init keymaster");
189         rc = -1;
190         goto out;
191     }
192
193     if (keymaster1_dev) {
194         rc = 1;
195         goto out;
196     }
197
198     // TODO(swillden): Check to see if there's any reason to require v0.3.  I think v0.1 and v0.2
199     // should work.
200     if (keymaster0_dev->common.module->module_api_version
201             < KEYMASTER_MODULE_API_VERSION_0_3) {
202         rc = 0;
203         goto out;
204     }
205
206     if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
207         (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
208         rc = 1;
209     }
210
211 out:
212     if (keymaster1_dev) {
213         keymaster1_close(keymaster1_dev);
214     }
215     if (keymaster0_dev) {
216         keymaster0_close(keymaster0_dev);
217     }
218     return rc;
219 #endif
220 }
221
222 /* Create a new keymaster key and store it in this footer */
223 static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
224 {
225 #ifdef MINIVOLD // no HALs in recovery...
226     return -1;
227 #else
228     uint8_t* key = 0;
229     keymaster0_device_t *keymaster0_dev = 0;
230     keymaster1_device_t *keymaster1_dev = 0;
231
232     if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
233         SLOGE("Failed to init keymaster");
234         return -1;
235     }
236
237     int rc = 0;
238     size_t key_size = 0;
239     if (keymaster1_dev) {
240         keymaster_key_param_t params[] = {
241             /* Algorithm & size specifications.  Stick with RSA for now.  Switch to AES later. */
242             keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
243             keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
244             keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
245
246             /* The only allowed purpose for this key is signing. */
247             keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
248
249             /* Padding & digest specifications. */
250             keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
251             keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
252
253             /* Require that the key be usable in standalone mode.  File system isn't available. */
254             keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
255
256             /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
257             keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
258
259             /* Rate-limit key usage attempts, to rate-limit brute force */
260             keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
261         };
262         keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
263         keymaster_key_blob_t key_blob;
264         keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, &param_set,
265                                                                &key_blob,
266                                                                NULL /* characteristics */);
267         if (error != KM_ERROR_OK) {
268             SLOGE("Failed to generate keymaster1 key, error %d", error);
269             rc = -1;
270             goto out;
271         }
272
273         key = (uint8_t*)key_blob.key_material;
274         key_size = key_blob.key_material_size;
275     }
276     else if (keymaster0_dev) {
277         keymaster_rsa_keygen_params_t params;
278         memset(&params, '\0', sizeof(params));
279         params.public_exponent = RSA_EXPONENT;
280         params.modulus_size = RSA_KEY_SIZE;
281
282         if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, &params,
283                                              &key, &key_size)) {
284             SLOGE("Failed to generate keypair");
285             rc = -1;
286             goto out;
287         }
288     } else {
289         SLOGE("Cryptfs bug: keymaster_init succeeded but didn't initialize a device");
290         rc = -1;
291         goto out;
292     }
293
294     if (key_size > KEYMASTER_BLOB_SIZE) {
295         SLOGE("Keymaster key too large for crypto footer");
296         rc = -1;
297         goto out;
298     }
299
300     memcpy(ftr->keymaster_blob, key, key_size);
301     ftr->keymaster_blob_size = key_size;
302
303 out:
304     if (keymaster0_dev)
305         keymaster0_close(keymaster0_dev);
306     if (keymaster1_dev)
307         keymaster1_close(keymaster1_dev);
308     free(key);
309     return rc;
310 #endif
311 }
312
313 /* This signs the given object using the keymaster key. */
314 static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
315                                  const unsigned char *object,
316                                  const size_t object_size,
317                                  unsigned char **signature,
318                                  size_t *signature_size)
319 {
320 #ifdef MINIVOLD // no HALs in recovery...
321     return -1;
322 #else
323     int rc = 0;
324     keymaster0_device_t *keymaster0_dev = 0;
325     keymaster1_device_t *keymaster1_dev = 0;
326     if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
327         SLOGE("Failed to init keymaster");
328         rc = -1;
329         goto out;
330     }
331
332     unsigned char to_sign[RSA_KEY_SIZE_BYTES];
333     size_t to_sign_size = sizeof(to_sign);
334     memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
335
336     // To sign a message with RSA, the message must satisfy two
337     // constraints:
338     //
339     // 1. The message, when interpreted as a big-endian numeric value, must
340     //    be strictly less than the public modulus of the RSA key.  Note
341     //    that because the most significant bit of the public modulus is
342     //    guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
343     //    key), an n-bit message with most significant bit 0 always
344     //    satisfies this requirement.
345     //
346     // 2. The message must have the same length in bits as the public
347     //    modulus of the RSA key.  This requirement isn't mathematically
348     //    necessary, but is necessary to ensure consistency in
349     //    implementations.
350     switch (ftr->kdf_type) {
351         case KDF_SCRYPT_KEYMASTER:
352             // This ensures the most significant byte of the signed message
353             // is zero.  We could have zero-padded to the left instead, but
354             // this approach is slightly more robust against changes in
355             // object size.  However, it's still broken (but not unusably
356             // so) because we really should be using a proper deterministic
357             // RSA padding function, such as PKCS1.
358             memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
359             SLOGI("Signing safely-padded object");
360             break;
361         default:
362             SLOGE("Unknown KDF type %d", ftr->kdf_type);
363             rc = -1;
364             goto out;
365     }
366
367     if (keymaster0_dev) {
368         keymaster_rsa_sign_params_t params;
369         params.digest_type = DIGEST_NONE;
370         params.padding_type = PADDING_NONE;
371
372         rc = keymaster0_dev->sign_data(keymaster0_dev,
373                                       &params,
374                                       ftr->keymaster_blob,
375                                       ftr->keymaster_blob_size,
376                                       to_sign,
377                                       to_sign_size,
378                                       signature,
379                                       signature_size);
380         goto out;
381     } else if (keymaster1_dev) {
382         keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
383         keymaster_key_param_t params[] = {
384             keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
385             keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
386         };
387         keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
388         keymaster_operation_handle_t op_handle;
389         keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
390                                                         &param_set, NULL /* out_params */,
391                                                         &op_handle);
392         if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
393             // Key usage has been rate-limited.  Wait a bit and try again.
394             sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
395             error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
396                                           &param_set, NULL /* out_params */,
397                                           &op_handle);
398         }
399         if (error != KM_ERROR_OK) {
400             SLOGE("Error starting keymaster signature transaction: %d", error);
401             rc = -1;
402             goto out;
403         }
404
405         keymaster_blob_t input = { to_sign, to_sign_size };
406         size_t input_consumed;
407         error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
408                                        &input, &input_consumed, NULL /* out_params */,
409                                        NULL /* output */);
410         if (error != KM_ERROR_OK) {
411             SLOGE("Error sending data to keymaster signature transaction: %d", error);
412             rc = -1;
413             goto out;
414         }
415         if (input_consumed != to_sign_size) {
416             // This should never happen.  If it does, it's a bug in the keymaster implementation.
417             SLOGE("Keymaster update() did not consume all data.");
418             keymaster1_dev->abort(keymaster1_dev, op_handle);
419             rc = -1;
420             goto out;
421         }
422
423         keymaster_blob_t tmp_sig;
424         error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
425                                        NULL /* verify signature */, NULL /* out_params */,
426                                        &tmp_sig);
427         if (error != KM_ERROR_OK) {
428             SLOGE("Error finishing keymaster signature transaction: %d", error);
429             rc = -1;
430             goto out;
431         }
432
433         *signature = (uint8_t*)tmp_sig.data;
434         *signature_size = tmp_sig.data_length;
435     } else {
436         SLOGE("Cryptfs bug: keymaster_init succeded but didn't initialize a device.");
437         rc = -1;
438         goto out;
439     }
440
441     out:
442         if (keymaster1_dev)
443             keymaster1_close(keymaster1_dev);
444         if (keymaster0_dev)
445             keymaster0_close(keymaster0_dev);
446
447         return rc;
448 #endif
449 }
450
451 /* Store password when userdata is successfully decrypted and mounted.
452  * Cleared by cryptfs_clear_password
453  *
454  * To avoid a double prompt at boot, we need to store the CryptKeeper
455  * password and pass it to KeyGuard, which uses it to unlock KeyStore.
456  * Since the entire framework is torn down and rebuilt after encryption,
457  * we have to use a daemon or similar to store the password. Since vold
458  * is secured against IPC except from system processes, it seems a reasonable
459  * place to store this.
460  *
461  * password should be cleared once it has been used.
462  *
463  * password is aged out after password_max_age_seconds seconds.
464  */
465 static char* password = 0;
466 static int password_expiry_time = 0;
467 static const int password_max_age_seconds = 60;
468
469 extern struct fstab *fstab;
470
471 enum RebootType {reboot, recovery, shutdown};
472 static void cryptfs_reboot(enum RebootType rt)
473 {
474   switch(rt) {
475       case reboot:
476           property_set(ANDROID_RB_PROPERTY, "reboot");
477           break;
478
479       case recovery:
480           property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
481           break;
482
483       case shutdown:
484           property_set(ANDROID_RB_PROPERTY, "shutdown");
485           break;
486     }
487
488     sleep(20);
489
490     /* Shouldn't get here, reboot should happen before sleep times out */
491     return;
492 }
493
494 static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
495 {
496     memset(io, 0, dataSize);
497     io->data_size = dataSize;
498     io->data_start = sizeof(struct dm_ioctl);
499     io->version[0] = 4;
500     io->version[1] = 0;
501     io->version[2] = 0;
502     io->flags = flags;
503     if (name) {
504         strlcpy(io->name, name, sizeof(io->name));
505     }
506 }
507
508 /**
509  * Gets the default device scrypt parameters for key derivation time tuning.
510  * The parameters should lead to about one second derivation time for the
511  * given device.
512  */
513 static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
514     const int default_params[] = SCRYPT_DEFAULTS;
515     int params[] = SCRYPT_DEFAULTS;
516     char paramstr[PROPERTY_VALUE_MAX];
517     char *token;
518     char *saveptr;
519     int i;
520
521     property_get(SCRYPT_PROP, paramstr, "");
522     if (paramstr[0] != '\0') {
523         /*
524          * The token we're looking for should be three integers separated by
525          * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
526          */
527         for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
528                 token != NULL && i < 3;
529                 i++, token = strtok_r(NULL, ":", &saveptr)) {
530             char *endptr;
531             params[i] = strtol(token, &endptr, 10);
532
533             /*
534              * Check that there was a valid number and it's 8-bit. If not,
535              * break out and the end check will take the default values.
536              */
537             if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
538                 break;
539             }
540         }
541
542         /*
543          * If there were not enough tokens or a token was malformed (not an
544          * integer), it will end up here and the default parameters can be
545          * taken.
546          */
547         if ((i != 3) || (token != NULL)) {
548             SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
549             memcpy(params, default_params, sizeof(params));
550         }
551     }
552
553     ftr->N_factor = params[0];
554     ftr->r_factor = params[1];
555     ftr->p_factor = params[2];
556 }
557
558 static unsigned int get_fs_size(char *dev)
559 {
560     int fd, block_size;
561     struct ext4_super_block sb;
562     off64_t len;
563
564     if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
565         SLOGE("Cannot open device to get filesystem size ");
566         return 0;
567     }
568
569     if (lseek64(fd, 1024, SEEK_SET) < 0) {
570         SLOGE("Cannot seek to superblock");
571         return 0;
572     }
573
574     if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
575         SLOGE("Cannot read superblock");
576         return 0;
577     }
578
579     close(fd);
580
581     if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
582         SLOGE("Not a valid ext4 superblock");
583         return 0;
584     }
585     block_size = 1024 << sb.s_log_block_size;
586     /* compute length in bytes */
587     len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
588
589     /* return length in sectors */
590     return (unsigned int) (len / 512);
591 }
592
593 static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
594 {
595   static int cached_data = 0;
596   static off64_t cached_off = 0;
597   static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
598   int fd;
599   char key_loc[PROPERTY_VALUE_MAX];
600   char real_blkdev[PROPERTY_VALUE_MAX];
601   int rc = -1;
602
603   if (!cached_data) {
604     fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
605
606     if (!strcmp(key_loc, KEY_IN_FOOTER)) {
607       if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
608         SLOGE("Cannot open real block device %s\n", real_blkdev);
609         return -1;
610       }
611
612       unsigned long nr_sec = 0;
613       get_blkdev_size(fd, &nr_sec);
614       if (nr_sec != 0) {
615         /* If it's an encrypted Android partition, the last 16 Kbytes contain the
616          * encryption info footer and key, and plenty of bytes to spare for future
617          * growth.
618          */
619         strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
620         cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
621         cached_data = 1;
622       } else {
623         SLOGE("Cannot get size of block device %s\n", real_blkdev);
624       }
625       close(fd);
626     } else {
627       strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
628       cached_off = 0;
629       cached_data = 1;
630     }
631   }
632
633   if (cached_data) {
634     if (metadata_fname) {
635         *metadata_fname = cached_metadata_fname;
636     }
637     if (off) {
638         *off = cached_off;
639     }
640     rc = 0;
641   }
642
643   return rc;
644 }
645
646 /* key or salt can be NULL, in which case just skip writing that value.  Useful to
647  * update the failed mount count but not change the key.
648  */
649 static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
650 {
651   int fd;
652   unsigned int cnt;
653   /* starting_off is set to the SEEK_SET offset
654    * where the crypto structure starts
655    */
656   off64_t starting_off;
657   int rc = -1;
658   char *fname = NULL;
659   struct stat statbuf;
660
661   if (get_crypt_ftr_info(&fname, &starting_off)) {
662     SLOGE("Unable to get crypt_ftr_info\n");
663     return -1;
664   }
665   if (fname[0] != '/') {
666     SLOGE("Unexpected value for crypto key location\n");
667     return -1;
668   }
669   if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
670     SLOGE("Cannot open footer file %s for put\n", fname);
671     return -1;
672   }
673
674   /* Seek to the start of the crypt footer */
675   if (lseek64(fd, starting_off, SEEK_SET) == -1) {
676     SLOGE("Cannot seek to real block device footer\n");
677     goto errout;
678   }
679
680   if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
681     SLOGE("Cannot write real block device footer\n");
682     goto errout;
683   }
684
685   fstat(fd, &statbuf);
686   /* If the keys are kept on a raw block device, do not try to truncate it. */
687   if (S_ISREG(statbuf.st_mode)) {
688     if (ftruncate(fd, 0x4000)) {
689       SLOGE("Cannot set footer file size\n");
690       goto errout;
691     }
692   }
693
694   /* Success! */
695   rc = 0;
696
697 errout:
698   close(fd);
699   return rc;
700
701 }
702
703 static inline int unix_read(int  fd, void*  buff, int  len)
704 {
705     return TEMP_FAILURE_RETRY(read(fd, buff, len));
706 }
707
708 static inline int unix_write(int  fd, const void*  buff, int  len)
709 {
710     return TEMP_FAILURE_RETRY(write(fd, buff, len));
711 }
712
713 static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
714 {
715     memset(pdata, 0, len);
716     pdata->persist_magic = PERSIST_DATA_MAGIC;
717     pdata->persist_valid_entries = 0;
718 }
719
720 /* A routine to update the passed in crypt_ftr to the lastest version.
721  * fd is open read/write on the device that holds the crypto footer and persistent
722  * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
723  * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
724  */
725 static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
726 {
727     int orig_major = crypt_ftr->major_version;
728     int orig_minor = crypt_ftr->minor_version;
729
730     if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
731         struct crypt_persist_data *pdata;
732         off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
733
734         SLOGW("upgrading crypto footer to 1.1");
735
736         pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
737         if (pdata == NULL) {
738             SLOGE("Cannot allocate persisent data\n");
739             return;
740         }
741         memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
742
743         /* Need to initialize the persistent data area */
744         if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
745             SLOGE("Cannot seek to persisent data offset\n");
746             free(pdata);
747             return;
748         }
749         /* Write all zeros to the first copy, making it invalid */
750         unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
751
752         /* Write a valid but empty structure to the second copy */
753         init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
754         unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
755
756         /* Update the footer */
757         crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
758         crypt_ftr->persist_data_offset[0] = pdata_offset;
759         crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
760         crypt_ftr->minor_version = 1;
761         free(pdata);
762     }
763
764     if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
765         SLOGW("upgrading crypto footer to 1.2");
766         /* But keep the old kdf_type.
767          * It will get updated later to KDF_SCRYPT after the password has been verified.
768          */
769         crypt_ftr->kdf_type = KDF_PBKDF2;
770         get_device_scrypt_params(crypt_ftr);
771         crypt_ftr->minor_version = 2;
772     }
773
774     if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
775         SLOGW("upgrading crypto footer to 1.3");
776         crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
777         crypt_ftr->minor_version = 3;
778     }
779
780     if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
781         if (lseek64(fd, offset, SEEK_SET) == -1) {
782             SLOGE("Cannot seek to crypt footer\n");
783             return;
784         }
785         unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
786     }
787 }
788
789
790 static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
791 {
792   int fd;
793   unsigned int cnt;
794   off64_t starting_off;
795   int rc = -1;
796   char *fname = NULL;
797   struct stat statbuf;
798
799   if (get_crypt_ftr_info(&fname, &starting_off)) {
800     SLOGE("Unable to get crypt_ftr_info\n");
801     return -1;
802   }
803   if (fname[0] != '/') {
804     SLOGE("Unexpected value for crypto key location\n");
805     return -1;
806   }
807   if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
808     SLOGE("Cannot open footer file %s for get\n", fname);
809     return -1;
810   }
811
812   /* Make sure it's 16 Kbytes in length */
813   fstat(fd, &statbuf);
814   if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
815     SLOGE("footer file %s is not the expected size!\n", fname);
816     goto errout;
817   }
818
819   /* Seek to the start of the crypt footer */
820   if (lseek64(fd, starting_off, SEEK_SET) == -1) {
821     SLOGE("Cannot seek to real block device footer\n");
822     goto errout;
823   }
824
825   if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
826     SLOGE("Cannot read real block device footer\n");
827     goto errout;
828   }
829
830   if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
831     SLOGE("Bad magic for real block device %s\n", fname);
832     goto errout;
833   }
834
835   if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
836     SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
837           crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
838     goto errout;
839   }
840
841   if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
842     SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
843           crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
844   }
845
846   /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
847    * copy on disk before returning.
848    */
849   if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
850     upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
851   }
852
853   /* Success! */
854   rc = 0;
855
856 errout:
857   close(fd);
858   return rc;
859 }
860
861 static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
862 {
863     if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
864         crypt_ftr->persist_data_offset[1]) {
865         SLOGE("Crypt_ftr persist data regions overlap");
866         return -1;
867     }
868
869     if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
870         SLOGE("Crypt_ftr persist data region 0 starts after region 1");
871         return -1;
872     }
873
874     if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
875         (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
876         CRYPT_FOOTER_OFFSET) {
877         SLOGE("Persistent data extends past crypto footer");
878         return -1;
879     }
880
881     return 0;
882 }
883
884 static int load_persistent_data(void)
885 {
886     struct crypt_mnt_ftr crypt_ftr;
887     struct crypt_persist_data *pdata = NULL;
888     char encrypted_state[PROPERTY_VALUE_MAX];
889     char *fname;
890     int found = 0;
891     int fd;
892     int ret;
893     int i;
894
895     if (persist_data) {
896         /* Nothing to do, we've already loaded or initialized it */
897         return 0;
898     }
899
900
901     /* If not encrypted, just allocate an empty table and initialize it */
902     property_get("ro.crypto.state", encrypted_state, "");
903     if (strcmp(encrypted_state, "encrypted") ) {
904         pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
905         if (pdata) {
906             init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
907             persist_data = pdata;
908             return 0;
909         }
910         return -1;
911     }
912
913     if(get_crypt_ftr_and_key(&crypt_ftr)) {
914         return -1;
915     }
916
917     if ((crypt_ftr.major_version < 1)
918         || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
919         SLOGE("Crypt_ftr version doesn't support persistent data");
920         return -1;
921     }
922
923     if (get_crypt_ftr_info(&fname, NULL)) {
924         return -1;
925     }
926
927     ret = validate_persistent_data_storage(&crypt_ftr);
928     if (ret) {
929         return -1;
930     }
931
932     fd = open(fname, O_RDONLY|O_CLOEXEC);
933     if (fd < 0) {
934         SLOGE("Cannot open %s metadata file", fname);
935         return -1;
936     }
937
938     if (persist_data == NULL) {
939         pdata = malloc(crypt_ftr.persist_data_size);
940         if (pdata == NULL) {
941             SLOGE("Cannot allocate memory for persistent data");
942             goto err;
943         }
944     }
945
946     for (i = 0; i < 2; i++) {
947         if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
948             SLOGE("Cannot seek to read persistent data on %s", fname);
949             goto err2;
950         }
951         if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
952             SLOGE("Error reading persistent data on iteration %d", i);
953             goto err2;
954         }
955         if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
956             found = 1;
957             break;
958         }
959     }
960
961     if (!found) {
962         SLOGI("Could not find valid persistent data, creating");
963         init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
964     }
965
966     /* Success */
967     persist_data = pdata;
968     close(fd);
969     return 0;
970
971 err2:
972     free(pdata);
973
974 err:
975     close(fd);
976     return -1;
977 }
978
979 static int save_persistent_data(void)
980 {
981     struct crypt_mnt_ftr crypt_ftr;
982     struct crypt_persist_data *pdata;
983     char *fname;
984     off64_t write_offset;
985     off64_t erase_offset;
986     int fd;
987     int ret;
988
989     if (persist_data == NULL) {
990         SLOGE("No persistent data to save");
991         return -1;
992     }
993
994     if(get_crypt_ftr_and_key(&crypt_ftr)) {
995         return -1;
996     }
997
998     if ((crypt_ftr.major_version < 1)
999         || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
1000         SLOGE("Crypt_ftr version doesn't support persistent data");
1001         return -1;
1002     }
1003
1004     ret = validate_persistent_data_storage(&crypt_ftr);
1005     if (ret) {
1006         return -1;
1007     }
1008
1009     if (get_crypt_ftr_info(&fname, NULL)) {
1010         return -1;
1011     }
1012
1013     fd = open(fname, O_RDWR|O_CLOEXEC);
1014     if (fd < 0) {
1015         SLOGE("Cannot open %s metadata file", fname);
1016         return -1;
1017     }
1018
1019     pdata = malloc(crypt_ftr.persist_data_size);
1020     if (pdata == NULL) {
1021         SLOGE("Cannot allocate persistant data");
1022         goto err;
1023     }
1024
1025     if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1026         SLOGE("Cannot seek to read persistent data on %s", fname);
1027         goto err2;
1028     }
1029
1030     if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
1031             SLOGE("Error reading persistent data before save");
1032             goto err2;
1033     }
1034
1035     if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1036         /* The first copy is the curent valid copy, so write to
1037          * the second copy and erase this one */
1038        write_offset = crypt_ftr.persist_data_offset[1];
1039        erase_offset = crypt_ftr.persist_data_offset[0];
1040     } else {
1041         /* The second copy must be the valid copy, so write to
1042          * the first copy, and erase the second */
1043        write_offset = crypt_ftr.persist_data_offset[0];
1044        erase_offset = crypt_ftr.persist_data_offset[1];
1045     }
1046
1047     /* Write the new copy first, if successful, then erase the old copy */
1048     if (lseek64(fd, write_offset, SEEK_SET) < 0) {
1049         SLOGE("Cannot seek to write persistent data");
1050         goto err2;
1051     }
1052     if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1053         (int) crypt_ftr.persist_data_size) {
1054         if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
1055             SLOGE("Cannot seek to erase previous persistent data");
1056             goto err2;
1057         }
1058         fsync(fd);
1059         memset(pdata, 0, crypt_ftr.persist_data_size);
1060         if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
1061             (int) crypt_ftr.persist_data_size) {
1062             SLOGE("Cannot write to erase previous persistent data");
1063             goto err2;
1064         }
1065         fsync(fd);
1066     } else {
1067         SLOGE("Cannot write to save persistent data");
1068         goto err2;
1069     }
1070
1071     /* Success */
1072     free(pdata);
1073     close(fd);
1074     return 0;
1075
1076 err2:
1077     free(pdata);
1078 err:
1079     close(fd);
1080     return -1;
1081 }
1082
1083 /* Convert a binary key of specified length into an ascii hex string equivalent,
1084  * without the leading 0x and with null termination
1085  */
1086 static void convert_key_to_hex_ascii(const unsigned char *master_key,
1087                                      unsigned int keysize, char *master_key_ascii) {
1088     unsigned int i, a;
1089     unsigned char nibble;
1090
1091     for (i=0, a=0; i<keysize; i++, a+=2) {
1092         /* For each byte, write out two ascii hex digits */
1093         nibble = (master_key[i] >> 4) & 0xf;
1094         master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
1095
1096         nibble = master_key[i] & 0xf;
1097         master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1098     }
1099
1100     /* Add the null termination */
1101     master_key_ascii[a] = '\0';
1102
1103 }
1104
1105 static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
1106         const unsigned char *master_key, const char *real_blk_name,
1107         const char *name, int fd, const char *extra_params) {
1108   _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1109   struct dm_ioctl *io;
1110   struct dm_target_spec *tgt;
1111   char *crypt_params;
1112   char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1113   int i;
1114
1115   io = (struct dm_ioctl *) buffer;
1116
1117   /* Load the mapping table for this device */
1118   tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1119
1120   ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1121   io->target_count = 1;
1122   tgt->status = 0;
1123   tgt->sector_start = 0;
1124   tgt->length = crypt_ftr->fs_size;
1125   crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1126
1127 #ifdef CONFIG_HW_DISK_ENCRYPTION
1128   if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1129     strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1130     if (is_ice_enabled())
1131       convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1132     else
1133       convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1134   }
1135   else {
1136     convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1137     strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1138   }
1139 #else
1140   convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1141   strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1142 #endif
1143
1144   snprintf(crypt_params,
1145            sizeof(buffer)-sizeof(struct dm_ioctl)-sizeof(struct dm_target_spec),
1146            "%s %s 0 %s 0 %s 0",
1147            crypt_ftr->crypto_type_name, master_key_ascii,
1148            real_blk_name, extra_params);
1149
1150   SLOGI("target_type = %s", tgt->target_type);
1151   SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1152
1153   crypt_params += strlen(crypt_params) + 1;
1154   crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1155   tgt->next = crypt_params - buffer;
1156
1157   for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1158     if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1159       break;
1160     }
1161     usleep(500000);
1162   }
1163
1164   if (i == TABLE_LOAD_RETRIES) {
1165     /* We failed to load the table, return an error */
1166     return -1;
1167   } else {
1168     return i + 1;
1169   }
1170 }
1171
1172 static int get_dm_crypt_version(int fd, const char *name,  int *version)
1173 {
1174     char buffer[DM_CRYPT_BUF_SIZE];
1175     struct dm_ioctl *io;
1176     struct dm_target_versions *v;
1177
1178     io = (struct dm_ioctl *) buffer;
1179
1180     ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1181
1182     if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1183         return -1;
1184     }
1185
1186     /* Iterate over the returned versions, looking for name of "crypt".
1187      * When found, get and return the version.
1188      */
1189     v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1190     while (v->next) {
1191         if (! strcmp(v->name, "crypt")) {
1192
1193             /* We found the crypt driver, return the version, and get out */
1194             version[0] = v->version[0];
1195             version[1] = v->version[1];
1196             version[2] = v->version[2];
1197             return 0;
1198         }
1199         v = (struct dm_target_versions *)(((char *)v) + v->next);
1200     }
1201
1202     return -1;
1203 }
1204
1205 static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
1206         const unsigned char *master_key, const char *real_blk_name,
1207         char *crypto_blk_name, const char *name) {
1208   char buffer[DM_CRYPT_BUF_SIZE];
1209   struct dm_ioctl *io;
1210   unsigned int minor;
1211   int fd=0;
1212   int retval = -1;
1213   int version[3];
1214   char *extra_params;
1215   int load_count;
1216 #ifdef CONFIG_HW_DISK_ENCRYPTION
1217   char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1218   char progress[PROPERTY_VALUE_MAX] = {0};
1219 #endif
1220
1221   if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
1222     SLOGE("Cannot open device-mapper\n");
1223     goto errout;
1224   }
1225
1226   io = (struct dm_ioctl *) buffer;
1227
1228   ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1229   if (ioctl(fd, DM_DEV_CREATE, io)) {
1230     SLOGE("Cannot create dm-crypt device\n");
1231     goto errout;
1232   }
1233
1234   /* Get the device status, in particular, the name of it's device file */
1235   ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1236   if (ioctl(fd, DM_DEV_STATUS, io)) {
1237     SLOGE("Cannot retrieve dm-crypt device status\n");
1238     goto errout;
1239   }
1240   minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1241   snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1242
1243 #ifdef CONFIG_HW_DISK_ENCRYPTION
1244   if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1245     /* Set fde_enabled if either FDE completed or in-progress */
1246     property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1247     property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1248     if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1249       if (is_ice_enabled())
1250           extra_params = "fde_enabled ice";
1251       else
1252         extra_params = "fde_enabled";
1253     } else
1254       extra_params = "fde_disabled";
1255   } else {
1256     extra_params = "";
1257     if (! get_dm_crypt_version(fd, name, version)) {
1258       /* Support for allow_discards was added in version 1.11.0 */
1259       if ((version[0] >= 2) ||
1260           ((version[0] == 1) && (version[1] >= 11))) {
1261           extra_params = "1 allow_discards";
1262           SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1263       }
1264     }
1265   }
1266 #else
1267   extra_params = "";
1268   if (! get_dm_crypt_version(fd, name, version)) {
1269       /* Support for allow_discards was added in version 1.11.0 */
1270       if ((version[0] >= 2) ||
1271           ((version[0] == 1) && (version[1] >= 11))) {
1272           extra_params = "1 allow_discards";
1273           SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1274       }
1275   }
1276 #endif
1277
1278   load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1279                                          fd, extra_params);
1280   if (load_count < 0) {
1281       SLOGE("Cannot load dm-crypt mapping table.\n");
1282       goto errout;
1283   } else if (load_count > 1) {
1284       SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1285   }
1286
1287   /* Resume this device to activate it */
1288   ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1289
1290   if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1291     SLOGE("Cannot resume the dm-crypt device\n");
1292     goto errout;
1293   }
1294
1295   /* We made it here with no errors.  Woot! */
1296   retval = 0;
1297
1298 errout:
1299   close(fd);   /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1300
1301   return retval;
1302 }
1303
1304 static int delete_crypto_blk_dev(char *name)
1305 {
1306   int fd;
1307   char buffer[DM_CRYPT_BUF_SIZE];
1308   struct dm_ioctl *io;
1309   int retval = -1;
1310
1311   if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
1312     SLOGE("Cannot open device-mapper\n");
1313     goto errout;
1314   }
1315
1316   io = (struct dm_ioctl *) buffer;
1317
1318   ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1319   if (ioctl(fd, DM_DEV_REMOVE, io)) {
1320     SLOGE("Cannot remove dm-crypt device\n");
1321     goto errout;
1322   }
1323
1324   /* We made it here with no errors.  Woot! */
1325   retval = 0;
1326
1327 errout:
1328   close(fd);    /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1329
1330   return retval;
1331
1332 }
1333
1334 static int pbkdf2(const char *passwd, const unsigned char *salt,
1335                   unsigned char *ikey, void *params UNUSED)
1336 {
1337     SLOGI("Using pbkdf2 for cryptfs KDF");
1338
1339     /* Turn the password into a key and IV that can decrypt the master key */
1340     PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd),
1341                            salt, SALT_LEN,
1342                            HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
1343
1344     return 0;
1345 }
1346
1347 static int scrypt(const char *passwd, const unsigned char *salt,
1348                   unsigned char *ikey, void *params)
1349 {
1350     SLOGI("Using scrypt for cryptfs KDF");
1351
1352     struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1353
1354     int N = 1 << ftr->N_factor;
1355     int r = 1 << ftr->r_factor;
1356     int p = 1 << ftr->p_factor;
1357
1358     /* Turn the password into a key and IV that can decrypt the master key */
1359     unsigned int keysize;
1360     crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1361                   salt, SALT_LEN, N, r, p, ikey,
1362                   KEY_LEN_BYTES + IV_LEN_BYTES);
1363
1364    return 0;
1365 }
1366
1367 static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1368                             unsigned char *ikey, void *params)
1369 {
1370     SLOGI("Using scrypt with keymaster for cryptfs KDF");
1371
1372     int rc;
1373     size_t signature_size;
1374     unsigned char* signature;
1375     struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1376
1377     int N = 1 << ftr->N_factor;
1378     int r = 1 << ftr->r_factor;
1379     int p = 1 << ftr->p_factor;
1380
1381     rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1382                        salt, SALT_LEN, N, r, p, ikey,
1383                        KEY_LEN_BYTES + IV_LEN_BYTES);
1384
1385     if (rc) {
1386         SLOGE("scrypt failed");
1387         return -1;
1388     }
1389
1390     if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1391                               &signature, &signature_size)) {
1392         SLOGE("Signing failed");
1393         return -1;
1394     }
1395
1396     rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1397                        N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1398     free(signature);
1399
1400     if (rc) {
1401         SLOGE("scrypt failed");
1402         return -1;
1403     }
1404
1405     return 0;
1406 }
1407
1408 static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1409                               const unsigned char *decrypted_master_key,
1410                               unsigned char *encrypted_master_key,
1411                               struct crypt_mnt_ftr *crypt_ftr,
1412                               bool create_keymaster_key)
1413 {
1414     unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1415     EVP_CIPHER_CTX e_ctx;
1416     int encrypted_len, final_len;
1417     int rc = 0;
1418
1419     /* Turn the password into an intermediate key and IV that can decrypt the master key */
1420     get_device_scrypt_params(crypt_ftr);
1421
1422     switch (crypt_ftr->kdf_type) {
1423     case KDF_SCRYPT_KEYMASTER:
1424         if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
1425             SLOGE("keymaster_create_key failed");
1426             return -1;
1427         }
1428
1429         if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1430             SLOGE("scrypt failed");
1431             return -1;
1432         }
1433         break;
1434
1435     case KDF_SCRYPT:
1436         if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1437             SLOGE("scrypt failed");
1438             return -1;
1439         }
1440         break;
1441
1442     default:
1443         SLOGE("Invalid kdf_type");
1444         return -1;
1445     }
1446
1447     /* Initialize the decryption engine */
1448     EVP_CIPHER_CTX_init(&e_ctx);
1449     if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
1450         SLOGE("EVP_EncryptInit failed\n");
1451         return -1;
1452     }
1453     EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
1454
1455     /* Encrypt the master key */
1456     if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1457                             decrypted_master_key, KEY_LEN_BYTES)) {
1458         SLOGE("EVP_EncryptUpdate failed\n");
1459         return -1;
1460     }
1461     if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
1462         SLOGE("EVP_EncryptFinal failed\n");
1463         return -1;
1464     }
1465
1466     if (encrypted_len + final_len != KEY_LEN_BYTES) {
1467         SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1468         return -1;
1469     }
1470
1471     /* Store the scrypt of the intermediate key, so we can validate if it's a
1472        password error or mount error when things go wrong.
1473        Note there's no need to check for errors, since if this is incorrect, we
1474        simply won't wipe userdata, which is the correct default behavior
1475     */
1476     int N = 1 << crypt_ftr->N_factor;
1477     int r = 1 << crypt_ftr->r_factor;
1478     int p = 1 << crypt_ftr->p_factor;
1479
1480     rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1481                        crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1482                        crypt_ftr->scrypted_intermediate_key,
1483                        sizeof(crypt_ftr->scrypted_intermediate_key));
1484
1485     if (rc) {
1486       SLOGE("encrypt_master_key: crypto_scrypt failed");
1487     }
1488
1489     return 0;
1490 }
1491
1492 static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
1493                                   unsigned char *encrypted_master_key,
1494                                   unsigned char *decrypted_master_key,
1495                                   kdf_func kdf, void *kdf_params,
1496                                   unsigned char** intermediate_key,
1497                                   size_t* intermediate_key_size)
1498 {
1499   unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1500   EVP_CIPHER_CTX d_ctx;
1501   int decrypted_len, final_len;
1502
1503   /* Turn the password into an intermediate key and IV that can decrypt the
1504      master key */
1505   if (kdf(passwd, salt, ikey, kdf_params)) {
1506     SLOGE("kdf failed");
1507     return -1;
1508   }
1509
1510   /* Initialize the decryption engine */
1511   EVP_CIPHER_CTX_init(&d_ctx);
1512   if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
1513     return -1;
1514   }
1515   EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1516   /* Decrypt the master key */
1517   if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1518                             encrypted_master_key, KEY_LEN_BYTES)) {
1519     return -1;
1520   }
1521   if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1522     return -1;
1523   }
1524
1525   if (decrypted_len + final_len != KEY_LEN_BYTES) {
1526     return -1;
1527   }
1528
1529   /* Copy intermediate key if needed by params */
1530   if (intermediate_key && intermediate_key_size) {
1531     *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1532     if (intermediate_key) {
1533       memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1534       *intermediate_key_size = KEY_LEN_BYTES;
1535     }
1536   }
1537
1538   return 0;
1539 }
1540
1541 static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
1542 {
1543     if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1544         *kdf = scrypt_keymaster;
1545         *kdf_params = ftr;
1546     } else if (ftr->kdf_type == KDF_SCRYPT) {
1547         *kdf = scrypt;
1548         *kdf_params = ftr;
1549     } else {
1550         *kdf = pbkdf2;
1551         *kdf_params = NULL;
1552     }
1553 }
1554
1555 static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
1556                               struct crypt_mnt_ftr *crypt_ftr,
1557                               unsigned char** intermediate_key,
1558                               size_t* intermediate_key_size)
1559 {
1560     kdf_func kdf;
1561     void *kdf_params;
1562     int ret;
1563
1564     get_kdf_func(crypt_ftr, &kdf, &kdf_params);
1565     ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1566                                  decrypted_master_key, kdf, kdf_params,
1567                                  intermediate_key, intermediate_key_size);
1568     if (ret != 0) {
1569         SLOGW("failure decrypting master key");
1570     }
1571
1572     return ret;
1573 }
1574
1575 static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1576         struct crypt_mnt_ftr *crypt_ftr) {
1577     int fd;
1578     unsigned char key_buf[KEY_LEN_BYTES];
1579
1580     /* Get some random bits for a key */
1581     fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
1582     read(fd, key_buf, sizeof(key_buf));
1583     read(fd, salt, SALT_LEN);
1584     close(fd);
1585
1586     /* Now encrypt it with the password */
1587     return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
1588 }
1589
1590 int wait_and_unmount(const char *mountpoint, bool kill)
1591 {
1592     int i, err, rc;
1593 #define WAIT_UNMOUNT_COUNT 20
1594
1595     /*  Now umount the tmpfs filesystem */
1596     for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1597         if (umount(mountpoint) == 0) {
1598             break;
1599         }
1600
1601         if (errno == EINVAL) {
1602             /* EINVAL is returned if the directory is not a mountpoint,
1603              * i.e. there is no filesystem mounted there.  So just get out.
1604              */
1605             break;
1606         }
1607
1608         err = errno;
1609
1610         /* If allowed, be increasingly aggressive before the last two retries */
1611         if (kill) {
1612             if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1613                 SLOGW("sending SIGHUP to processes with open files\n");
1614                 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
1615             } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1616                 SLOGW("sending SIGKILL to processes with open files\n");
1617                 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
1618             }
1619         }
1620
1621         sleep(1);
1622     }
1623
1624     if (i < WAIT_UNMOUNT_COUNT) {
1625       SLOGD("unmounting %s succeeded\n", mountpoint);
1626       rc = 0;
1627     } else {
1628       vold_killProcessesWithOpenFiles(mountpoint, 0);
1629       SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1630       rc = -1;
1631     }
1632
1633     return rc;
1634 }
1635
1636 #define DATA_PREP_TIMEOUT 1000
1637 static int prep_data_fs(void)
1638 {
1639     int i;
1640
1641     /* Do the prep of the /data filesystem */
1642     property_set("vold.post_fs_data_done", "0");
1643     property_set("vold.decrypt", "trigger_post_fs_data");
1644     SLOGD("Just triggered post_fs_data\n");
1645
1646     /* Wait a max of 50 seconds, hopefully it takes much less */
1647     for (i=0; i<DATA_PREP_TIMEOUT; i++) {
1648         char p[PROPERTY_VALUE_MAX];
1649
1650         property_get("vold.post_fs_data_done", p, "0");
1651         if (*p == '1') {
1652             break;
1653         } else {
1654             usleep(50000);
1655         }
1656     }
1657     if (i == DATA_PREP_TIMEOUT) {
1658         /* Ugh, we failed to prep /data in time.  Bail. */
1659         SLOGE("post_fs_data timed out!\n");
1660         return -1;
1661     } else {
1662         SLOGD("post_fs_data done\n");
1663         return 0;
1664     }
1665 }
1666
1667 static void cryptfs_set_corrupt()
1668 {
1669     // Mark the footer as bad
1670     struct crypt_mnt_ftr crypt_ftr;
1671     if (get_crypt_ftr_and_key(&crypt_ftr)) {
1672         SLOGE("Failed to get crypto footer - panic");
1673         return;
1674     }
1675
1676     crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1677     if (put_crypt_ftr_and_key(&crypt_ftr)) {
1678         SLOGE("Failed to set crypto footer - panic");
1679         return;
1680     }
1681 }
1682
1683 static void cryptfs_trigger_restart_min_framework()
1684 {
1685     if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1686       SLOGE("Failed to mount tmpfs on data - panic");
1687       return;
1688     }
1689
1690     if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1691         SLOGE("Failed to trigger post fs data - panic");
1692         return;
1693     }
1694
1695     if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1696         SLOGE("Failed to trigger restart min framework - panic");
1697         return;
1698     }
1699 }
1700
1701 /* returns < 0 on failure */
1702 static int cryptfs_restart_internal(int restart_main)
1703 {
1704     char crypto_blkdev[MAXPATHLEN];
1705     int rc = -1;
1706     static int restart_successful = 0;
1707
1708     /* Validate that it's OK to call this routine */
1709     if (! master_key_saved) {
1710         SLOGE("Encrypted filesystem not validated, aborting");
1711         return -1;
1712     }
1713
1714     if (restart_successful) {
1715         SLOGE("System already restarted with encrypted disk, aborting");
1716         return -1;
1717     }
1718
1719     if (restart_main) {
1720         /* Here is where we shut down the framework.  The init scripts
1721          * start all services in one of three classes: core, main or late_start.
1722          * On boot, we start core and main.  Now, we stop main, but not core,
1723          * as core includes vold and a few other really important things that
1724          * we need to keep running.  Once main has stopped, we should be able
1725          * to umount the tmpfs /data, then mount the encrypted /data.
1726          * We then restart the class main, and also the class late_start.
1727          * At the moment, I've only put a few things in late_start that I know
1728          * are not needed to bring up the framework, and that also cause problems
1729          * with unmounting the tmpfs /data, but I hope to add add more services
1730          * to the late_start class as we optimize this to decrease the delay
1731          * till the user is asked for the password to the filesystem.
1732          */
1733
1734         /* The init files are setup to stop the class main when vold.decrypt is
1735          * set to trigger_reset_main.
1736          */
1737         property_set("vold.decrypt", "trigger_reset_main");
1738         SLOGD("Just asked init to shut down class main\n");
1739
1740         /* Ugh, shutting down the framework is not synchronous, so until it
1741          * can be fixed, this horrible hack will wait a moment for it all to
1742          * shut down before proceeding.  Without it, some devices cannot
1743          * restart the graphics services.
1744          */
1745         sleep(2);
1746     }
1747
1748     /* Now that the framework is shutdown, we should be able to umount()
1749      * the tmpfs filesystem, and mount the real one.
1750      */
1751
1752     property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1753     if (strlen(crypto_blkdev) == 0) {
1754         SLOGE("fs_crypto_blkdev not set\n");
1755         return -1;
1756     }
1757
1758     if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
1759         /* If ro.crypto.readonly is set to 1, mount the decrypted
1760          * filesystem readonly.  This is used when /data is mounted by
1761          * recovery mode.
1762          */
1763         char ro_prop[PROPERTY_VALUE_MAX];
1764         property_get("ro.crypto.readonly", ro_prop, "");
1765         if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1766             struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1767             rec->flags |= MS_RDONLY;
1768         }
1769
1770         /* If that succeeded, then mount the decrypted filesystem */
1771         int retries = RETRY_MOUNT_ATTEMPTS;
1772         int mount_rc;
1773         while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1774                                            crypto_blkdev, 0))
1775                != 0) {
1776             if (mount_rc == FS_MGR_DOMNT_BUSY) {
1777                 /* TODO: invoke something similar to
1778                    Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1779                                    retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1780                 SLOGI("Failed to mount %s because it is busy - waiting",
1781                       crypto_blkdev);
1782                 if (--retries) {
1783                     sleep(RETRY_MOUNT_DELAY_SECONDS);
1784                 } else {
1785                     /* Let's hope that a reboot clears away whatever is keeping
1786                        the mount busy */
1787                     cryptfs_reboot(reboot);
1788                 }
1789             } else {
1790                 SLOGE("Failed to mount decrypted data");
1791                 cryptfs_set_corrupt();
1792                 cryptfs_trigger_restart_min_framework();
1793                 SLOGI("Started framework to offer wipe");
1794                 return -1;
1795             }
1796         }
1797
1798         property_set("vold.decrypt", "trigger_load_persist_props");
1799         /* Create necessary paths on /data */
1800         if (prep_data_fs()) {
1801             return -1;
1802         }
1803
1804         /* startup service classes main and late_start */
1805         property_set("vold.decrypt", "trigger_restart_framework");
1806         SLOGD("Just triggered restart_framework\n");
1807
1808         /* Give it a few moments to get started */
1809         sleep(1);
1810     }
1811
1812     if (rc == 0) {
1813         restart_successful = 1;
1814     }
1815
1816     return rc;
1817 }
1818
1819 int cryptfs_restart(void)
1820 {
1821     SLOGI("cryptfs_restart");
1822     if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
1823         struct fstab_rec* rec;
1824         int rc;
1825
1826         if (e4crypt_restart(DATA_MNT_POINT)) {
1827             SLOGE("Can't unmount e4crypt temp volume\n");
1828             return -1;
1829         }
1830
1831         rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1832         if (!rec) {
1833             SLOGE("Can't get fstab record for %s\n", DATA_MNT_POINT);
1834             return -1;
1835         }
1836
1837         rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, rec->blk_device, 0);
1838         if (rc) {
1839             SLOGE("Can't mount %s\n", DATA_MNT_POINT);
1840             return rc;
1841         }
1842
1843         property_set("vold.decrypt", "trigger_restart_framework");
1844         return 0;
1845     }
1846
1847     /* Call internal implementation forcing a restart of main service group */
1848     return cryptfs_restart_internal(1);
1849 }
1850
1851 static int do_crypto_complete(char *mount_point)
1852 {
1853   struct crypt_mnt_ftr crypt_ftr;
1854   char encrypted_state[PROPERTY_VALUE_MAX];
1855   char key_loc[PROPERTY_VALUE_MAX];
1856
1857   property_get("ro.crypto.state", encrypted_state, "");
1858   if (strcmp(encrypted_state, "encrypted") ) {
1859     SLOGE("not running with encryption, aborting");
1860     return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1861   }
1862
1863   if (e4crypt_crypto_complete(mount_point) == 0) {
1864     return CRYPTO_COMPLETE_ENCRYPTED;
1865   }
1866
1867   if (get_crypt_ftr_and_key(&crypt_ftr)) {
1868     fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
1869
1870     /*
1871      * Only report this error if key_loc is a file and it exists.
1872      * If the device was never encrypted, and /data is not mountable for
1873      * some reason, returning 1 should prevent the UI from presenting the
1874      * a "enter password" screen, or worse, a "press button to wipe the
1875      * device" screen.
1876      */
1877     if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1878       SLOGE("master key file does not exist, aborting");
1879       return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1880     } else {
1881       SLOGE("Error getting crypt footer and key\n");
1882       return CRYPTO_COMPLETE_BAD_METADATA;
1883     }
1884   }
1885
1886   // Test for possible error flags
1887   if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1888     SLOGE("Encryption process is partway completed\n");
1889     return CRYPTO_COMPLETE_PARTIAL;
1890   }
1891
1892   if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1893     SLOGE("Encryption process was interrupted but cannot continue\n");
1894     return CRYPTO_COMPLETE_INCONSISTENT;
1895   }
1896
1897   if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1898     SLOGE("Encryption is successful but data is corrupt\n");
1899     return CRYPTO_COMPLETE_CORRUPT;
1900   }
1901
1902   /* We passed the test! We shall diminish, and return to the west */
1903   return CRYPTO_COMPLETE_ENCRYPTED;
1904 }
1905
1906 static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1907                                    char *passwd, char *mount_point, char *label)
1908 {
1909   /* Allocate enough space for a 256 bit key, but we may use less */
1910   unsigned char decrypted_master_key[32];
1911   char crypto_blkdev[MAXPATHLEN];
1912   char real_blkdev[MAXPATHLEN];
1913   char tmp_mount_point[64];
1914   unsigned int orig_failed_decrypt_count;
1915   int rc;
1916   int use_keymaster = 0;
1917   int upgrade = 0;
1918   unsigned char* intermediate_key = 0;
1919   size_t intermediate_key_size = 0;
1920
1921   SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1922   orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
1923
1924   if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1925     if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1926                            &intermediate_key, &intermediate_key_size)) {
1927       SLOGE("Failed to decrypt master key\n");
1928       rc = -1;
1929       goto errout;
1930     }
1931   }
1932
1933   fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1934
1935 #ifdef CONFIG_HW_DISK_ENCRYPTION
1936   int key_index = 0;
1937   unsigned char newpw[32];
1938   if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1939     if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
1940       key_index = set_hw_device_encryption_key(passwd,
1941                                 (char*) crypt_ftr->crypto_type_name);
1942     else
1943       key_index = set_hw_device_encryption_key((const char*)newpw,
1944                                 (char*) crypt_ftr->crypto_type_name);
1945     if (key_index < 0) {
1946       rc = ++crypt_ftr->failed_decrypt_count;
1947       put_crypt_ftr_and_key(crypt_ftr);
1948       goto errout;
1949     }
1950     else {
1951       if (is_ice_enabled()) {
1952         if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
1953                             real_blkdev, crypto_blkdev, label)) {
1954           SLOGE("Error creating decrypted block device");
1955           rc = -1;
1956           goto errout;
1957         }
1958       } else {
1959         if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1960                             real_blkdev, crypto_blkdev, label)) {
1961           SLOGE("Error creating decrypted block device");
1962           rc = -1;
1963           goto errout;
1964         }
1965       }
1966     }
1967   } else {
1968     /* in case HW FDE is delivered through OTA  and device is already encrypted
1969      * using SW FDE, we should let user continue using SW FDE until userdata is
1970      * wiped.
1971      */
1972     if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1973                             real_blkdev, crypto_blkdev, label)) {
1974       SLOGE("Error creating decrypted block device");
1975       rc = -1;
1976       goto errout;
1977     }
1978   }
1979 #else
1980   // Create crypto block device - all (non fatal) code paths
1981   // need it
1982   if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1983                             real_blkdev, crypto_blkdev, label)) {
1984      SLOGE("Error creating decrypted block device\n");
1985      rc = -1;
1986      goto errout;
1987   }
1988 #endif
1989
1990   /* Work out if the problem is the password or the data */
1991   unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1992                                                  scrypted_intermediate_key)];
1993   int N = 1 << crypt_ftr->N_factor;
1994   int r = 1 << crypt_ftr->r_factor;
1995   int p = 1 << crypt_ftr->p_factor;
1996
1997   rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1998                      crypt_ftr->salt, sizeof(crypt_ftr->salt),
1999                      N, r, p, scrypted_intermediate_key,
2000                      sizeof(scrypted_intermediate_key));
2001
2002   // Does the key match the crypto footer?
2003   if (rc == 0 && memcmp(scrypted_intermediate_key,
2004                         crypt_ftr->scrypted_intermediate_key,
2005                         sizeof(scrypted_intermediate_key)) == 0) {
2006     SLOGI("Password matches");
2007     rc = 0;
2008   } else {
2009     /* Try mounting the file system anyway, just in case the problem's with
2010      * the footer, not the key. */
2011     sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
2012     mkdir(tmp_mount_point, 0755);
2013     if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
2014       SLOGE("Error temp mounting decrypted block device\n");
2015       delete_crypto_blk_dev(label);
2016
2017       rc = ++crypt_ftr->failed_decrypt_count;
2018       put_crypt_ftr_and_key(crypt_ftr);
2019     } else {
2020       /* Success! */
2021       SLOGI("Password did not match but decrypted drive mounted - continue");
2022       umount(tmp_mount_point);
2023       rc = 0;
2024     }
2025   }
2026
2027   if (rc == 0) {
2028     crypt_ftr->failed_decrypt_count = 0;
2029     if (orig_failed_decrypt_count != 0) {
2030       put_crypt_ftr_and_key(crypt_ftr);
2031     }
2032
2033     /* Save the name of the crypto block device
2034      * so we can mount it when restarting the framework. */
2035     property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2036
2037     /* Also save a the master key so we can reencrypted the key
2038      * the key when we want to change the password on it. */
2039     memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
2040     saved_mount_point = strdup(mount_point);
2041     master_key_saved = 1;
2042     SLOGD("%s(): Master key saved\n", __FUNCTION__);
2043     rc = 0;
2044
2045     // Upgrade if we're not using the latest KDF.
2046     use_keymaster = keymaster_check_compatibility();
2047     if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2048         // Don't allow downgrade
2049     } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2050         crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2051         upgrade = 1;
2052     } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2053         crypt_ftr->kdf_type = KDF_SCRYPT;
2054         upgrade = 1;
2055     }
2056
2057     if (upgrade) {
2058         rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
2059                                 crypt_ftr->master_key, crypt_ftr, true);
2060         if (!rc) {
2061             rc = put_crypt_ftr_and_key(crypt_ftr);
2062         }
2063         SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2064
2065         // Do not fail even if upgrade failed - machine is bootable
2066         // Note that if this code is ever hit, there is a *serious* problem
2067         // since KDFs should never fail. You *must* fix the kdf before
2068         // proceeding!
2069         if (rc) {
2070           SLOGW("Upgrade failed with error %d,"
2071                 " but continuing with previous state",
2072                 rc);
2073           rc = 0;
2074         }
2075     }
2076   }
2077
2078  errout:
2079   if (intermediate_key) {
2080     memset(intermediate_key, 0, intermediate_key_size);
2081     free(intermediate_key);
2082   }
2083   return rc;
2084 }
2085
2086 /*
2087  * Called by vold when it's asked to mount an encrypted external
2088  * storage volume. The incoming partition has no crypto header/footer,
2089  * as any metadata is been stored in a separate, small partition.
2090  *
2091  * out_crypto_blkdev must be MAXPATHLEN.
2092  */
2093 int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
2094         const unsigned char* key, int keysize, char* out_crypto_blkdev) {
2095     int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
2096     if (fd == -1) {
2097         SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
2098         return -1;
2099     }
2100
2101     unsigned long nr_sec = 0;
2102     get_blkdev_size(fd, &nr_sec);
2103     close(fd);
2104
2105     if (nr_sec == 0) {
2106         SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
2107         return -1;
2108     }
2109
2110     struct crypt_mnt_ftr ext_crypt_ftr;
2111     memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2112     ext_crypt_ftr.fs_size = nr_sec;
2113     ext_crypt_ftr.keysize = keysize;
2114     strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
2115
2116     return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
2117             out_crypto_blkdev, label);
2118 }
2119
2120 /*
2121  * Called by vold when it's asked to unmount an encrypted external
2122  * storage volume.
2123  */
2124 int cryptfs_revert_ext_volume(const char* label) {
2125     return delete_crypto_blk_dev((char*) label);
2126 }
2127
2128 int cryptfs_crypto_complete(void)
2129 {
2130   int mdtp_activated = fs_mgr_is_mdtp_activated();
2131   int crypto_state = do_crypto_complete("/data");
2132
2133   /* if MDTP is activated, it should be reflected in the crypto state */
2134   if(mdtp_activated){
2135     if (crypto_state != CRYPTO_COMPLETE_ENCRYPTED ){
2136       /* MDTP is activated and crypto state is bad */
2137       return CRYPTO_COMPLETE_ERROR_MDTP_ACTIVATED;
2138     } else {
2139       /* MDTP is activated and crypto state is ok */
2140       return CRYPTO_COMPLETE_ENCRYPTED_MDTP_ACTIVATED;
2141     }
2142   }
2143
2144   /* mdtp is not activated, return the crypto state only */
2145   return crypto_state;
2146 }
2147
2148 int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2149 {
2150     char encrypted_state[PROPERTY_VALUE_MAX];
2151     property_get("ro.crypto.state", encrypted_state, "");
2152     if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2153         SLOGE("encrypted fs already validated or not running with encryption,"
2154               " aborting");
2155         return -1;
2156     }
2157
2158     if (get_crypt_ftr_and_key(crypt_ftr)) {
2159         SLOGE("Error getting crypt footer and key");
2160         return -1;
2161     }
2162
2163     return 0;
2164 }
2165
2166 int cryptfs_check_passwd(char *passwd)
2167 {
2168     SLOGI("cryptfs_check_passwd");
2169     if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
2170         return e4crypt_check_passwd(DATA_MNT_POINT, passwd);
2171     }
2172
2173     struct crypt_mnt_ftr crypt_ftr;
2174     int rc;
2175
2176     rc = check_unmounted_and_get_ftr(&crypt_ftr);
2177     if (rc)
2178         return rc;
2179
2180     rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2181                                  DATA_MNT_POINT, "userdata");
2182
2183     if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2184         cryptfs_clear_password();
2185         password = strdup(passwd);
2186         struct timespec now;
2187         clock_gettime(CLOCK_BOOTTIME, &now);
2188         password_expiry_time = now.tv_sec + password_max_age_seconds;
2189     }
2190
2191     return rc;
2192 }
2193
2194 int cryptfs_verify_passwd(char *passwd)
2195 {
2196     struct crypt_mnt_ftr crypt_ftr;
2197     /* Allocate enough space for a 256 bit key, but we may use less */
2198     unsigned char decrypted_master_key[32];
2199     char encrypted_state[PROPERTY_VALUE_MAX];
2200     int rc;
2201
2202     property_get("ro.crypto.state", encrypted_state, "");
2203     if (strcmp(encrypted_state, "encrypted") ) {
2204         SLOGE("device not encrypted, aborting");
2205         return -2;
2206     }
2207
2208     if (!master_key_saved) {
2209         SLOGE("encrypted fs not yet mounted, aborting");
2210         return -1;
2211     }
2212
2213     if (!saved_mount_point) {
2214         SLOGE("encrypted fs failed to save mount point, aborting");
2215         return -1;
2216     }
2217
2218     if (get_crypt_ftr_and_key(&crypt_ftr)) {
2219         SLOGE("Error getting crypt footer and key\n");
2220         return -1;
2221     }
2222
2223     if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2224         /* If the device has no password, then just say the password is valid */
2225         rc = 0;
2226     } else {
2227         decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2228         if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2229             /* They match, the password is correct */
2230             rc = 0;
2231         } else {
2232             /* If incorrect, sleep for a bit to prevent dictionary attacks */
2233             sleep(1);
2234             rc = 1;
2235         }
2236     }
2237
2238     return rc;
2239 }
2240
2241 /* Initialize a crypt_mnt_ftr structure.  The keysize is
2242  * defaulted to 16 bytes, and the filesystem size to 0.
2243  * Presumably, at a minimum, the caller will update the
2244  * filesystem size and crypto_type_name after calling this function.
2245  */
2246 static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
2247 {
2248     off64_t off;
2249
2250     memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
2251     ftr->magic = CRYPT_MNT_MAGIC;
2252     ftr->major_version = CURRENT_MAJOR_VERSION;
2253     ftr->minor_version = CURRENT_MINOR_VERSION;
2254     ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
2255     ftr->keysize = KEY_LEN_BYTES;
2256
2257     switch (keymaster_check_compatibility()) {
2258     case 1:
2259         ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2260         break;
2261
2262     case 0:
2263         ftr->kdf_type = KDF_SCRYPT;
2264         break;
2265
2266     default:
2267         SLOGE("keymaster_check_compatibility failed");
2268         return -1;
2269     }
2270
2271     get_device_scrypt_params(ftr);
2272
2273     ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2274     if (get_crypt_ftr_info(NULL, &off) == 0) {
2275         ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2276         ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2277                                     ftr->persist_data_size;
2278     }
2279
2280     return 0;
2281 }
2282
2283 static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
2284 {
2285     const char *args[10];
2286     char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2287     int num_args;
2288     int status;
2289     int tmp;
2290     int rc = -1;
2291
2292     if (type == EXT4_FS) {
2293         args[0] = "/system/bin/make_ext4fs";
2294         args[1] = "-a";
2295         args[2] = "/data";
2296         args[3] = "-l";
2297         snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
2298         args[4] = size_str;
2299         args[5] = crypto_blkdev;
2300         num_args = 6;
2301         SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2302               args[0], args[1], args[2], args[3], args[4], args[5]);
2303     } else if (type == F2FS_FS) {
2304         args[0] = "/system/bin/mkfs.f2fs";
2305         args[1] = "-t";
2306         args[2] = "-d1";
2307         args[3] = crypto_blkdev;
2308         snprintf(size_str, sizeof(size_str), "%" PRId64, size);
2309         args[4] = size_str;
2310         num_args = 5;
2311         SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2312               args[0], args[1], args[2], args[3], args[4]);
2313     } else {
2314         SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2315         return -1;
2316     }
2317
2318     tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2319
2320     if (tmp != 0) {
2321       SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
2322     } else {
2323         if (WIFEXITED(status)) {
2324             if (WEXITSTATUS(status)) {
2325                 SLOGE("Error creating filesystem on %s, exit status %d ",
2326                       crypto_blkdev, WEXITSTATUS(status));
2327             } else {
2328                 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2329                 rc = 0;
2330             }
2331         } else {
2332             SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2333        }
2334     }
2335
2336     return rc;
2337 }
2338
2339 #define CRYPT_INPLACE_BUFSIZE 4096
2340 #define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2341 #define CRYPT_SECTOR_SIZE 512
2342
2343 /* aligned 32K writes tends to make flash happy.
2344  * SD card association recommends it.
2345  */
2346 #ifndef CONFIG_HW_DISK_ENCRYPTION
2347 #define BLOCKS_AT_A_TIME 8
2348 #else
2349 #define BLOCKS_AT_A_TIME 1024
2350 #endif
2351
2352 struct encryptGroupsData
2353 {
2354     int realfd;
2355     int cryptofd;
2356     off64_t numblocks;
2357     off64_t one_pct, cur_pct, new_pct;
2358     off64_t blocks_already_done, tot_numblocks;
2359     off64_t used_blocks_already_done, tot_used_blocks;
2360     char* real_blkdev, * crypto_blkdev;
2361     int count;
2362     off64_t offset;
2363     char* buffer;
2364     off64_t last_written_sector;
2365     int completed;
2366     time_t time_started;
2367     int remaining_time;
2368 };
2369
2370 static void update_progress(struct encryptGroupsData* data, int is_used)
2371 {
2372     data->blocks_already_done++;
2373
2374     if (is_used) {
2375         data->used_blocks_already_done++;
2376     }
2377     if (data->tot_used_blocks) {
2378         data->new_pct = data->used_blocks_already_done / data->one_pct;
2379     } else {
2380         data->new_pct = data->blocks_already_done / data->one_pct;
2381     }
2382
2383     if (data->new_pct > data->cur_pct) {
2384         char buf[8];
2385         data->cur_pct = data->new_pct;
2386         snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
2387         property_set("vold.encrypt_progress", buf);
2388     }
2389
2390     if (data->cur_pct >= 5) {
2391         struct timespec time_now;
2392         if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2393             SLOGW("Error getting time");
2394         } else {
2395             double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2396             off64_t remaining_blocks = data->tot_used_blocks
2397                                        - data->used_blocks_already_done;
2398             int remaining_time = (int)(elapsed_time * remaining_blocks
2399                                        / data->used_blocks_already_done);
2400
2401             // Change time only if not yet set, lower, or a lot higher for
2402             // best user experience
2403             if (data->remaining_time == -1
2404                 || remaining_time < data->remaining_time
2405                 || remaining_time > data->remaining_time + 60) {
2406                 char buf[8];
2407                 snprintf(buf, sizeof(buf), "%d", remaining_time);
2408                 property_set("vold.encrypt_time_remaining", buf);
2409                 data->remaining_time = remaining_time;
2410             }
2411         }
2412     }
2413 }
2414
2415 static void log_progress(struct encryptGroupsData const* data, bool completed)
2416 {
2417     // Precondition - if completed data = 0 else data != 0
2418
2419     // Track progress so we can skip logging blocks
2420     static off64_t offset = -1;
2421
2422     // Need to close existing 'Encrypting from' log?
2423     if (completed || (offset != -1 && data->offset != offset)) {
2424         SLOGI("Encrypted to sector %" PRId64,
2425               offset / info.block_size * CRYPT_SECTOR_SIZE);
2426         offset = -1;
2427     }
2428
2429     // Need to start new 'Encrypting from' log?
2430     if (!completed && offset != data->offset) {
2431         SLOGI("Encrypting from sector %" PRId64,
2432               data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2433     }
2434
2435     // Update offset
2436     if (!completed) {
2437         offset = data->offset + (off64_t)data->count * info.block_size;
2438     }
2439 }
2440
2441 static int flush_outstanding_data(struct encryptGroupsData* data)
2442 {
2443     if (data->count == 0) {
2444         return 0;
2445     }
2446
2447     SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
2448
2449     if (pread64(data->realfd, data->buffer,
2450                 info.block_size * data->count, data->offset)
2451         <= 0) {
2452         SLOGE("Error reading real_blkdev %s for inplace encrypt",
2453               data->real_blkdev);
2454         return -1;
2455     }
2456
2457     if (pwrite64(data->cryptofd, data->buffer,
2458                  info.block_size * data->count, data->offset)
2459         <= 0) {
2460         SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2461               data->crypto_blkdev);
2462         return -1;
2463     } else {
2464       log_progress(data, false);
2465     }
2466
2467     data->count = 0;
2468     data->last_written_sector = (data->offset + data->count)
2469                                 / info.block_size * CRYPT_SECTOR_SIZE - 1;
2470     return 0;
2471 }
2472
2473 static int encrypt_groups(struct encryptGroupsData* data)
2474 {
2475     unsigned int i;
2476     u8 *block_bitmap = 0;
2477     unsigned int block;
2478     off64_t ret;
2479     int rc = -1;
2480
2481     data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2482     if (!data->buffer) {
2483         SLOGE("Failed to allocate crypto buffer");
2484         goto errout;
2485     }
2486
2487     block_bitmap = malloc(info.block_size);
2488     if (!block_bitmap) {
2489         SLOGE("failed to allocate block bitmap");
2490         goto errout;
2491     }
2492
2493     for (i = 0; i < aux_info.groups; ++i) {
2494         SLOGI("Encrypting group %d", i);
2495
2496         u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2497         u32 block_count = min(info.blocks_per_group,
2498                              aux_info.len_blocks - first_block);
2499
2500         off64_t offset = (u64)info.block_size
2501                          * aux_info.bg_desc[i].bg_block_bitmap;
2502
2503         ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2504         if (ret != (int)info.block_size) {
2505             SLOGE("failed to read all of block group bitmap %d", i);
2506             goto errout;
2507         }
2508
2509         offset = (u64)info.block_size * first_block;
2510
2511         data->count = 0;
2512
2513         for (block = 0; block < block_count; block++) {
2514             int used = bitmap_get_bit(block_bitmap, block);
2515             update_progress(data, used);
2516             if (used) {
2517                 if (data->count == 0) {
2518                     data->offset = offset;
2519                 }
2520                 data->count++;
2521             } else {
2522                 if (flush_outstanding_data(data)) {
2523                     goto errout;
2524                 }
2525             }
2526
2527             offset += info.block_size;
2528
2529             /* Write data if we are aligned or buffer size reached */
2530             if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2531                 || data->count == BLOCKS_AT_A_TIME) {
2532                 if (flush_outstanding_data(data)) {
2533                     goto errout;
2534                 }
2535             }
2536
2537             if (!is_battery_ok_to_continue()) {
2538                 SLOGE("Stopping encryption due to low battery");
2539                 rc = 0;
2540                 goto errout;
2541             }
2542
2543         }
2544         if (flush_outstanding_data(data)) {
2545             goto errout;
2546         }
2547     }
2548
2549     data->completed = 1;
2550     rc = 0;
2551
2552 errout:
2553     log_progress(0, true);
2554     free(data->buffer);
2555     free(block_bitmap);
2556     return rc;
2557 }
2558
2559 static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2560                                        char *real_blkdev,
2561                                        off64_t size,
2562                                        off64_t *size_already_done,
2563                                        off64_t tot_size,
2564                                        off64_t previously_encrypted_upto)
2565 {
2566     u32 i;
2567     struct encryptGroupsData data;
2568     int rc; // Can't initialize without causing warning -Wclobbered
2569
2570     if (previously_encrypted_upto > *size_already_done) {
2571         SLOGD("Not fast encrypting since resuming part way through");
2572         return -1;
2573     }
2574
2575     memset(&data, 0, sizeof(data));
2576     data.real_blkdev = real_blkdev;
2577     data.crypto_blkdev = crypto_blkdev;
2578
2579     if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
2580         SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2581               real_blkdev, errno, strerror(errno));
2582         rc = -1;
2583         goto errout;
2584     }
2585
2586     // Wait until the block device appears.  Re-use the mount retry values since it is reasonable.
2587     int retries = RETRY_MOUNT_ATTEMPTS;
2588     while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2589         if (--retries) {
2590             SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2591                   crypto_blkdev, errno, strerror(errno));
2592             sleep(RETRY_MOUNT_DELAY_SECONDS);
2593         } else {
2594             SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2595                   crypto_blkdev, errno, strerror(errno));
2596             rc = ENABLE_INPLACE_ERR_DEV;
2597             goto errout;
2598         }
2599     }
2600
2601     if (setjmp(setjmp_env)) {
2602         SLOGE("Reading ext4 extent caused an exception\n");
2603         rc = -1;
2604         goto errout;
2605     }
2606
2607     if (read_ext(data.realfd, 0) != 0) {
2608         SLOGE("Failed to read ext4 extent\n");
2609         rc = -1;
2610         goto errout;
2611     }
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     SLOGI("Encrypting ext4 filesystem in place...");
2618
2619     data.tot_used_blocks = data.numblocks;
2620     for (i = 0; i < aux_info.groups; ++i) {
2621       data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2622     }
2623
2624     data.one_pct = data.tot_used_blocks / 100;
2625     data.cur_pct = 0;
2626
2627     struct timespec time_started = {0};
2628     if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2629         SLOGW("Error getting time at start");
2630         // Note - continue anyway - we'll run with 0
2631     }
2632     data.time_started = time_started.tv_sec;
2633     data.remaining_time = -1;
2634
2635     rc = encrypt_groups(&data);
2636     if (rc) {
2637         SLOGE("Error encrypting groups");
2638         goto errout;
2639     }
2640
2641     *size_already_done += data.completed ? size : data.last_written_sector;
2642     rc = 0;
2643
2644 errout:
2645     close(data.realfd);
2646     close(data.cryptofd);
2647
2648     return rc;
2649 }
2650
2651 static void log_progress_f2fs(u64 block, bool completed)
2652 {
2653     // Precondition - if completed data = 0 else data != 0
2654
2655     // Track progress so we can skip logging blocks
2656     static u64 last_block = (u64)-1;
2657
2658     // Need to close existing 'Encrypting from' log?
2659     if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2660         SLOGI("Encrypted to block %" PRId64, last_block);
2661         last_block = -1;
2662     }
2663
2664     // Need to start new 'Encrypting from' log?
2665     if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2666         SLOGI("Encrypting from block %" PRId64, block);
2667     }
2668
2669     // Update offset
2670     if (!completed) {
2671         last_block = block;
2672     }
2673 }
2674
2675 static int encrypt_one_block_f2fs(u64 pos, void *data)
2676 {
2677     struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2678
2679     priv_dat->blocks_already_done = pos - 1;
2680     update_progress(priv_dat, 1);
2681
2682     off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2683
2684     if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2685         SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
2686         return -1;
2687     }
2688
2689     if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2690         SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
2691         return -1;
2692     } else {
2693         log_progress_f2fs(pos, false);
2694     }
2695
2696     return 0;
2697 }
2698
2699 static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2700                                        char *real_blkdev,
2701                                        off64_t size,
2702                                        off64_t *size_already_done,
2703                                        off64_t tot_size,
2704                                        off64_t previously_encrypted_upto)
2705 {
2706     struct encryptGroupsData data;
2707     struct f2fs_info *f2fs_info = NULL;
2708     int rc = ENABLE_INPLACE_ERR_OTHER;
2709     if (previously_encrypted_upto > *size_already_done) {
2710         SLOGD("Not fast encrypting since resuming part way through");
2711         return ENABLE_INPLACE_ERR_OTHER;
2712     }
2713     memset(&data, 0, sizeof(data));
2714     data.real_blkdev = real_blkdev;
2715     data.crypto_blkdev = crypto_blkdev;
2716     data.realfd = -1;
2717     data.cryptofd = -1;
2718     if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
2719         SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
2720               real_blkdev);
2721         goto errout;
2722     }
2723     if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2724         SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
2725               crypto_blkdev, errno, strerror(errno));
2726         rc = ENABLE_INPLACE_ERR_DEV;
2727         goto errout;
2728     }
2729
2730     f2fs_info = generate_f2fs_info(data.realfd);
2731     if (!f2fs_info)
2732       goto errout;
2733
2734     data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2735     data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2736     data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2737
2738     data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2739
2740     data.one_pct = data.tot_used_blocks / 100;
2741     data.cur_pct = 0;
2742     data.time_started = time(NULL);
2743     data.remaining_time = -1;
2744
2745     data.buffer = malloc(f2fs_info->block_size);
2746     if (!data.buffer) {
2747         SLOGE("Failed to allocate crypto buffer");
2748         goto errout;
2749     }
2750
2751     data.count = 0;
2752
2753     /* Currently, this either runs to completion, or hits a nonrecoverable error */
2754     rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2755
2756     if (rc) {
2757         SLOGE("Error in running over f2fs blocks");
2758         rc = ENABLE_INPLACE_ERR_OTHER;
2759         goto errout;
2760     }
2761
2762     *size_already_done += size;
2763     rc = 0;
2764
2765 errout:
2766     if (rc)
2767         SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2768
2769     log_progress_f2fs(0, true);
2770     free(f2fs_info);
2771     free(data.buffer);
2772     close(data.realfd);
2773     close(data.cryptofd);
2774
2775     return rc;
2776 }
2777
2778 static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2779                                        off64_t size, off64_t *size_already_done,
2780                                        off64_t tot_size,
2781                                        off64_t previously_encrypted_upto)
2782 {
2783     int realfd, cryptofd;
2784     char *buf[CRYPT_INPLACE_BUFSIZE];
2785     int rc = ENABLE_INPLACE_ERR_OTHER;
2786     off64_t numblocks, i, remainder;
2787     off64_t one_pct, cur_pct, new_pct;
2788     off64_t blocks_already_done, tot_numblocks;
2789
2790     if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
2791         SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2792         return ENABLE_INPLACE_ERR_OTHER;
2793     }
2794
2795     if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2796         SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2797               crypto_blkdev, errno, strerror(errno));
2798         close(realfd);
2799         return ENABLE_INPLACE_ERR_DEV;
2800     }
2801
2802     /* This is pretty much a simple loop of reading 4K, and writing 4K.
2803      * The size passed in is the number of 512 byte sectors in the filesystem.
2804      * So compute the number of whole 4K blocks we should read/write,
2805      * and the remainder.
2806      */
2807     numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2808     remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
2809     tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2810     blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2811
2812     SLOGE("Encrypting filesystem in place...");
2813
2814     i = previously_encrypted_upto + 1 - *size_already_done;
2815
2816     if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2817         SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2818         goto errout;
2819     }
2820
2821     if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2822         SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2823         goto errout;
2824     }
2825
2826     for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2827         if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2828             SLOGE("Error reading initial sectors from real_blkdev %s for "
2829                   "inplace encrypt\n", crypto_blkdev);
2830             goto errout;
2831         }
2832         if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2833             SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2834                   "inplace encrypt\n", crypto_blkdev);
2835             goto errout;
2836         } else {
2837             SLOGI("Encrypted 1 block at %" PRId64, i);
2838         }
2839     }
2840
2841     one_pct = tot_numblocks / 100;
2842     cur_pct = 0;
2843     /* process the majority of the filesystem in blocks */
2844     for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
2845         new_pct = (i + blocks_already_done) / one_pct;
2846         if (new_pct > cur_pct) {
2847             char buf[8];
2848
2849             cur_pct = new_pct;
2850             snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
2851             property_set("vold.encrypt_progress", buf);
2852         }
2853         if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
2854             SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
2855             goto errout;
2856         }
2857         if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
2858             SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2859             goto errout;
2860         } else {
2861             SLOGD("Encrypted %d block at %" PRId64,
2862                   CRYPT_SECTORS_PER_BUFSIZE,
2863                   i * CRYPT_SECTORS_PER_BUFSIZE);
2864         }
2865
2866        if (!is_battery_ok_to_continue()) {
2867             SLOGE("Stopping encryption due to low battery");
2868             *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2869             rc = 0;
2870             goto errout;
2871         }
2872     }
2873
2874     /* Do any remaining sectors */
2875     for (i=0; i<remainder; i++) {
2876         if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2877             SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
2878             goto errout;
2879         }
2880         if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2881             SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2882             goto errout;
2883         } else {
2884             SLOGI("Encrypted 1 block at next location");
2885         }
2886     }
2887
2888     *size_already_done += size;
2889     rc = 0;
2890
2891 errout:
2892     close(realfd);
2893     close(cryptofd);
2894
2895     return rc;
2896 }
2897
2898 /* returns on of the ENABLE_INPLACE_* return codes */
2899 static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2900                                   off64_t size, off64_t *size_already_done,
2901                                   off64_t tot_size,
2902                                   off64_t previously_encrypted_upto)
2903 {
2904     int rc_ext4, rc_f2fs, rc_full;
2905     if (previously_encrypted_upto) {
2906         SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
2907     }
2908
2909     if (*size_already_done + size < previously_encrypted_upto) {
2910         *size_already_done += size;
2911         return 0;
2912     }
2913
2914     /* TODO: identify filesystem type.
2915      * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2916      * then we will drop down to cryptfs_enable_inplace_f2fs.
2917      * */
2918     if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
2919                                 size, size_already_done,
2920                                 tot_size, previously_encrypted_upto)) == 0) {
2921       return 0;
2922     }
2923     SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
2924
2925     if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
2926                                 size, size_already_done,
2927                                 tot_size, previously_encrypted_upto)) == 0) {
2928       return 0;
2929     }
2930     SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
2931
2932     rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
2933                                        size, size_already_done, tot_size,
2934                                        previously_encrypted_upto);
2935     SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2936
2937     /* Hack for b/17898962, the following is the symptom... */
2938     if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2939         && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2940         && rc_full == ENABLE_INPLACE_ERR_DEV) {
2941             return ENABLE_INPLACE_ERR_DEV;
2942     }
2943     return rc_full;
2944 }
2945
2946 #define CRYPTO_ENABLE_WIPE 1
2947 #define CRYPTO_ENABLE_INPLACE 2
2948
2949 #define FRAMEWORK_BOOT_WAIT 60
2950
2951 static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2952 {
2953     int fd = open(filename, O_RDONLY|O_CLOEXEC);
2954     if (fd == -1) {
2955         SLOGE("Error opening file %s", filename);
2956         return -1;
2957     }
2958
2959     char block[CRYPT_INPLACE_BUFSIZE];
2960     memset(block, 0, sizeof(block));
2961     if (unix_read(fd, block, sizeof(block)) < 0) {
2962         SLOGE("Error reading file %s", filename);
2963         close(fd);
2964         return -1;
2965     }
2966
2967     close(fd);
2968
2969     SHA256_CTX c;
2970     SHA256_Init(&c);
2971     SHA256_Update(&c, block, sizeof(block));
2972     SHA256_Final(buf, &c);
2973
2974     return 0;
2975 }
2976
2977 static int get_fs_type(struct fstab_rec *rec)
2978 {
2979     if (!strcmp(rec->fs_type, "ext4")) {
2980         return EXT4_FS;
2981     } else if (!strcmp(rec->fs_type, "f2fs")) {
2982         return F2FS_FS;
2983     } else {
2984         return -1;
2985     }
2986 }
2987
2988 static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2989                                       char *crypto_blkdev, char *real_blkdev,
2990                                       int previously_encrypted_upto)
2991 {
2992     off64_t cur_encryption_done=0, tot_encryption_size=0;
2993     int rc = -1;
2994
2995     if (!is_battery_ok_to_start()) {
2996         SLOGW("Not starting encryption due to low battery");
2997         return 0;
2998     }
2999
3000     /* The size of the userdata partition, and add in the vold volumes below */
3001     tot_encryption_size = crypt_ftr->fs_size;
3002
3003     if (how == CRYPTO_ENABLE_WIPE) {
3004         struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3005         int fs_type = get_fs_type(rec);
3006         if (fs_type < 0) {
3007             SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
3008             return -1;
3009         }
3010         rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
3011     } else if (how == CRYPTO_ENABLE_INPLACE) {
3012         rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
3013                                     crypt_ftr->fs_size, &cur_encryption_done,
3014                                     tot_encryption_size,
3015                                     previously_encrypted_upto);
3016
3017         if (rc == ENABLE_INPLACE_ERR_DEV) {
3018             /* Hack for b/17898962 */
3019             SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
3020             cryptfs_reboot(reboot);
3021         }
3022
3023         if (!rc) {
3024             crypt_ftr->encrypted_upto = cur_encryption_done;
3025         }
3026
3027         if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
3028             /* The inplace routine never actually sets the progress to 100% due
3029              * to the round down nature of integer division, so set it here */
3030             property_set("vold.encrypt_progress", "100");
3031         }
3032     } else {
3033         /* Shouldn't happen */
3034         SLOGE("cryptfs_enable: internal error, unknown option\n");
3035         rc = -1;
3036     }
3037
3038     return rc;
3039 }
3040
3041 int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
3042                             int allow_reboot)
3043 {
3044     int how = 0;
3045     char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
3046     unsigned char decrypted_master_key[KEY_LEN_BYTES];
3047     int rc=-1, i;
3048     struct crypt_mnt_ftr crypt_ftr;
3049     struct crypt_persist_data *pdata;
3050     char encrypted_state[PROPERTY_VALUE_MAX];
3051     char lockid[32] = { 0 };
3052     char key_loc[PROPERTY_VALUE_MAX];
3053     int num_vols;
3054     off64_t previously_encrypted_upto = 0;
3055 #ifdef CONFIG_HW_DISK_ENCRYPTION
3056     unsigned char newpw[32];
3057     int key_index = 0;
3058 #endif
3059
3060     if (!strcmp(howarg, "wipe")) {
3061       how = CRYPTO_ENABLE_WIPE;
3062     } else if (! strcmp(howarg, "inplace")) {
3063       how = CRYPTO_ENABLE_INPLACE;
3064     } else {
3065       /* Shouldn't happen, as CommandListener vets the args */
3066       goto error_unencrypted;
3067     }
3068
3069     /* See if an encryption was underway and interrupted */
3070     if (how == CRYPTO_ENABLE_INPLACE
3071           && get_crypt_ftr_and_key(&crypt_ftr) == 0
3072           && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
3073         previously_encrypted_upto = crypt_ftr.encrypted_upto;
3074         crypt_ftr.encrypted_upto = 0;
3075         crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
3076
3077         /* At this point, we are in an inconsistent state. Until we successfully
3078            complete encryption, a reboot will leave us broken. So mark the
3079            encryption failed in case that happens.
3080            On successfully completing encryption, remove this flag */
3081         crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3082
3083         put_crypt_ftr_and_key(&crypt_ftr);
3084     }
3085
3086     property_get("ro.crypto.state", encrypted_state, "");
3087     if (how != CRYPTO_ENABLE_WIPE && !strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
3088         SLOGE("Device is already running encrypted, aborting");
3089         goto error_unencrypted;
3090     }
3091
3092     // TODO refactor fs_mgr_get_crypt_info to get both in one call
3093     fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
3094     fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
3095
3096     /* Get the size of the real block device */
3097     int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
3098     if (fd == -1) {
3099         SLOGE("Cannot open block device %s\n", real_blkdev);
3100         goto error_unencrypted;
3101     }
3102     unsigned long nr_sec;
3103     get_blkdev_size(fd, &nr_sec);
3104     if (nr_sec == 0) {
3105         SLOGE("Cannot get size of block device %s\n", real_blkdev);
3106         goto error_unencrypted;
3107     }
3108     close(fd);
3109
3110     /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
3111     if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
3112         unsigned int fs_size_sec, max_fs_size_sec;
3113         fs_size_sec = get_fs_size(real_blkdev);
3114         if (fs_size_sec == 0)
3115             fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3116
3117         max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3118
3119         if (fs_size_sec > max_fs_size_sec) {
3120             SLOGE("Orig filesystem overlaps crypto footer region.  Cannot encrypt in place.");
3121             goto error_unencrypted;
3122         }
3123     }
3124
3125     /* Get a wakelock as this may take a while, and we don't want the
3126      * device to sleep on us.  We'll grab a partial wakelock, and if the UI
3127      * wants to keep the screen on, it can grab a full wakelock.
3128      */
3129     snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
3130     acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3131
3132     /* The init files are setup to stop the class main and late start when
3133      * vold sets trigger_shutdown_framework.
3134      */
3135     property_set("vold.decrypt", "trigger_shutdown_framework");
3136     SLOGD("Just asked init to shut down class main\n");
3137
3138     /* Ask vold to unmount all devices that it manages */
3139     if (vold_unmountAll()) {
3140         SLOGE("Failed to unmount all vold managed devices");
3141     }
3142
3143     /* Now unmount the /data partition. */
3144     if (wait_and_unmount(DATA_MNT_POINT, false)) {
3145         if (allow_reboot) {
3146             goto error_shutting_down;
3147         } else {
3148             goto error_unencrypted;
3149         }
3150     }
3151
3152     /* Start the actual work of making an encrypted filesystem */
3153     /* Initialize a crypt_mnt_ftr for the partition */
3154     if (previously_encrypted_upto == 0) {
3155         if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3156             goto error_shutting_down;
3157         }
3158
3159         if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3160             crypt_ftr.fs_size = nr_sec
3161               - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3162         } else {
3163             crypt_ftr.fs_size = nr_sec;
3164         }
3165         /* At this point, we are in an inconsistent state. Until we successfully
3166            complete encryption, a reboot will leave us broken. So mark the
3167            encryption failed in case that happens.
3168            On successfully completing encryption, remove this flag */
3169         crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3170         crypt_ftr.crypt_type = crypt_type;
3171         strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3172
3173         /* Make an encrypted master key */
3174         if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3175             SLOGE("Cannot create encrypted master key\n");
3176             goto error_shutting_down;
3177         }
3178
3179 #ifdef CONFIG_HW_DISK_ENCRYPTION
3180         strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3181         clear_hw_device_encryption_key();
3182         if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr.salt,
3183                                         &crypt_ftr))
3184             key_index = set_hw_device_encryption_key(passwd, (char*)crypt_ftr.crypto_type_name);
3185         else
3186             key_index = set_hw_device_encryption_key((const char*)newpw,
3187                                 (char*) crypt_ftr.crypto_type_name);
3188         if (key_index < 0)
3189             goto error_shutting_down;
3190 #endif
3191
3192         /* Write the key to the end of the partition */
3193         put_crypt_ftr_and_key(&crypt_ftr);
3194
3195         /* If any persistent data has been remembered, save it.
3196          * If none, create a valid empty table and save that.
3197          */
3198         if (!persist_data) {
3199            pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3200            if (pdata) {
3201                init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3202                persist_data = pdata;
3203            }
3204         }
3205         if (persist_data) {
3206             save_persistent_data();
3207         }
3208     }
3209
3210     /* Do extra work for a better UX when doing the long inplace encryption */
3211     if (how == CRYPTO_ENABLE_INPLACE) {
3212         /* Now that /data is unmounted, we need to mount a tmpfs
3213          * /data, set a property saying we're doing inplace encryption,
3214          * and restart the framework.
3215          */
3216         if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
3217             goto error_shutting_down;
3218         }
3219         /* Tells the framework that inplace encryption is starting */
3220         property_set("vold.encrypt_progress", "0");
3221
3222         /* restart the framework. */
3223         /* Create necessary paths on /data */
3224         if (prep_data_fs()) {
3225             goto error_shutting_down;
3226         }
3227
3228         /* Ugh, shutting down the framework is not synchronous, so until it
3229          * can be fixed, this horrible hack will wait a moment for it all to
3230          * shut down before proceeding.  Without it, some devices cannot
3231          * restart the graphics services.
3232          */
3233         sleep(2);
3234
3235         /* startup service classes main and late_start */
3236         property_set("vold.decrypt", "trigger_restart_min_framework");
3237         SLOGD("Just triggered restart_min_framework\n");
3238
3239         /* OK, the framework is restarted and will soon be showing a
3240          * progress bar.  Time to setup an encrypted mapping, and
3241          * either write a new filesystem, or encrypt in place updating
3242          * the progress bar as we work.
3243          */
3244     }
3245
3246     decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
3247 #ifdef CONFIG_HW_DISK_ENCRYPTION
3248     if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
3249       create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev, crypto_blkdev,
3250                           "userdata");
3251     else
3252       create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3253                           "userdata");
3254
3255 #else
3256     create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3257                           "userdata");
3258 #endif
3259
3260     /* If we are continuing, check checksums match */
3261     rc = 0;
3262     if (previously_encrypted_upto) {
3263         __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3264         rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
3265
3266         if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3267                           sizeof(hash_first_block)) != 0) {
3268             SLOGE("Checksums do not match - trigger wipe");
3269             rc = -1;
3270         }
3271     }
3272
3273     if (!rc) {
3274         rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3275                                         crypto_blkdev, real_blkdev,
3276                                         previously_encrypted_upto);
3277     }
3278
3279     /* Calculate checksum if we are not finished */
3280     if (!rc && how == CRYPTO_ENABLE_INPLACE
3281             && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
3282         rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3283                                       crypt_ftr.hash_first_block);
3284         if (rc) {
3285             SLOGE("Error calculating checksum for continuing encryption");
3286             rc = -1;
3287         }
3288     }
3289
3290     /* Undo the dm-crypt mapping whether we succeed or not */
3291     delete_crypto_blk_dev("userdata");
3292
3293     if (! rc) {
3294         /* Success */
3295         crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
3296
3297         if (how == CRYPTO_ENABLE_INPLACE
3298               && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
3299             SLOGD("Encrypted up to sector %lld - will continue after reboot",
3300                   crypt_ftr.encrypted_upto);
3301             crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
3302         }
3303
3304         put_crypt_ftr_and_key(&crypt_ftr);
3305
3306         if (how == CRYPTO_ENABLE_WIPE
3307               || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
3308           char value[PROPERTY_VALUE_MAX];
3309           property_get("ro.crypto.state", value, "");
3310           if (!strcmp(value, "")) {
3311             /* default encryption - continue first boot sequence */
3312             property_set("ro.crypto.state", "encrypted");
3313             release_wake_lock(lockid);
3314             cryptfs_check_passwd(DEFAULT_PASSWORD);
3315             cryptfs_restart_internal(1);
3316             return 0;
3317           } else {
3318             sleep(2); /* Give the UI a chance to show 100% progress */
3319             cryptfs_reboot(reboot);
3320           }
3321         } else {
3322             sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
3323             cryptfs_reboot(shutdown);
3324         }
3325     } else {
3326         char value[PROPERTY_VALUE_MAX];
3327
3328         property_get("ro.vold.wipe_on_crypt_fail", value, "0");
3329         if (!strcmp(value, "1")) {
3330             /* wipe data if encryption failed */
3331             SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3332             mkdir("/cache/recovery", 0700);
3333             int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0600);
3334             if (fd >= 0) {
3335                 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3336                 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
3337                 close(fd);
3338             } else {
3339                 SLOGE("could not open /cache/recovery/command\n");
3340             }
3341             cryptfs_reboot(recovery);
3342         } else {
3343             /* set property to trigger dialog */
3344             property_set("vold.encrypt_progress", "error_partially_encrypted");
3345             release_wake_lock(lockid);
3346         }
3347         return -1;
3348     }
3349
3350     /* hrm, the encrypt step claims success, but the reboot failed.
3351      * This should not happen.
3352      * Set the property and return.  Hope the framework can deal with it.
3353      */
3354     property_set("vold.encrypt_progress", "error_reboot_failed");
3355     release_wake_lock(lockid);
3356     return rc;
3357
3358 error_unencrypted:
3359     property_set("vold.encrypt_progress", "error_not_encrypted");
3360     if (lockid[0]) {
3361         release_wake_lock(lockid);
3362     }
3363     return -1;
3364
3365 error_shutting_down:
3366     /* we failed, and have not encrypted anthing, so the users's data is still intact,
3367      * but the framework is stopped and not restarted to show the error, so it's up to
3368      * vold to restart the system.
3369      */
3370     SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
3371     cryptfs_reboot(reboot);
3372
3373     /* shouldn't get here */
3374     property_set("vold.encrypt_progress", "error_shutting_down");
3375     if (lockid[0]) {
3376         release_wake_lock(lockid);
3377     }
3378     return -1;
3379 }
3380
3381 int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
3382 {
3383     return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3384 }
3385
3386 int cryptfs_enable_default(char *howarg, int allow_reboot)
3387 {
3388     return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3389                           DEFAULT_PASSWORD, allow_reboot);
3390 }
3391
3392 int cryptfs_changepw(int crypt_type, const char *currentpw, const char *newpw)
3393 {
3394     if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3395         return e4crypt_change_password(DATA_MNT_POINT, crypt_type,
3396                     crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3397                                                      : newpw);
3398     }
3399
3400     struct crypt_mnt_ftr crypt_ftr;
3401     int rc;
3402
3403     /* This is only allowed after we've successfully decrypted the master key */
3404     if (!master_key_saved) {
3405         SLOGE("Key not saved, aborting");
3406         return -1;
3407     }
3408
3409     if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3410         SLOGE("Invalid crypt_type %d", crypt_type);
3411         return -1;
3412     }
3413
3414     /* get key */
3415     if (get_crypt_ftr_and_key(&crypt_ftr)) {
3416         SLOGE("Error getting crypt footer and key");
3417         return -1;
3418     }
3419
3420 #ifdef CONFIG_HW_DISK_ENCRYPTION
3421     int rc1;
3422     unsigned char tmp_curpw[32] = {0};
3423     rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3424                                       DEFAULT_PASSWORD : currentpw, tmp_curpw,
3425                                       crypt_ftr.salt, &crypt_ftr);
3426 #endif
3427
3428
3429     crypt_ftr.crypt_type = crypt_type;
3430
3431     if (previous_type == CRYPT_TYPE_DEFAULT)
3432         currentpw = DEFAULT_PASSWORD;
3433     previous_type = crypt_type;
3434
3435     rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3436                                                         : newpw,
3437                        crypt_ftr.salt,
3438                        saved_master_key,
3439                        crypt_ftr.master_key,
3440                        &crypt_ftr, false);
3441     if (rc) {
3442         SLOGE("Encrypt master key failed: %d", rc);
3443         return -1;
3444     }
3445     /* save the key */
3446     put_crypt_ftr_and_key(&crypt_ftr);
3447
3448 #ifdef CONFIG_HW_DISK_ENCRYPTION
3449     int ret, rc2;
3450     unsigned char tmp_newpw[32] = {0};
3451
3452     rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3453                                 DEFAULT_PASSWORD : newpw , tmp_newpw,
3454                                 crypt_ftr.salt, &crypt_ftr);
3455
3456     if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3457         ret = update_hw_device_encryption_key(
3458                 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3459                 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3460                                     (char*)crypt_ftr.crypto_type_name);
3461         if (ret) {
3462             SLOGE("Error updating device encryption hardware key ret %d", ret);
3463             return -1;
3464         } else {
3465             SLOGI("Encryption hardware key updated");
3466         }
3467     }
3468 #endif
3469     return 0;
3470 }
3471
3472 static unsigned int persist_get_max_entries(int encrypted) {
3473     struct crypt_mnt_ftr crypt_ftr;
3474     unsigned int dsize;
3475     unsigned int max_persistent_entries;
3476
3477     /* If encrypted, use the values from the crypt_ftr, otherwise
3478      * use the values for the current spec.
3479      */
3480     if (encrypted) {
3481         if (get_crypt_ftr_and_key(&crypt_ftr)) {
3482             return -1;
3483         }
3484         dsize = crypt_ftr.persist_data_size;
3485     } else {
3486         dsize = CRYPT_PERSIST_DATA_SIZE;
3487     }
3488
3489     max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3490         sizeof(struct crypt_persist_entry);
3491
3492     return max_persistent_entries;
3493 }
3494
3495 static int persist_get_key(const char *fieldname, char *value)
3496 {
3497     unsigned int i;
3498
3499     if (persist_data == NULL) {
3500         return -1;
3501     }
3502     for (i = 0; i < persist_data->persist_valid_entries; i++) {
3503         if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3504             /* We found it! */
3505             strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3506             return 0;
3507         }
3508     }
3509
3510     return -1;
3511 }
3512
3513 static int persist_set_key(const char *fieldname, const char *value, int encrypted)
3514 {
3515     unsigned int i;
3516     unsigned int num;
3517     unsigned int max_persistent_entries;
3518
3519     if (persist_data == NULL) {
3520         return -1;
3521     }
3522
3523     max_persistent_entries = persist_get_max_entries(encrypted);
3524
3525     num = persist_data->persist_valid_entries;
3526
3527     for (i = 0; i < num; i++) {
3528         if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3529             /* We found an existing entry, update it! */
3530             memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3531             strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3532             return 0;
3533         }
3534     }
3535
3536     /* We didn't find it, add it to the end, if there is room */
3537     if (persist_data->persist_valid_entries < max_persistent_entries) {
3538         memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3539         strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3540         strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3541         persist_data->persist_valid_entries++;
3542         return 0;
3543     }
3544
3545     return -1;
3546 }
3547
3548 /**
3549  * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3550  * sequence and its index is greater than or equal to index. Return 0 otherwise.
3551  */
3552 static int match_multi_entry(const char *key, const char *field, unsigned index) {
3553     unsigned int field_len;
3554     unsigned int key_index;
3555     field_len = strlen(field);
3556
3557     if (index == 0) {
3558         // The first key in a multi-entry field is just the filedname itself.
3559         if (!strcmp(key, field)) {
3560             return 1;
3561         }
3562     }
3563     // Match key against "%s_%d" % (field, index)
3564     if (strlen(key) < field_len + 1 + 1) {
3565         // Need at least a '_' and a digit.
3566         return 0;
3567     }
3568     if (strncmp(key, field, field_len)) {
3569         // If the key does not begin with field, it's not a match.
3570         return 0;
3571     }
3572     if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3573         return 0;
3574     }
3575     return key_index >= index;
3576 }
3577
3578 /*
3579  * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3580  * remaining entries starting from index will be deleted.
3581  * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3582  * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3583  * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3584  *
3585  */
3586 static int persist_del_keys(const char *fieldname, unsigned index)
3587 {
3588     unsigned int i;
3589     unsigned int j;
3590     unsigned int num;
3591
3592     if (persist_data == NULL) {
3593         return PERSIST_DEL_KEY_ERROR_OTHER;
3594     }
3595
3596     num = persist_data->persist_valid_entries;
3597
3598     j = 0; // points to the end of non-deleted entries.
3599     // Filter out to-be-deleted entries in place.
3600     for (i = 0; i < num; i++) {
3601         if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3602             persist_data->persist_entry[j] = persist_data->persist_entry[i];
3603             j++;
3604         }
3605     }
3606
3607     if (j < num) {
3608         persist_data->persist_valid_entries = j;
3609         // Zeroise the remaining entries
3610         memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3611         return PERSIST_DEL_KEY_OK;
3612     } else {
3613         // Did not find an entry matching the given fieldname
3614         return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3615     }
3616 }
3617
3618 static int persist_count_keys(const char *fieldname)
3619 {
3620     unsigned int i;
3621     unsigned int count;
3622
3623     if (persist_data == NULL) {
3624         return -1;
3625     }
3626
3627     count = 0;
3628     for (i = 0; i < persist_data->persist_valid_entries; i++) {
3629         if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3630             count++;
3631         }
3632     }
3633
3634     return count;
3635 }
3636
3637 /* Return the value of the specified field. */
3638 int cryptfs_getfield(const char *fieldname, char *value, int len)
3639 {
3640     if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3641         return e4crypt_get_field(DATA_MNT_POINT, fieldname, value, len);
3642     }
3643
3644     char temp_value[PROPERTY_VALUE_MAX];
3645     /* CRYPTO_GETFIELD_OK is success,
3646      * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3647      * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3648      * CRYPTO_GETFIELD_ERROR_OTHER is any other error
3649      */
3650     int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3651     int i;
3652     char temp_field[PROPERTY_KEY_MAX];
3653
3654     if (persist_data == NULL) {
3655         load_persistent_data();
3656         if (persist_data == NULL) {
3657             SLOGE("Getfield error, cannot load persistent data");
3658             goto out;
3659         }
3660     }
3661
3662     // Read value from persistent entries. If the original value is split into multiple entries,
3663     // stitch them back together.
3664     if (!persist_get_key(fieldname, temp_value)) {
3665         // We found it, copy it to the caller's buffer and keep going until all entries are read.
3666         if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3667             // value too small
3668             rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3669             goto out;
3670         }
3671         rc = CRYPTO_GETFIELD_OK;
3672
3673         for (i = 1; /* break explicitly */; i++) {
3674             if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3675                     (int) sizeof(temp_field)) {
3676                 // If the fieldname is very long, we stop as soon as it begins to overflow the
3677                 // maximum field length. At this point we have in fact fully read out the original
3678                 // value because cryptfs_setfield would not allow fields with longer names to be
3679                 // written in the first place.
3680                 break;
3681             }
3682             if (!persist_get_key(temp_field, temp_value)) {
3683                   if (strlcat(value, temp_value, len) >= (unsigned)len) {
3684                       // value too small.
3685                       rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3686                       goto out;
3687                   }
3688             } else {
3689                 // Exhaust all entries.
3690                 break;
3691             }
3692         }
3693     } else {
3694         /* Sadness, it's not there.  Return the error */
3695         rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
3696     }
3697
3698 out:
3699     return rc;
3700 }
3701
3702 /* Set the value of the specified field. */
3703 int cryptfs_setfield(const char *fieldname, const char *value)
3704 {
3705     if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3706         return e4crypt_set_field(DATA_MNT_POINT, fieldname, value);
3707     }
3708
3709     char encrypted_state[PROPERTY_VALUE_MAX];
3710     /* 0 is success, negative values are error */
3711     int rc = CRYPTO_SETFIELD_ERROR_OTHER;
3712     int encrypted = 0;
3713     unsigned int field_id;
3714     char temp_field[PROPERTY_KEY_MAX];
3715     unsigned int num_entries;
3716     unsigned int max_keylen;
3717
3718     if (persist_data == NULL) {
3719         load_persistent_data();
3720         if (persist_data == NULL) {
3721             SLOGE("Setfield error, cannot load persistent data");
3722             goto out;
3723         }
3724     }
3725
3726     property_get("ro.crypto.state", encrypted_state, "");
3727     if (!strcmp(encrypted_state, "encrypted") ) {
3728         encrypted = 1;
3729     }
3730
3731     // Compute the number of entries required to store value, each entry can store up to
3732     // (PROPERTY_VALUE_MAX - 1) chars
3733     if (strlen(value) == 0) {
3734         // Empty value also needs one entry to store.
3735         num_entries = 1;
3736     } else {
3737         num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3738     }
3739
3740     max_keylen = strlen(fieldname);
3741     if (num_entries > 1) {
3742         // Need an extra "_%d" suffix.
3743         max_keylen += 1 + log10(num_entries);
3744     }
3745     if (max_keylen > PROPERTY_KEY_MAX - 1) {
3746         rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
3747         goto out;
3748     }
3749
3750     // Make sure we have enough space to write the new value
3751     if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3752         persist_get_max_entries(encrypted)) {
3753         rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3754         goto out;
3755     }
3756
3757     // Now that we know persist_data has enough space for value, let's delete the old field first
3758     // to make up space.
3759     persist_del_keys(fieldname, 0);
3760
3761     if (persist_set_key(fieldname, value, encrypted)) {
3762         // fail to set key, should not happen as we have already checked the available space
3763         SLOGE("persist_set_key() error during setfield()");
3764         goto out;
3765     }
3766
3767     for (field_id = 1; field_id < num_entries; field_id++) {
3768         snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3769
3770         if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3771             // fail to set key, should not happen as we have already checked the available space.
3772             SLOGE("persist_set_key() error during setfield()");
3773             goto out;
3774         }
3775     }
3776
3777     /* If we are running encrypted, save the persistent data now */
3778     if (encrypted) {
3779         if (save_persistent_data()) {
3780             SLOGE("Setfield error, cannot save persistent data");
3781             goto out;
3782         }
3783     }
3784
3785     rc = CRYPTO_SETFIELD_OK;
3786
3787 out:
3788     return rc;
3789 }
3790
3791 /* Checks userdata. Attempt to mount the volume if default-
3792  * encrypted.
3793  * On success trigger next init phase and return 0.
3794  * Currently do not handle failure - see TODO below.
3795  */
3796 int cryptfs_mount_default_encrypted(void)
3797 {
3798     char decrypt_state[PROPERTY_VALUE_MAX];
3799     property_get("vold.decrypt", decrypt_state, "0");
3800     if (!strcmp(decrypt_state, "0")) {
3801         SLOGE("Not encrypted - should not call here");
3802     } else {
3803         int crypt_type = cryptfs_get_password_type();
3804         if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3805             SLOGE("Bad crypt type - error");
3806         } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3807             SLOGD("Password is not default - "
3808                   "starting min framework to prompt");
3809             property_set("vold.decrypt", "trigger_restart_min_framework");
3810             return 0;
3811         } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3812             SLOGD("Password is default - restarting filesystem");
3813             cryptfs_restart_internal(0);
3814             return 0;
3815         } else {
3816             SLOGE("Encrypted, default crypt type but can't decrypt");
3817         }
3818     }
3819
3820     /** Corrupt. Allow us to boot into framework, which will detect bad
3821         crypto when it calls do_crypto_complete, then do a factory reset
3822      */
3823     property_set("vold.decrypt", "trigger_restart_min_framework");
3824     return 0;
3825 }
3826
3827 /* Returns type of the password, default, pattern, pin or password.
3828  */
3829 int cryptfs_get_password_type(void)
3830 {
3831     if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3832         return e4crypt_get_password_type(DATA_MNT_POINT);
3833     }
3834
3835     struct crypt_mnt_ftr crypt_ftr;
3836
3837     if (get_crypt_ftr_and_key(&crypt_ftr)) {
3838         SLOGE("Error getting crypt footer and key\n");
3839         return -1;
3840     }
3841
3842     if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3843         return -1;
3844     }
3845
3846     return crypt_ftr.crypt_type;
3847 }
3848
3849 const char* cryptfs_get_password()
3850 {
3851     if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3852         return e4crypt_get_password(DATA_MNT_POINT);
3853     }
3854
3855     struct timespec now;
3856     clock_gettime(CLOCK_BOOTTIME, &now);
3857     if (now.tv_sec < password_expiry_time) {
3858         return password;
3859     } else {
3860         cryptfs_clear_password();
3861         return 0;
3862     }
3863 }
3864
3865 void cryptfs_clear_password()
3866 {
3867     if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3868         e4crypt_clear_password(DATA_MNT_POINT);
3869     }
3870
3871     if (password) {
3872         size_t len = strlen(password);
3873         memset(password, 0, len);
3874         free(password);
3875         password = 0;
3876         password_expiry_time = 0;
3877     }
3878 }
3879
3880 int cryptfs_enable_file()
3881 {
3882     return e4crypt_enable(DATA_MNT_POINT);
3883 }
3884
3885 int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3886 {
3887     if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3888         SLOGE("Failed to initialize crypt_ftr");
3889         return -1;
3890     }
3891
3892     if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3893                                     crypt_ftr->salt, crypt_ftr)) {
3894         SLOGE("Cannot create encrypted master key\n");
3895         return -1;
3896     }
3897
3898     //crypt_ftr->keysize = key_length / 8;
3899     return 0;
3900 }
3901
3902 int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3903                            unsigned char* master_key)
3904 {
3905     int rc;
3906
3907     unsigned char* intermediate_key = 0;
3908     size_t intermediate_key_size = 0;
3909
3910     if (password == 0 || *password == 0) {
3911         password = DEFAULT_PASSWORD;
3912     }
3913
3914     rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3915                             &intermediate_key_size);
3916
3917     int N = 1 << ftr->N_factor;
3918     int r = 1 << ftr->r_factor;
3919     int p = 1 << ftr->p_factor;
3920
3921     unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3922
3923     rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3924                        ftr->salt, sizeof(ftr->salt), N, r, p,
3925                        scrypted_intermediate_key,
3926                        sizeof(scrypted_intermediate_key));
3927
3928     free(intermediate_key);
3929
3930     if (rc) {
3931         SLOGE("Can't calculate intermediate key");
3932         return rc;
3933     }
3934
3935     return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3936                   intermediate_key_size);
3937 }
3938
3939 int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3940                          const unsigned char* master_key)
3941 {
3942     return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3943                               ftr, true);
3944 }