1
/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2
* Use of this source code is governed by a BSD-style license that can be
3
* found in the LICENSE file.
5
* This tool will attempt to mount or create the encrypted stateful partition,
6
* and the various bind mountable subdirectories.
10
#define _FILE_OFFSET_BITS 64
21
#include <sys/ioctl.h>
23
#include <sys/statvfs.h>
25
#include <sys/types.h>
26
#include <sys/mount.h>
31
#include <openssl/rand.h>
33
#define CHROMEOS_ENVIRONMENT
35
#include "crossystem.h"
37
#include "mount-encrypted.h"
38
#include "mount-helpers.h"
40
#define STATEFUL_MNT "mnt/stateful_partition"
41
#define ENCRYPTED_MNT STATEFUL_MNT "/encrypted"
45
static const gchar * const kKernelCmdline = "/proc/cmdline";
46
static const gchar * const kKernelCmdlineOption = " encrypted-stateful-key=";
47
static const gchar * const kEncryptedFSType = "ext4";
48
static const gchar * const kCryptDevName = "encstateful";
49
static const gchar * const kTpmDev = "/dev/tpm0";
50
static const gchar * const kNullDev = "/dev/null";
51
static const float kSizePercent = 0.3;
52
static const float kMigrationSizeMultiplier = 1.1;
53
static const uint32_t kLockboxIndex = 0x20000004;
54
static const uint32_t kLockboxSizeV1 = 0x2c;
55
static const uint32_t kLockboxSizeV2 = 0x45;
56
static const uint32_t kLockboxSaltOffset = 0x5;
57
static const uint64_t kSectorSize = 512;
58
static const uint64_t kExt4BlockSize = 4096;
59
static const uint64_t kExt4MinBytes = 16 * 1024 * 1024;
60
static const char * const kStaticKeyDefault = "default unsafe static key";
61
static const char * const kStaticKeyFactory = "factory unsafe static key";
62
static const char * const kStaticKeyFinalizationNeeded = "needs finalization";
63
static const int kModeProduction = 0;
64
static const int kModeFactory = 1;
65
static const int kCryptAllowDiscard = 1;
67
enum migration_method {
77
static struct bind_mount {
78
char * src; /* Location of bind source. */
79
char * dst; /* Destination of bind. */
80
char * previous; /* Migratable prior bind source. */
81
char * pending; /* Location for pending deletion. */
85
int submount; /* Submount is bound already. */
86
} bind_mounts_default[] = {
87
{ ENCRYPTED_MNT "/var", "var",
88
STATEFUL_MNT "/var", STATEFUL_MNT "/.var",
90
S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH, 0 },
91
{ ENCRYPTED_MNT "/chronos", "home/chronos",
92
STATEFUL_MNT "/home/chronos", STATEFUL_MNT "/home/.chronos",
94
S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH, 1 },
99
struct timeval tick = { };
100
struct timeval tick_start = { };
103
static struct bind_mount *bind_mounts = NULL;
104
static gchar *rootdir = NULL;
105
static gchar *stateful_mount = NULL;
106
static gchar *key_path = NULL;
107
static gchar *needs_finalization_path = NULL;
108
static gchar *block_path = NULL;
109
static gchar *encrypted_mount = NULL;
110
static gchar *dmcrypt_name = NULL;
111
static gchar *dmcrypt_dev = NULL;
112
static int has_tpm = 0;
113
static int tpm_init_called = 0;
115
static void tpm_init(void)
122
DEBUG("Opening TPM");
124
setenv("TPM_NO_EXIT", "1", 1);
125
result = TlclLibInit();
128
has_tpm = (result == TPM_SUCCESS);
129
INFO("TPM %s", has_tpm ? "ready" : "not available");
132
/* Returns TPM result status code, and on TPM_SUCCESS, stores ownership
135
static uint32_t tpm_owned(uint8_t *owned)
140
DEBUG("Reading TPM Ownership Flag");
142
result = TPM_E_NO_DEVICE;
144
result = TlclGetOwnership(owned);
145
DEBUG("TPM Ownership Flag returned: %s", result ? "FAIL" : "ok");
150
static void tpm_close(void)
152
if (!has_tpm || !tpm_init_called)
158
static void sha256(char *string, uint8_t *digest)
160
SHA256((unsigned char *)string, strlen(string), digest);
163
/* Extract the desired system key from the kernel's boot command line. */
164
static int get_key_from_cmdline(uint8_t *digest)
169
char *cmdline, *option_end;
170
/* Option name without the leading space. */
171
const gchar *option = kKernelCmdlineOption + 1;
173
if (!g_file_get_contents(kKernelCmdline, &buffer, &length, NULL)) {
174
PERROR(kKernelCmdline);
178
/* Find a string match either at start of string or following
182
if (strncmp(cmdline, option, strlen(option)) == 0 ||
183
(cmdline = strstr(cmdline, kKernelCmdlineOption))) {
184
/* The "=" exists because it is in kKernelCmdlineOption. */
185
cmdline = strstr(cmdline, "=");
186
/* strchrnul() cannot return NULL. */
187
option_end = strchrnul(cmdline, ' ');
189
sha256(cmdline, digest);
190
debug_dump_hex("system key", digest, DIGEST_LENGTH);
198
static int get_system_property(const char *prop, char *buf, size_t length)
202
DEBUG("Fetching System Property '%s'", prop);
203
rc = VbGetSystemPropertyString(prop, buf, length);
204
DEBUG("Got System Property 'mainfw_type': %s", rc ? buf : "FAIL");
209
static int has_chromefw(void)
211
static int state = -1;
214
/* Cache the state so we don't have to perform the query again. */
218
if (!get_system_property("mainfw_type", fw, sizeof(fw)))
221
state = strcmp(fw, "nonchrome") != 0;
225
static int is_cr48(void)
227
static int state = -1;
228
char hwid[PROP_SIZE];
230
/* Cache the state so we don't have to perform the query again. */
234
if (!get_system_property("hwid", hwid, sizeof(hwid)))
237
state = strstr(hwid, "MARIO") != NULL;
242
_read_nvram(uint8_t *buffer, size_t len, uint32_t index, uint32_t size)
247
ERROR("NVRAM size (0x%x > 0x%zx) is too big", size, len);
252
DEBUG("Reading NVRAM area 0x%x (size %u)", index, size);
254
result = TPM_E_NO_DEVICE;
256
result = TlclRead(index, buffer, size);
257
DEBUG("NVRAM read returned: %s", result == TPM_SUCCESS ? "ok"
265
* - does not exist at all (disabled in test firmware or non-chrome device).
268
* TPM ownership cases:
270
* - expect modern lockbox (no migration allowed).
271
* - owned: depends on NVRAM area (below).
274
* - no NVRAM area at all:
275
* - interrupted install (cryptohome has the TPM password)
276
* - ancient device (cr48, cryptohome has thrown away TPM password)
277
* - broken device (cryptohome has thrown away/never had TPM password)
278
* - must expect worst-case: no lockbox ever, and migration allowed.
279
* - defined NVRAM area, but not written to ("Finalized"); interrupted OOBE:
280
* - if legacy size, allow migration.
281
* - if not, disallow migration.
282
* - written ("Finalized") NVRAM area:
283
* - if legacy size, allow migration.
284
* - if not, disallow migration.
286
* When returning 1: (NVRAM area found and used)
287
* - *digest populated with NVRAM area entropy.
288
* - *migrate is 1 for NVRAM v1, 0 for NVRAM v2.
289
* When returning 0: (NVRAM missing or error)
290
* - *digest untouched.
291
* - *migrate always 1
293
static int get_nvram_key(uint8_t *digest, int *migrate)
296
uint8_t value[kLockboxSizeV2], bytes_anded, bytes_ored;
297
uint32_t size, result, i;
301
/* Default to allowing migration (disallow when owned with NVRAMv2). */
304
/* Ignore unowned TPM's NVRAM area. */
305
result = tpm_owned(&owned);
306
if (result != TPM_SUCCESS) {
307
INFO("Could not read TPM Permanent Flags: error 0x%02x.",
312
INFO("TPM not Owned, ignoring NVRAM area.");
316
/* Reading the NVRAM takes 40ms. Instead of querying the NVRAM area
317
* for its size (which takes time), just read the expected size. If
318
* it fails, then fall back to the older size. This means cleared
319
* devices take 80ms (2 failed reads), legacy devices take 80ms
320
* (1 failed read, 1 good read), and populated devices take 40ms,
321
* which is the minimum possible time (instead of 40ms + time to
324
size = kLockboxSizeV2;
325
result = _read_nvram(value, sizeof(value), kLockboxIndex, size);
326
if (result != TPM_SUCCESS) {
327
size = kLockboxSizeV1;
328
result = _read_nvram(value, sizeof(value), kLockboxIndex, size);
329
if (result != TPM_SUCCESS) {
330
/* No NVRAM area at all. */
331
INFO("No NVRAM area defined: error 0x%02x", result);
334
/* Legacy NVRAM area. */
335
INFO("Version 1 NVRAM area found.");
338
INFO("Version 2 NVRAM area found.");
341
debug_dump_hex("nvram", value, size);
343
/* Ignore defined but unwritten NVRAM area. */
346
for (i = 0; i < size; ++i) {
347
bytes_ored |= value[i];
348
bytes_anded &= value[i];
350
if (bytes_ored == 0x0 || bytes_anded == 0xff) {
351
INFO("NVRAM area has been defined but not written.");
355
/* Choose random bytes to use based on NVRAM version. */
360
rand_bytes = value + kLockboxSaltOffset;
361
if (kLockboxSaltOffset + DIGEST_LENGTH > size) {
362
INFO("Impossibly small NVRAM area size (%d).", size);
365
rand_size = DIGEST_LENGTH;
367
if (rand_size < DIGEST_LENGTH) {
368
INFO("Impossibly small rand_size (%d).", rand_size);
371
debug_dump_hex("rand_bytes", rand_bytes, rand_size);
373
SHA256(rand_bytes, rand_size, digest);
374
debug_dump_hex("system key", digest, DIGEST_LENGTH);
379
/* Find the system key used for decrypting the stored encryption key.
380
* ChromeOS devices are required to use the NVRAM area, all the rest will
381
* fallback through various places (kernel command line, BIOS UUID, and
382
* finally a static value) for a system key.
384
static int find_system_key(int mode, uint8_t *digest, int *migration_allowed)
389
/* By default, do not allow migration. */
390
*migration_allowed = 0;
392
/* Factory mode uses a static system key. */
393
if (mode == kModeFactory) {
394
INFO("Using factory insecure system key.");
395
sha256((char *)kStaticKeyFactory, digest);
396
debug_dump_hex("system key", digest, DIGEST_LENGTH);
400
/* Force ChromeOS devices into requiring the system key come from
403
if (has_chromefw()) {
405
rc = get_nvram_key(digest, migration_allowed);
408
INFO("Using NVRAM as system key; already populated%s.",
409
*migration_allowed ? " (legacy)" : "");
411
INFO("Using NVRAM as system key; finalization needed.");
416
if (get_key_from_cmdline(digest)) {
417
INFO("Using kernel command line argument as system key.");
420
if (g_file_get_contents("/sys/class/dmi/id/product_uuid",
421
&key, &length, NULL)) {
423
debug_dump_hex("system key", digest, DIGEST_LENGTH);
425
INFO("Using UUID as system key.");
429
INFO("Using default insecure system key.");
430
sha256((char *)kStaticKeyDefault, digest);
431
debug_dump_hex("system key", digest, DIGEST_LENGTH);
435
/* Returns 1 on success, 0 on failure. */
436
static int get_random_bytes_tpm(unsigned char *buffer, int wanted)
438
uint32_t remaining = wanted;
441
/* Read random bytes from TPM, which can return short reads. */
443
uint32_t result, size;
445
result = TlclGetRandom(buffer + (wanted - remaining),
447
if (result != TPM_SUCCESS || size > remaining) {
448
ERROR("TPM GetRandom failed: error 0x%02x.", result);
457
/* Returns 1 on success, 0 on failure. */
458
static int get_random_bytes(unsigned char *buffer, int wanted)
460
if (has_tpm && get_random_bytes_tpm(buffer, wanted))
463
if (RAND_bytes(buffer, wanted))
465
SSL_ERROR("RAND_bytes");
470
static char *choose_encryption_key(void)
472
unsigned char rand_bytes[DIGEST_LENGTH];
473
unsigned char digest[DIGEST_LENGTH];
475
if (!get_random_bytes(rand_bytes, sizeof(rand_bytes)))
476
ERROR("No entropy source found -- using uninitialized stack");
478
SHA256(rand_bytes, DIGEST_LENGTH, digest);
479
debug_dump_hex("encryption key", digest, DIGEST_LENGTH);
481
return stringify_hex(digest, DIGEST_LENGTH);
484
static int check_bind(struct bind_mount *bind, enum bind_dir dir)
490
if (dir == BIND_SOURCE)
495
if (access(target, R_OK) && mkdir(target, bind->mode)) {
496
PERROR("mkdir(%s)", target);
500
/* Destination may be on read-only filesystem, so skip tweaks. */
501
if (dir == BIND_DEST)
504
if (!(user = getpwnam(bind->owner))) {
505
PERROR("getpwnam(%s)", bind->owner);
508
if (!(group = getgrnam(bind->group))) {
509
PERROR("getgrnam(%s)", bind->group);
513
/* Must do explicit chmod since mkdir()'s mode respects umask. */
514
if (chmod(target, bind->mode)) {
515
PERROR("chmod(%s)", target);
518
if (chown(target, user->pw_uid, group->gr_gid)) {
519
PERROR("chown(%s)", target);
526
static int migrate_contents(struct bind_mount *bind,
527
enum migration_method method)
529
const gchar *previous = NULL;
530
const gchar *pending = NULL;
533
/* Skip migration if the previous bind sources are missing. */
534
if (bind->pending && access(bind->pending, R_OK) == 0)
535
pending = bind->pending;
536
if (bind->previous && access(bind->previous, R_OK) == 0)
537
previous = bind->previous;
538
if (!pending && !previous)
541
/* Pretend migration happened. */
542
if (method == MIGRATE_TEST_ONLY)
545
check_bind(bind, BIND_SOURCE);
547
/* Prefer the pending-delete location when doing migration. */
548
if (!(dotdir = g_strdup_printf("%s/.", pending ? pending : previous))) {
549
PERROR("g_strdup_printf");
550
goto mark_for_removal;
553
INFO("Migrating bind mount contents %s to %s.", dotdir, bind->src);
554
const gchar *cp[] = {
561
if (runcmd(cp, NULL) != 0) {
562
/* If the copy failed, it may have partially populated the
563
* new source, so we need to remove the new source and
564
* rebuild it. Regardless, the previous source must be removed
567
INFO("Failed to migrate %s to %s!", dotdir, bind->src);
568
remove_tree(bind->src);
569
check_bind(bind, BIND_SOURCE);
575
/* The removal of the previous directory needs to happen at finalize
576
* time, otherwise /var state gets lost on a migration if the
577
* system is powered off before the encryption key is saved. Instead,
578
* relocate the directory so it can be removed (or re-migrated).
582
/* If both pending and previous directory exists, we must
583
* remove previous entirely now so it stops taking up disk
584
* space. The pending area will stay pending to be deleted
588
remove_tree(pending);
589
if (rename(previous, bind->pending)) {
590
PERROR("rename(%s,%s)", previous, bind->pending);
594
/* As noted above, failures are unrecoverable, so getting here means
595
* "we're done" more than "it worked".
600
static void finalized(void)
602
/* TODO(keescook): once ext4 supports secure delete, just unlink. */
603
if (access(needs_finalization_path, R_OK) == 0) {
604
/* This is nearly useless on SSDs. */
605
shred(needs_finalization_path);
606
unlink(needs_finalization_path);
610
static void finalize(uint8_t *system_key, char *encryption_key)
612
struct bind_mount *bind;
614
INFO("Writing keyfile %s.", key_path);
615
if (!keyfile_write(key_path, system_key, encryption_key)) {
616
ERROR("Failed to write %s -- aborting.", key_path);
622
for (bind = bind_mounts; bind->src; ++ bind) {
623
if (!bind->pending || access(bind->pending, R_OK))
625
INFO("Removing %s.", bind->pending);
629
remove_tree(bind->pending);
633
static void needs_finalization(char *encryption_key)
635
uint8_t useless_key[DIGEST_LENGTH];
636
sha256((char *)kStaticKeyFinalizationNeeded, useless_key);
638
INFO("Writing finalization intent %s.", needs_finalization_path);
639
if (!keyfile_write(needs_finalization_path, useless_key,
641
ERROR("Failed to write %s -- aborting.",
642
needs_finalization_path);
647
/* This triggers the live encryption key to be written to disk, encrypted
648
* by the system key. It is intended to be called by Cryptohome once the
649
* TPM is done being set up. If the system key is passed as an argument,
650
* use it, otherwise attempt to query the TPM again.
652
static int finalize_from_cmdline(char *key)
654
uint8_t system_key[DIGEST_LENGTH];
655
char *encryption_key;
658
/* Early sanity-check to see if the encrypted device exists,
659
* instead of failing at the end of this function.
661
if (access(dmcrypt_dev, R_OK)) {
662
ERROR("'%s' does not exist, giving up.", dmcrypt_dev);
667
if (strlen(key) != 2 * DIGEST_LENGTH) {
668
ERROR("Invalid key length.");
672
if (!hexify_string(key, system_key, DIGEST_LENGTH)) {
673
ERROR("Failed to convert hex string to byte array");
677
/* Factory mode will never call finalize from the command
678
* line, so force Production mode here.
680
if (!find_system_key(kModeProduction, system_key, &migrate)) {
681
ERROR("Could not locate system key.");
686
encryption_key = dm_get_key(dmcrypt_dev);
687
if (!encryption_key) {
688
ERROR("Could not locate encryption key for %s.", dmcrypt_dev);
692
finalize(system_key, encryption_key);
697
static void spawn_resizer(const char *device, uint64_t blocks,
702
/* Skip resize before forking, if it's not going to happen. */
703
if (blocks >= blocks_max) {
704
INFO("Resizing skipped. blocks:%" PRIu64 " >= blocks_max:%" PRIu64,
716
INFO("Started filesystem resizing process %d.", pid);
722
INFO_INIT("Resizer spawned.");
729
filesystem_resize(device, blocks, blocks_max);
736
/* Do all the work needed to actually set up the encrypted partition.
737
* Takes "mode" argument to help determine where the system key should
740
static int setup_encrypted(int mode)
743
uint8_t system_key[DIGEST_LENGTH];
744
char *encryption_key = NULL;
745
int migrate_allowed = 0, migrate_needed = 0, rebuild = 0;
748
struct bind_mount *bind;
750
struct statvfs stateful_statbuf;
751
uint64_t blocks_min, blocks_max;
753
/* Use the "system key" to decrypt the "encryption key" stored in
754
* the stateful partition.
756
has_system_key = find_system_key(mode, system_key, &migrate_allowed);
757
if (has_system_key) {
758
encryption_key = keyfile_read(key_path, system_key);
760
INFO("No usable system key found.");
763
if (encryption_key) {
764
/* If we found a stored encryption key, we've already
765
* finished a complete login and Cryptohome Finalize
766
* so migration is finished.
770
uint8_t useless_key[DIGEST_LENGTH];
771
sha256((char *)kStaticKeyFinalizationNeeded, useless_key);
772
encryption_key = keyfile_read(needs_finalization_path,
774
if (!encryption_key) {
775
/* This is a brand new system with no keys. */
776
INFO("Generating new encryption key.");
777
encryption_key = choose_encryption_key();
782
ERROR("Finalization unfinished! " \
783
"Encryption key still on disk!");
788
uint64_t fs_bytes_max;
790
/* Wipe out the old files, and ignore errors. */
794
/* Calculate the desired size of the new partition. */
795
if (statvfs(stateful_mount, &stateful_statbuf)) {
796
PERROR(stateful_mount);
799
fs_bytes_max = stateful_statbuf.f_blocks;
800
fs_bytes_max *= kSizePercent;
801
fs_bytes_max *= stateful_statbuf.f_frsize;
803
INFO("Creating sparse backing file with size %" PRIu64 ".",
806
/* Create the sparse file. */
807
sparsefd = sparse_create(block_path, fs_bytes_max);
813
sparsefd = open(block_path, O_RDWR | O_NOFOLLOW);
820
/* Set up loopback device. */
821
INFO("Loopback attaching %s (named %s).", block_path, dmcrypt_name);
822
lodev = loop_attach(sparsefd, dmcrypt_name);
823
if (!lodev || strlen(lodev) == 0) {
824
ERROR("loop_attach failed");
828
/* Get size as seen by block device. */
829
sectors = blk_size(lodev) / kSectorSize;
831
ERROR("Failed to read device size");
835
/* Mount loopback device with dm-crypt using the encryption key. */
836
INFO("Setting up dm-crypt %s as %s.", lodev, dmcrypt_dev);
837
if (!dm_setup(sectors, encryption_key, dmcrypt_name, lodev,
838
dmcrypt_dev, kCryptAllowDiscard)) {
839
/* If dm_setup() fails, it could be due to lacking
840
* "allow_discard" support, so try again with discard
841
* disabled. There doesn't seem to be a way to query
842
* the kernel for this feature short of a fallible
843
* version test or just trying to set up the dm table
844
* again, so do the latter.
846
if (!dm_setup(sectors, encryption_key, dmcrypt_name, lodev,
847
dmcrypt_dev, !kCryptAllowDiscard)) {
848
ERROR("dm_setup failed");
851
INFO("%s: dm-crypt does not support discard; disabling.",
855
/* Decide now if any migration will happen. If so, we will not
856
* grow the new filesystem in the background, since we need to
857
* copy the contents over before /var is valid again.
861
if (migrate_allowed) {
862
for (bind = bind_mounts; bind->src; ++ bind) {
863
if (migrate_contents(bind, MIGRATE_TEST_ONLY))
868
/* Calculate filesystem min/max size. */
869
blocks_max = sectors / (kExt4BlockSize / kSectorSize);
870
blocks_min = kExt4MinBytes / kExt4BlockSize;
871
if (migrate_needed && migrate_allowed) {
872
uint64_t fs_bytes_min;
873
uint64_t calc_blocks_min;
874
/* When doing a migration, the new filesystem must be
875
* large enough to hold what we're going to migrate.
876
* Instead of walking the bind mount sources, which would
877
* be IO and time expensive, just read the bytes-used
878
* value from statvfs (plus 10% for overhead). It will
879
* be too large, since it includes the eCryptFS data, so
880
* we must cap at the max filesystem size just in case.
883
/* Bytes used in stateful partition plus 10%. */
884
fs_bytes_min = stateful_statbuf.f_blocks -
885
stateful_statbuf.f_bfree;
886
fs_bytes_min *= stateful_statbuf.f_frsize;
887
DEBUG("Stateful bytes used: %" PRIu64 "", fs_bytes_min);
888
fs_bytes_min *= kMigrationSizeMultiplier;
890
/* Minimum blocks needed for that many bytes. */
891
calc_blocks_min = fs_bytes_min / kExt4BlockSize;
892
/* Do not use more than blocks_max. */
893
if (calc_blocks_min > blocks_max)
894
calc_blocks_min = blocks_max;
895
/* Do not use less than blocks_min. */
896
else if (calc_blocks_min < blocks_min)
897
calc_blocks_min = blocks_min;
899
DEBUG("Maximum fs blocks: %" PRIu64 "", blocks_max);
900
DEBUG("Minimum fs blocks: %" PRIu64 "", blocks_min);
901
DEBUG("Migration blocks chosen: %" PRIu64 "", calc_blocks_min);
902
blocks_min = calc_blocks_min;
906
INFO("Building filesystem on %s "
907
"(blocksize:%" PRIu64 ", min:%" PRIu64 ", max:%" PRIu64 ").",
908
dmcrypt_dev, kExt4BlockSize, blocks_min, blocks_max);
909
if (!filesystem_build(dmcrypt_dev, kExt4BlockSize,
910
blocks_min, blocks_max))
914
/* Mount the dm-crypt partition finally. */
915
INFO("Mounting %s onto %s.", dmcrypt_dev, encrypted_mount);
916
if (access(encrypted_mount, R_OK) &&
917
mkdir(encrypted_mount, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) {
921
if (mount(dmcrypt_dev, encrypted_mount, kEncryptedFSType,
922
MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RELATIME,
923
"discard,commit=600")) {
924
PERROR("mount(%s,%s)", dmcrypt_dev, encrypted_mount);
928
/* Always spawn filesystem resizer, in case growth was interrupted. */
929
/* TODO(keescook): if already full size, don't resize. */
930
spawn_resizer(dmcrypt_dev, blocks_min, blocks_max);
932
/* If the legacy lockbox NVRAM area exists, we've rebuilt the
933
* filesystem, and there are old bind sources on disk, attempt
936
if (migrate_needed && migrate_allowed) {
937
/* Migration needs to happen before bind mounting because
938
* some partitions were not already on the stateful partition,
939
* and would be over-mounted by the new bind mount.
941
for (bind = bind_mounts; bind->src; ++ bind)
942
migrate_contents(bind, MIGRATE_FOR_REAL);
945
/* Perform bind mounts. */
946
for (bind = bind_mounts; bind->src; ++ bind) {
947
INFO("Bind mounting %s onto %s.", bind->src, bind->dst);
948
if (check_bind(bind, BIND_SOURCE) ||
949
check_bind(bind, BIND_DEST))
951
if (mount(bind->src, bind->dst, "none", MS_BIND, NULL)) {
952
PERROR("mount(%s,%s)", bind->src, bind->dst);
957
/* When we are creating the encrypted mount for the first time,
958
* either finalize immediately, or write the encryption key to
959
* disk (*sigh*) to handle the seemingly endless broken or
963
/* Devices that already have the NVRAM area populated and
964
* are being rebuilt don't need to wait for Cryptohome
965
* because the NVRAM area isn't going to change.
967
* Devices that do not have the NVRAM area populated
968
* may potentially never have the NVRAM area populated,
969
* which means we have to write the encryption key to
970
* disk until we finalize. Once secure deletion is
971
* supported on ext4, this won't be as horrible.
974
finalize(system_key, encryption_key);
976
needs_finalization(encryption_key);
978
/* If we're not rebuilding and we have a sane system
979
* key, then we must have finalized. Force any required
990
for (bind = bind_mounts; bind->src; ++ bind) {
991
INFO("Unmounting %s.", bind->dst);
995
INFO("Unmounting %s.", encrypted_mount);
996
umount(encrypted_mount);
999
INFO("Removing %s.", dmcrypt_dev);
1000
/* TODO(keescook): something holds this open briefly on mkfs failure
1001
* and I haven't been able to catch it yet. Adding an "fuser" call
1002
* here is sufficient to lose the race. Instead, just sleep during
1006
dm_teardown(dmcrypt_dev);
1009
INFO("Unlooping %s.", lodev);
1018
/* Clean up all bind mounts, mounts, attaches, etc. Only the final
1019
* action informs the return value. This makes it so that failures
1020
* can be cleaned up from, and continue the shutdown process on a
1021
* second call. If the loopback cannot be found, claim success.
1023
static int shutdown(void)
1025
struct bind_mount *bind;
1027
for (bind = bind_mounts; bind->src; ++ bind) {
1028
INFO("Unmounting %s.", bind->dst);
1030
/* Allow either success or a "not mounted" failure. */
1031
if (umount(bind->dst)) {
1032
if (errno != EINVAL) {
1033
PERROR("umount(%s)", bind->dst);
1034
return EXIT_FAILURE;
1039
INFO("Unmounting %s.", encrypted_mount);
1041
/* Allow either success or a "not mounted" failure. */
1042
if (umount(encrypted_mount)) {
1043
if (errno != EINVAL) {
1044
PERROR("umount(%s)", encrypted_mount);
1045
return EXIT_FAILURE;
1049
/* Optionally run fsck on the device after umount. */
1050
if (getenv("MOUNT_ENCRYPTED_FSCK")) {
1053
if (asprintf(&cmd, "fsck -a %s", dmcrypt_dev) == -1)
1060
ERROR("'%s' failed: %d", cmd, rc);
1064
INFO("Removing %s.", dmcrypt_dev);
1065
if (!dm_teardown(dmcrypt_dev))
1066
ERROR("dm_teardown(%s)", dmcrypt_dev);
1068
INFO("Unlooping %s (named %s).", block_path, dmcrypt_name);
1069
if (!loop_detach_name(dmcrypt_name)) {
1070
ERROR("loop_detach_name(%s)", dmcrypt_name);
1071
return EXIT_FAILURE;
1073
return EXIT_SUCCESS;
1076
static void check_mount_states(void)
1078
struct bind_mount *bind;
1080
/* Verify stateful partition exists. */
1081
if (access(stateful_mount, R_OK)) {
1082
INFO("%s does not exist.", stateful_mount);
1085
/* Verify stateful is either a separate mount, or that the
1086
* root directory is writable (i.e. a factory install, dev mode
1087
* where root remounted rw, etc).
1089
if (same_vfs(stateful_mount, rootdir) && access(rootdir, W_OK)) {
1090
INFO("%s is not mounted.", stateful_mount);
1094
/* Verify encrypted partition is missing or not already mounted. */
1095
if (access(encrypted_mount, R_OK) == 0 &&
1096
!same_vfs(encrypted_mount, stateful_mount)) {
1097
INFO("%s already appears to be mounted.", encrypted_mount);
1101
/* Verify that bind mount targets exist. */
1102
for (bind = bind_mounts; bind->src; ++ bind) {
1103
if (access(bind->dst, R_OK)) {
1104
PERROR("%s mount point is missing.", bind->dst);
1109
/* Verify that old bind mounts on stateful haven't happened yet. */
1110
for (bind = bind_mounts; bind->src; ++ bind) {
1114
if (same_vfs(bind->dst, stateful_mount)) {
1115
INFO("%s already bind mounted.", bind->dst);
1120
INFO("VFS mount state sanity check ok.");
1123
static int report_info(void)
1125
uint8_t system_key[DIGEST_LENGTH];
1127
struct bind_mount *mnt;
1130
printf("TPM: %s\n", has_tpm ? "yes" : "no");
1132
printf("TPM Owned: %s\n", tpm_owned(&owned) != TPM_SUCCESS ?
1133
"fail" : (owned ? "yes" : "no"));
1135
printf("ChromeOS: %s\n", has_chromefw() ? "yes" : "no");
1136
printf("CR48: %s\n", is_cr48() ? "yes" : "no");
1137
if (has_chromefw()) {
1139
rc = get_nvram_key(system_key, &migrate);
1141
printf("NVRAM: missing.\n");
1143
printf("NVRAM: %s, %s.\n",
1144
migrate ? "legacy" : "modern",
1145
rc ? "available" : "ignored");
1149
printf("NVRAM: not present\n");
1152
printf("rootdir: %s\n", rootdir);
1153
printf("stateful_mount: %s\n", stateful_mount);
1154
printf("key_path: %s\n", key_path);
1155
printf("block_path: %s\n", block_path);
1156
printf("encrypted_mount: %s\n", encrypted_mount);
1157
printf("dmcrypt_name: %s\n", dmcrypt_name);
1158
printf("dmcrypt_dev: %s\n", dmcrypt_dev);
1159
printf("bind mounts:\n");
1160
for (mnt = bind_mounts; mnt->src; ++mnt) {
1161
printf("\tsrc:%s\n", mnt->src);
1162
printf("\tdst:%s\n", mnt->dst);
1163
printf("\tprevious:%s\n", mnt->previous);
1164
printf("\tpending:%s\n", mnt->pending);
1165
printf("\towner:%s\n", mnt->owner);
1166
printf("\tmode:%o\n", mnt->mode);
1167
printf("\tsubmount:%d\n", mnt->submount);
1171
return EXIT_SUCCESS;
1174
/* This expects "mnt" to be allocated and initialized to NULL bytes. */
1175
static int dup_bind_mount(struct bind_mount *mnt, struct bind_mount *old,
1178
if (old->src && asprintf(&mnt->src, "%s%s", dir, old->src) == -1)
1180
if (old->dst && asprintf(&mnt->dst, "%s%s", dir, old->dst) == -1)
1182
if (old->previous && asprintf(&mnt->previous, "%s%s", dir,
1183
old->previous) == -1)
1185
if (old->pending && asprintf(&mnt->pending, "%s%s", dir,
1186
old->pending) == -1)
1188
if (!(mnt->owner = strdup(old->owner)))
1190
if (!(mnt->group = strdup(old->group)))
1192
mnt->mode = old->mode;
1193
mnt->submount = old->submount;
1198
perror(__FUNCTION__);
1202
static void prepare_paths(void)
1205
struct bind_mount *old;
1206
struct bind_mount *mnt;
1208
mnt = bind_mounts = calloc(sizeof(bind_mounts_default) /
1209
sizeof(*bind_mounts_default),
1210
sizeof(*bind_mounts_default));
1216
if ((dir = getenv("MOUNT_ENCRYPTED_ROOT")) != NULL) {
1217
unsigned char digest[DIGEST_LENGTH];
1220
if (asprintf(&rootdir, "%s/", dir) == -1)
1223
/* Generate a shortened hash for non-default cryptnames,
1224
* which will get re-used in the loopback name, which
1225
* must be less than 64 (LO_NAME_SIZE) bytes. */
1226
sha256(dir, digest);
1227
hex = stringify_hex(digest, sizeof(digest));
1229
if (asprintf(&dmcrypt_name, "%s_%s", kCryptDevName,
1235
if (!(dmcrypt_name = strdup(kCryptDevName)))
1239
if (asprintf(&stateful_mount, "%s%s", rootdir, STATEFUL_MNT) == -1)
1241
if (asprintf(&key_path, "%s%s", rootdir,
1242
STATEFUL_MNT "/encrypted.key") == -1)
1244
if (asprintf(&needs_finalization_path, "%s%s", rootdir,
1245
STATEFUL_MNT "/encrypted.needs-finalization") == -1)
1247
if (asprintf(&block_path, "%s%s", rootdir,
1248
STATEFUL_MNT "/encrypted.block") == -1)
1250
if (asprintf(&encrypted_mount, "%s%s", rootdir, ENCRYPTED_MNT) == -1)
1252
if (asprintf(&dmcrypt_dev, "/dev/mapper/%s", dmcrypt_name) == -1)
1255
for (old = bind_mounts_default; old->src; ++old) {
1256
if (dup_bind_mount(mnt++, old, rootdir))
1267
int main(int argc, char *argv[])
1270
int mode = kModeProduction;
1272
INFO_INIT("Starting.");
1276
if (!strcmp(argv[1], "umount"))
1278
else if (!strcmp(argv[1], "info"))
1279
return report_info();
1280
else if (!strcmp(argv[1], "finalize"))
1281
return finalize_from_cmdline(argc > 2 ? argv[2] : NULL);
1282
else if (!strcmp(argv[1], "factory"))
1283
mode = kModeFactory;
1286
"Usage: %s [info|finalize|umount|factory]\n",
1292
check_mount_states();
1294
okay = setup_encrypted(mode);
1295
/* If we fail, let chromeos_startup handle the stateful wipe. */
1299
/* Continue boot. */
1300
return okay ? EXIT_SUCCESS : EXIT_FAILURE;