~ubuntu-branches/ubuntu/trusty/vboot-utils/trusty

« back to all changes in this revision

Viewing changes to utility/mount-encrypted.c

  • Committer: Package Import Robot
  • Author(s): Antonio Terceiro
  • Date: 2012-12-16 11:03:40 UTC
  • Revision ID: package-import@ubuntu.com-20121216110340-f7wcseecbc9jed5l
Tags: upstream-0~20121212
ImportĀ upstreamĀ versionĀ 0~20121212

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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.
 
4
 *
 
5
 * This tool will attempt to mount or create the encrypted stateful partition,
 
6
 * and the various bind mountable subdirectories.
 
7
 *
 
8
 */
 
9
#define _GNU_SOURCE
 
10
#define _FILE_OFFSET_BITS 64
 
11
#include <stdint.h>
 
12
#include <stdio.h>
 
13
#include <stdlib.h>
 
14
#include <unistd.h>
 
15
#include <string.h>
 
16
#include <errno.h>
 
17
#include <fcntl.h>
 
18
#include <inttypes.h>
 
19
#include <grp.h>
 
20
#include <pwd.h>
 
21
#include <sys/ioctl.h>
 
22
#include <sys/stat.h>
 
23
#include <sys/statvfs.h>
 
24
#include <sys/time.h>
 
25
#include <sys/types.h>
 
26
#include <sys/mount.h>
 
27
#include <linux/fs.h>
 
28
 
 
29
#include <glib.h>
 
30
 
 
31
#include <openssl/rand.h>
 
32
 
 
33
#define CHROMEOS_ENVIRONMENT
 
34
#include "tlcl.h"
 
35
#include "crossystem.h"
 
36
 
 
37
#include "mount-encrypted.h"
 
38
#include "mount-helpers.h"
 
39
 
 
40
#define STATEFUL_MNT "mnt/stateful_partition"
 
41
#define ENCRYPTED_MNT STATEFUL_MNT "/encrypted"
 
42
#define BUF_SIZE 1024
 
43
#define PROP_SIZE 64
 
44
 
 
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;
 
66
 
 
67
enum migration_method {
 
68
        MIGRATE_TEST_ONLY,
 
69
        MIGRATE_FOR_REAL,
 
70
};
 
71
 
 
72
enum bind_dir {
 
73
        BIND_SOURCE,
 
74
        BIND_DEST,
 
75
};
 
76
 
 
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. */
 
82
        char * owner;
 
83
        char * group;
 
84
        mode_t mode;
 
85
        int submount;           /* Submount is bound already. */
 
86
} bind_mounts_default[] = {
 
87
        { ENCRYPTED_MNT "/var", "var",
 
88
          STATEFUL_MNT "/var", STATEFUL_MNT "/.var",
 
89
          "root", "root",
 
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",
 
93
          "chronos", "chronos",
 
94
          S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH, 1 },
 
95
        { },
 
96
};
 
97
 
 
98
#if DEBUG_ENABLED
 
99
struct timeval tick = { };
 
100
struct timeval tick_start = { };
 
101
#endif
 
102
 
 
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;
 
114
 
 
115
static void tpm_init(void)
 
116
{
 
117
        uint32_t result;
 
118
 
 
119
        if (tpm_init_called)
 
120
                return;
 
121
 
 
122
        DEBUG("Opening TPM");
 
123
 
 
124
        setenv("TPM_NO_EXIT", "1", 1);
 
125
        result = TlclLibInit();
 
126
 
 
127
        tpm_init_called = 1;
 
128
        has_tpm = (result == TPM_SUCCESS);
 
129
        INFO("TPM %s", has_tpm ? "ready" : "not available");
 
130
}
 
131
 
 
132
/* Returns TPM result status code, and on TPM_SUCCESS, stores ownership
 
133
 * flag to "owned".
 
134
 */
 
135
static uint32_t tpm_owned(uint8_t *owned)
 
136
{
 
137
        uint32_t result;
 
138
 
 
139
        tpm_init();
 
140
        DEBUG("Reading TPM Ownership Flag");
 
141
        if (!has_tpm)
 
142
                result = TPM_E_NO_DEVICE;
 
143
        else
 
144
                result = TlclGetOwnership(owned);
 
145
        DEBUG("TPM Ownership Flag returned: %s", result ? "FAIL" : "ok");
 
146
 
 
147
        return result;
 
148
}
 
149
 
 
150
static void tpm_close(void)
 
151
{
 
152
        if (!has_tpm || !tpm_init_called)
 
153
                return;
 
154
        TlclLibClose();
 
155
        tpm_init_called = 0;
 
156
}
 
157
 
 
158
static void sha256(char *string, uint8_t *digest)
 
159
{
 
160
        SHA256((unsigned char *)string, strlen(string), digest);
 
161
}
 
162
 
 
163
/* Extract the desired system key from the kernel's boot command line. */
 
164
static int get_key_from_cmdline(uint8_t *digest)
 
165
{
 
166
        int result = 0;
 
167
        gchar *buffer;
 
168
        gsize length;
 
169
        char *cmdline, *option_end;
 
170
        /* Option name without the leading space. */
 
171
        const gchar *option = kKernelCmdlineOption + 1;
 
172
 
 
173
        if (!g_file_get_contents(kKernelCmdline, &buffer, &length, NULL)) {
 
174
                PERROR(kKernelCmdline);
 
175
                return 0;
 
176
        }
 
177
 
 
178
        /* Find a string match either at start of string or following
 
179
         * a space.
 
180
         */
 
181
        cmdline = buffer;
 
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, ' ');
 
188
                *option_end = '\0';
 
189
                sha256(cmdline, digest);
 
190
                debug_dump_hex("system key", digest, DIGEST_LENGTH);
 
191
                result = 1;
 
192
        }
 
193
 
 
194
        g_free(buffer);
 
195
        return result;
 
196
}
 
197
 
 
198
static int get_system_property(const char *prop, char *buf, size_t length)
 
199
{
 
200
        const char *rc;
 
201
 
 
202
        DEBUG("Fetching System Property '%s'", prop);
 
203
        rc = VbGetSystemPropertyString(prop, buf, length);
 
204
        DEBUG("Got System Property 'mainfw_type': %s", rc ? buf : "FAIL");
 
205
 
 
206
        return rc != NULL;
 
207
}
 
208
 
 
209
static int has_chromefw(void)
 
210
{
 
211
        static int state = -1;
 
212
        char fw[PROP_SIZE];
 
213
 
 
214
        /* Cache the state so we don't have to perform the query again. */
 
215
        if (state != -1)
 
216
                return state;
 
217
 
 
218
        if (!get_system_property("mainfw_type", fw, sizeof(fw)))
 
219
                state = 0;
 
220
        else
 
221
                state = strcmp(fw, "nonchrome") != 0;
 
222
        return state;
 
223
}
 
224
 
 
225
static int is_cr48(void)
 
226
{
 
227
        static int state = -1;
 
228
        char hwid[PROP_SIZE];
 
229
 
 
230
        /* Cache the state so we don't have to perform the query again. */
 
231
        if (state != -1)
 
232
                return state;
 
233
 
 
234
        if (!get_system_property("hwid", hwid, sizeof(hwid)))
 
235
                state = 0;
 
236
        else
 
237
                state = strstr(hwid, "MARIO") != NULL;
 
238
        return state;
 
239
}
 
240
 
 
241
static uint32_t
 
242
_read_nvram(uint8_t *buffer, size_t len, uint32_t index, uint32_t size)
 
243
{
 
244
        uint32_t result;
 
245
 
 
246
        if (size > len) {
 
247
                ERROR("NVRAM size (0x%x > 0x%zx) is too big", size, len);
 
248
                return 0;
 
249
        }
 
250
 
 
251
        tpm_init();
 
252
        DEBUG("Reading NVRAM area 0x%x (size %u)", index, size);
 
253
        if (!has_tpm)
 
254
                result = TPM_E_NO_DEVICE;
 
255
        else
 
256
                result = TlclRead(index, buffer, size);
 
257
        DEBUG("NVRAM read returned: %s", result == TPM_SUCCESS ? "ok"
 
258
                                                               : "FAIL");
 
259
 
 
260
        return result;
 
261
}
 
262
 
 
263
/*
 
264
 * TPM cases:
 
265
 *  - does not exist at all (disabled in test firmware or non-chrome device).
 
266
 *  - exists (below).
 
267
 *
 
268
 * TPM ownership cases:
 
269
 *  - unowned (OOBE):
 
270
 *    - expect modern lockbox (no migration allowed).
 
271
 *  - owned: depends on NVRAM area (below).
 
272
 *
 
273
 * NVRAM area cases:
 
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.
 
285
 *
 
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
 
292
 */
 
293
static int get_nvram_key(uint8_t *digest, int *migrate)
 
294
{
 
295
        uint8_t owned = 0;
 
296
        uint8_t value[kLockboxSizeV2], bytes_anded, bytes_ored;
 
297
        uint32_t size, result, i;
 
298
        uint8_t *rand_bytes;
 
299
        uint32_t rand_size;
 
300
 
 
301
        /* Default to allowing migration (disallow when owned with NVRAMv2). */
 
302
        *migrate = 1;
 
303
 
 
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.",
 
308
                     result);
 
309
                return 0;
 
310
        }
 
311
        if (!owned) {
 
312
                INFO("TPM not Owned, ignoring NVRAM area.");
 
313
                return 0;
 
314
        }
 
315
 
 
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
 
322
         * query NVRAM size).
 
323
         */
 
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);
 
332
                        return 0;
 
333
                }
 
334
                /* Legacy NVRAM area. */
 
335
                INFO("Version 1 NVRAM area found.");
 
336
        } else {
 
337
                *migrate = 0;
 
338
                INFO("Version 2 NVRAM area found.");
 
339
        }
 
340
 
 
341
        debug_dump_hex("nvram", value, size);
 
342
 
 
343
        /* Ignore defined but unwritten NVRAM area. */
 
344
        bytes_ored = 0x0;
 
345
        bytes_anded = 0xff;
 
346
        for (i = 0; i < size; ++i) {
 
347
                bytes_ored |= value[i];
 
348
                bytes_anded &= value[i];
 
349
        }
 
350
        if (bytes_ored == 0x0 || bytes_anded == 0xff) {
 
351
                INFO("NVRAM area has been defined but not written.");
 
352
                return 0;
 
353
        }
 
354
 
 
355
        /* Choose random bytes to use based on NVRAM version. */
 
356
        if (*migrate) {
 
357
                rand_bytes = value;
 
358
                rand_size = size;
 
359
        } else {
 
360
                rand_bytes = value + kLockboxSaltOffset;
 
361
                if (kLockboxSaltOffset + DIGEST_LENGTH > size) {
 
362
                        INFO("Impossibly small NVRAM area size (%d).", size);
 
363
                        return 0;
 
364
                }
 
365
                rand_size = DIGEST_LENGTH;
 
366
        }
 
367
        if (rand_size < DIGEST_LENGTH) {
 
368
                INFO("Impossibly small rand_size (%d).", rand_size);
 
369
                return 0;
 
370
        }
 
371
        debug_dump_hex("rand_bytes", rand_bytes, rand_size);
 
372
 
 
373
        SHA256(rand_bytes, rand_size, digest);
 
374
        debug_dump_hex("system key", digest, DIGEST_LENGTH);
 
375
 
 
376
        return 1;
 
377
}
 
378
 
 
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.
 
383
 */
 
384
static int find_system_key(int mode, uint8_t *digest, int *migration_allowed)
 
385
{
 
386
        gchar *key;
 
387
        gsize length;
 
388
 
 
389
        /* By default, do not allow migration. */
 
390
        *migration_allowed = 0;
 
391
 
 
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);
 
397
                return 1;
 
398
        }
 
399
 
 
400
        /* Force ChromeOS devices into requiring the system key come from
 
401
         * NVRAM.
 
402
         */
 
403
        if (has_chromefw()) {
 
404
                int rc;
 
405
                rc = get_nvram_key(digest, migration_allowed);
 
406
 
 
407
                if (rc) {
 
408
                        INFO("Using NVRAM as system key; already populated%s.",
 
409
                                *migration_allowed ? " (legacy)" : "");
 
410
                } else {
 
411
                        INFO("Using NVRAM as system key; finalization needed.");
 
412
                }
 
413
                return rc;
 
414
        }
 
415
 
 
416
        if (get_key_from_cmdline(digest)) {
 
417
                INFO("Using kernel command line argument as system key.");
 
418
                return 1;
 
419
        }
 
420
        if (g_file_get_contents("/sys/class/dmi/id/product_uuid",
 
421
                                &key, &length, NULL)) {
 
422
                sha256(key, digest);
 
423
                debug_dump_hex("system key", digest, DIGEST_LENGTH);
 
424
                g_free(key);
 
425
                INFO("Using UUID as system key.");
 
426
                return 1;
 
427
        }
 
428
 
 
429
        INFO("Using default insecure system key.");
 
430
        sha256((char *)kStaticKeyDefault, digest);
 
431
        debug_dump_hex("system key", digest, DIGEST_LENGTH);
 
432
        return 1;
 
433
}
 
434
 
 
435
/* Returns 1 on success, 0 on failure. */
 
436
static int get_random_bytes_tpm(unsigned char *buffer, int wanted)
 
437
{
 
438
        uint32_t remaining = wanted;
 
439
 
 
440
        tpm_init();
 
441
        /* Read random bytes from TPM, which can return short reads. */
 
442
        while (remaining) {
 
443
                uint32_t result, size;
 
444
 
 
445
                result = TlclGetRandom(buffer + (wanted - remaining),
 
446
                                       remaining, &size);
 
447
                if (result != TPM_SUCCESS || size > remaining) {
 
448
                        ERROR("TPM GetRandom failed: error 0x%02x.", result);
 
449
                        return 0;
 
450
                }
 
451
                remaining -= size;
 
452
        }
 
453
 
 
454
        return 1;
 
455
}
 
456
 
 
457
/* Returns 1 on success, 0 on failure. */
 
458
static int get_random_bytes(unsigned char *buffer, int wanted)
 
459
{
 
460
        if (has_tpm && get_random_bytes_tpm(buffer, wanted))
 
461
                return 1;
 
462
 
 
463
        if (RAND_bytes(buffer, wanted))
 
464
                return 1;
 
465
        SSL_ERROR("RAND_bytes");
 
466
 
 
467
        return 0;
 
468
}
 
469
 
 
470
static char *choose_encryption_key(void)
 
471
{
 
472
        unsigned char rand_bytes[DIGEST_LENGTH];
 
473
        unsigned char digest[DIGEST_LENGTH];
 
474
 
 
475
        if (!get_random_bytes(rand_bytes, sizeof(rand_bytes)))
 
476
                ERROR("No entropy source found -- using uninitialized stack");
 
477
 
 
478
        SHA256(rand_bytes, DIGEST_LENGTH, digest);
 
479
        debug_dump_hex("encryption key", digest, DIGEST_LENGTH);
 
480
 
 
481
        return stringify_hex(digest, DIGEST_LENGTH);
 
482
}
 
483
 
 
484
static int check_bind(struct bind_mount *bind, enum bind_dir dir)
 
485
{
 
486
        struct passwd *user;
 
487
        struct group *group;
 
488
        const gchar *target;
 
489
 
 
490
        if (dir == BIND_SOURCE)
 
491
                target = bind->src;
 
492
        else
 
493
                target = bind->dst;
 
494
 
 
495
        if (access(target, R_OK) && mkdir(target, bind->mode)) {
 
496
                PERROR("mkdir(%s)", target);
 
497
                return -1;
 
498
        }
 
499
 
 
500
        /* Destination may be on read-only filesystem, so skip tweaks. */
 
501
        if (dir == BIND_DEST)
 
502
                return 0;
 
503
 
 
504
        if (!(user = getpwnam(bind->owner))) {
 
505
                PERROR("getpwnam(%s)", bind->owner);
 
506
                return -1;
 
507
        }
 
508
        if (!(group = getgrnam(bind->group))) {
 
509
                PERROR("getgrnam(%s)", bind->group);
 
510
                return -1;
 
511
        }
 
512
 
 
513
        /* Must do explicit chmod since mkdir()'s mode respects umask. */
 
514
        if (chmod(target, bind->mode)) {
 
515
                PERROR("chmod(%s)", target);
 
516
                return -1;
 
517
        }
 
518
        if (chown(target, user->pw_uid, group->gr_gid)) {
 
519
                PERROR("chown(%s)", target);
 
520
                return -1;
 
521
        }
 
522
 
 
523
        return 0;
 
524
}
 
525
 
 
526
static int migrate_contents(struct bind_mount *bind,
 
527
                            enum migration_method method)
 
528
{
 
529
        const gchar *previous = NULL;
 
530
        const gchar *pending = NULL;
 
531
        gchar *dotdir;
 
532
 
 
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)
 
539
                return 0;
 
540
 
 
541
        /* Pretend migration happened. */
 
542
        if (method == MIGRATE_TEST_ONLY)
 
543
                return 1;
 
544
 
 
545
        check_bind(bind, BIND_SOURCE);
 
546
 
 
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;
 
551
        }
 
552
 
 
553
        INFO("Migrating bind mount contents %s to %s.", dotdir, bind->src);
 
554
        const gchar *cp[] = {
 
555
                "/bin/cp", "-a",
 
556
                dotdir,
 
557
                bind->src,
 
558
                NULL
 
559
        };
 
560
 
 
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
 
565
                 * as well.
 
566
                 */
 
567
                INFO("Failed to migrate %s to %s!", dotdir, bind->src);
 
568
                remove_tree(bind->src);
 
569
                check_bind(bind, BIND_SOURCE);
 
570
        }
 
571
 
 
572
mark_for_removal:
 
573
        g_free(dotdir);
 
574
 
 
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).
 
579
         */
 
580
 
 
581
        if (previous) {
 
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
 
585
                 * later.
 
586
                 */
 
587
                if (pending)
 
588
                        remove_tree(pending);
 
589
                if (rename(previous, bind->pending)) {
 
590
                        PERROR("rename(%s,%s)", previous, bind->pending);
 
591
                }
 
592
        }
 
593
 
 
594
        /* As noted above, failures are unrecoverable, so getting here means
 
595
         * "we're done" more than "it worked".
 
596
         */
 
597
        return 1;
 
598
}
 
599
 
 
600
static void finalized(void)
 
601
{
 
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);
 
607
        }
 
608
}
 
609
 
 
610
static void finalize(uint8_t *system_key, char *encryption_key)
 
611
{
 
612
        struct bind_mount *bind;
 
613
 
 
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);
 
617
                return;
 
618
        }
 
619
 
 
620
        finalized();
 
621
 
 
622
        for (bind = bind_mounts; bind->src; ++ bind) {
 
623
                if (!bind->pending || access(bind->pending, R_OK))
 
624
                        continue;
 
625
                INFO("Removing %s.", bind->pending);
 
626
#if DEBUG_ENABLED
 
627
                continue;
 
628
#endif
 
629
                remove_tree(bind->pending);
 
630
        }
 
631
}
 
632
 
 
633
static void needs_finalization(char *encryption_key)
 
634
{
 
635
        uint8_t useless_key[DIGEST_LENGTH];
 
636
        sha256((char *)kStaticKeyFinalizationNeeded, useless_key);
 
637
 
 
638
        INFO("Writing finalization intent %s.", needs_finalization_path);
 
639
        if (!keyfile_write(needs_finalization_path, useless_key,
 
640
                           encryption_key)) {
 
641
                ERROR("Failed to write %s -- aborting.",
 
642
                      needs_finalization_path);
 
643
                return;
 
644
        }
 
645
}
 
646
 
 
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.
 
651
 */
 
652
static int finalize_from_cmdline(char *key)
 
653
{
 
654
        uint8_t system_key[DIGEST_LENGTH];
 
655
        char *encryption_key;
 
656
        int migrate;
 
657
 
 
658
        /* Early sanity-check to see if the encrypted device exists,
 
659
         * instead of failing at the end of this function.
 
660
         */
 
661
        if (access(dmcrypt_dev, R_OK)) {
 
662
                ERROR("'%s' does not exist, giving up.", dmcrypt_dev);
 
663
                return EXIT_FAILURE;
 
664
        }
 
665
 
 
666
        if (key) {
 
667
                if (strlen(key) != 2 * DIGEST_LENGTH) {
 
668
                        ERROR("Invalid key length.");
 
669
                        return EXIT_FAILURE;
 
670
                }
 
671
 
 
672
                if (!hexify_string(key, system_key, DIGEST_LENGTH)) {
 
673
                        ERROR("Failed to convert hex string to byte array");
 
674
                        return EXIT_FAILURE;
 
675
                }
 
676
        } else {
 
677
                /* Factory mode will never call finalize from the command
 
678
                 * line, so force Production mode here.
 
679
                 */
 
680
                if (!find_system_key(kModeProduction, system_key, &migrate)) {
 
681
                        ERROR("Could not locate system key.");
 
682
                        return EXIT_FAILURE;
 
683
                }
 
684
        }
 
685
 
 
686
        encryption_key = dm_get_key(dmcrypt_dev);
 
687
        if (!encryption_key) {
 
688
                ERROR("Could not locate encryption key for %s.", dmcrypt_dev);
 
689
                return EXIT_FAILURE;
 
690
        }
 
691
 
 
692
        finalize(system_key, encryption_key);
 
693
 
 
694
        return EXIT_SUCCESS;
 
695
}
 
696
 
 
697
static void spawn_resizer(const char *device, uint64_t blocks,
 
698
                          uint64_t blocks_max)
 
699
{
 
700
        pid_t pid;
 
701
 
 
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,
 
705
                     blocks, blocks_max);
 
706
                return;
 
707
        }
 
708
 
 
709
        fflush(NULL);
 
710
        pid = fork();
 
711
        if (pid < 0) {
 
712
                PERROR("fork");
 
713
                return;
 
714
        }
 
715
        if (pid != 0) {
 
716
                INFO("Started filesystem resizing process %d.", pid);
 
717
                return;
 
718
        }
 
719
 
 
720
        /* Child */
 
721
        tpm_close();
 
722
        INFO_INIT("Resizer spawned.");
 
723
 
 
724
        if (daemon(0, 1)) {
 
725
                PERROR("daemon");
 
726
                goto out;
 
727
        }
 
728
 
 
729
        filesystem_resize(device, blocks, blocks_max);
 
730
 
 
731
out:
 
732
        INFO_DONE("Done.");
 
733
        exit(0);
 
734
}
 
735
 
 
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
 
738
 * come from.
 
739
 */
 
740
static int setup_encrypted(int mode)
 
741
{
 
742
        int has_system_key;
 
743
        uint8_t system_key[DIGEST_LENGTH];
 
744
        char *encryption_key = NULL;
 
745
        int migrate_allowed = 0, migrate_needed = 0, rebuild = 0;
 
746
        gchar *lodev = NULL;
 
747
        uint64_t sectors;
 
748
        struct bind_mount *bind;
 
749
        int sparsefd;
 
750
        struct statvfs stateful_statbuf;
 
751
        uint64_t blocks_min, blocks_max;
 
752
 
 
753
        /* Use the "system key" to decrypt the "encryption key" stored in
 
754
         * the stateful partition.
 
755
         */
 
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);
 
759
        } else {
 
760
                INFO("No usable system key found.");
 
761
        }
 
762
 
 
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.
 
767
                 */
 
768
                migrate_allowed = 0;
 
769
        } else {
 
770
                uint8_t useless_key[DIGEST_LENGTH];
 
771
                sha256((char *)kStaticKeyFinalizationNeeded, useless_key);
 
772
                encryption_key = keyfile_read(needs_finalization_path,
 
773
                                              useless_key);
 
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();
 
778
                        if (!encryption_key)
 
779
                                return 0;
 
780
                        rebuild = 1;
 
781
                } else {
 
782
                        ERROR("Finalization unfinished! " \
 
783
                              "Encryption key still on disk!");
 
784
                }
 
785
        }
 
786
 
 
787
        if (rebuild) {
 
788
                uint64_t fs_bytes_max;
 
789
 
 
790
                /* Wipe out the old files, and ignore errors. */
 
791
                unlink(key_path);
 
792
                unlink(block_path);
 
793
 
 
794
                /* Calculate the desired size of the new partition. */
 
795
                if (statvfs(stateful_mount, &stateful_statbuf)) {
 
796
                        PERROR(stateful_mount);
 
797
                        return 0;
 
798
                }
 
799
                fs_bytes_max = stateful_statbuf.f_blocks;
 
800
                fs_bytes_max *= kSizePercent;
 
801
                fs_bytes_max *= stateful_statbuf.f_frsize;
 
802
 
 
803
                INFO("Creating sparse backing file with size %" PRIu64 ".",
 
804
                     fs_bytes_max);
 
805
 
 
806
                /* Create the sparse file. */
 
807
                sparsefd = sparse_create(block_path, fs_bytes_max);
 
808
                if (sparsefd < 0) {
 
809
                        PERROR(block_path);
 
810
                        return 0;
 
811
                }
 
812
        } else {
 
813
                sparsefd = open(block_path, O_RDWR | O_NOFOLLOW);
 
814
                if (sparsefd < 0) {
 
815
                        PERROR(block_path);
 
816
                        return 0;
 
817
                }
 
818
        }
 
819
 
 
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");
 
825
                goto failed;
 
826
        }
 
827
 
 
828
        /* Get size as seen by block device. */
 
829
        sectors = blk_size(lodev) / kSectorSize;
 
830
        if (!sectors) {
 
831
                ERROR("Failed to read device size");
 
832
                goto lo_cleanup;
 
833
        }
 
834
 
 
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.
 
845
                 */
 
846
                if (!dm_setup(sectors, encryption_key, dmcrypt_name, lodev,
 
847
                              dmcrypt_dev, !kCryptAllowDiscard)) {
 
848
                        ERROR("dm_setup failed");
 
849
                        goto lo_cleanup;
 
850
                }
 
851
                INFO("%s: dm-crypt does not support discard; disabling.",
 
852
                     dmcrypt_dev);
 
853
        }
 
854
 
 
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.
 
858
         */
 
859
        if (!rebuild)
 
860
                migrate_allowed = 0;
 
861
        if (migrate_allowed) {
 
862
                for (bind = bind_mounts; bind->src; ++ bind) {
 
863
                        if (migrate_contents(bind, MIGRATE_TEST_ONLY))
 
864
                                migrate_needed = 1;
 
865
                }
 
866
        }
 
867
 
 
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.
 
881
                 */
 
882
 
 
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;
 
889
 
 
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;
 
898
 
 
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;
 
903
        }
 
904
 
 
905
        if (rebuild) {
 
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))
 
911
                        goto dm_cleanup;
 
912
        }
 
913
 
 
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)) {
 
918
                PERROR(dmcrypt_dev);
 
919
                goto dm_cleanup;
 
920
        }
 
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);
 
925
                goto dm_cleanup;
 
926
        }
 
927
 
 
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);
 
931
 
 
932
        /* If the legacy lockbox NVRAM area exists, we've rebuilt the
 
933
         * filesystem, and there are old bind sources on disk, attempt
 
934
         * migration.
 
935
         */
 
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.
 
940
                 */
 
941
                for (bind = bind_mounts; bind->src; ++ bind)
 
942
                        migrate_contents(bind, MIGRATE_FOR_REAL);
 
943
        }
 
944
 
 
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))
 
950
                        goto unbind;
 
951
                if (mount(bind->src, bind->dst, "none", MS_BIND, NULL)) {
 
952
                        PERROR("mount(%s,%s)", bind->src, bind->dst);
 
953
                        goto unbind;
 
954
                }
 
955
        }
 
956
 
 
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
 
960
         * wedged TPM states.
 
961
         */
 
962
        if (rebuild) {
 
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.
 
966
                 *
 
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.
 
972
                 */
 
973
                if (has_system_key)
 
974
                        finalize(system_key, encryption_key);
 
975
                else
 
976
                        needs_finalization(encryption_key);
 
977
        } else {
 
978
                /* If we're not rebuilding and we have a sane system
 
979
                 * key, then we must have finalized. Force any required
 
980
                 * clean up.
 
981
                 */
 
982
                if (has_system_key)
 
983
                        finalized();
 
984
        }
 
985
 
 
986
        free(lodev);
 
987
        return 1;
 
988
 
 
989
unbind:
 
990
        for (bind = bind_mounts; bind->src; ++ bind) {
 
991
                INFO("Unmounting %s.", bind->dst);
 
992
                umount(bind->dst);
 
993
        }
 
994
 
 
995
        INFO("Unmounting %s.", encrypted_mount);
 
996
        umount(encrypted_mount);
 
997
 
 
998
dm_cleanup:
 
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
 
1003
         * the error path.
 
1004
         */
 
1005
        sleep(1);
 
1006
        dm_teardown(dmcrypt_dev);
 
1007
 
 
1008
lo_cleanup:
 
1009
        INFO("Unlooping %s.", lodev);
 
1010
        loop_detach(lodev);
 
1011
 
 
1012
failed:
 
1013
        free(lodev);
 
1014
 
 
1015
        return 0;
 
1016
}
 
1017
 
 
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.
 
1022
 */
 
1023
static int shutdown(void)
 
1024
{
 
1025
        struct bind_mount *bind;
 
1026
 
 
1027
        for (bind = bind_mounts; bind->src; ++ bind) {
 
1028
                INFO("Unmounting %s.", bind->dst);
 
1029
                errno = 0;
 
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;
 
1035
                        }
 
1036
                }
 
1037
        }
 
1038
 
 
1039
        INFO("Unmounting %s.", encrypted_mount);
 
1040
        errno = 0;
 
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;
 
1046
                }
 
1047
        }
 
1048
 
 
1049
        /* Optionally run fsck on the device after umount. */
 
1050
        if (getenv("MOUNT_ENCRYPTED_FSCK")) {
 
1051
                char *cmd;
 
1052
 
 
1053
                if (asprintf(&cmd, "fsck -a %s", dmcrypt_dev) == -1)
 
1054
                        PERROR("asprintf");
 
1055
                else {
 
1056
                        int rc;
 
1057
 
 
1058
                        rc = system(cmd);
 
1059
                        if (rc != 0)
 
1060
                                ERROR("'%s' failed: %d", cmd, rc);
 
1061
                }
 
1062
        }
 
1063
 
 
1064
        INFO("Removing %s.", dmcrypt_dev);
 
1065
        if (!dm_teardown(dmcrypt_dev))
 
1066
                ERROR("dm_teardown(%s)", dmcrypt_dev);
 
1067
 
 
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;
 
1072
        }
 
1073
        return EXIT_SUCCESS;
 
1074
}
 
1075
 
 
1076
static void check_mount_states(void)
 
1077
{
 
1078
        struct bind_mount *bind;
 
1079
 
 
1080
        /* Verify stateful partition exists. */
 
1081
        if (access(stateful_mount, R_OK)) {
 
1082
                INFO("%s does not exist.", stateful_mount);
 
1083
                exit(1);
 
1084
        }
 
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).
 
1088
         */
 
1089
        if (same_vfs(stateful_mount, rootdir) && access(rootdir, W_OK)) {
 
1090
                INFO("%s is not mounted.", stateful_mount);
 
1091
                exit(1);
 
1092
        }
 
1093
 
 
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);
 
1098
                exit(0);
 
1099
        }
 
1100
 
 
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);
 
1105
                        exit(1);
 
1106
                }
 
1107
        }
 
1108
 
 
1109
        /* Verify that old bind mounts on stateful haven't happened yet. */
 
1110
        for (bind = bind_mounts; bind->src; ++ bind) {
 
1111
                if (bind->submount)
 
1112
                        continue;
 
1113
 
 
1114
                if (same_vfs(bind->dst, stateful_mount)) {
 
1115
                        INFO("%s already bind mounted.", bind->dst);
 
1116
                        exit(1);
 
1117
                }
 
1118
        }
 
1119
 
 
1120
        INFO("VFS mount state sanity check ok.");
 
1121
}
 
1122
 
 
1123
static int report_info(void)
 
1124
{
 
1125
        uint8_t system_key[DIGEST_LENGTH];
 
1126
        uint8_t owned = 0;
 
1127
        struct bind_mount *mnt;
 
1128
        int migrate = -1;
 
1129
 
 
1130
        printf("TPM: %s\n", has_tpm ? "yes" : "no");
 
1131
        if (has_tpm) {
 
1132
                printf("TPM Owned: %s\n", tpm_owned(&owned) != TPM_SUCCESS ?
 
1133
                        "fail" : (owned ? "yes" : "no"));
 
1134
        }
 
1135
        printf("ChromeOS: %s\n", has_chromefw() ? "yes" : "no");
 
1136
        printf("CR48: %s\n", is_cr48() ? "yes" : "no");
 
1137
        if (has_chromefw()) {
 
1138
                int rc;
 
1139
                rc = get_nvram_key(system_key, &migrate);
 
1140
                if (!rc)
 
1141
                        printf("NVRAM: missing.\n");
 
1142
                else {
 
1143
                        printf("NVRAM: %s, %s.\n",
 
1144
                                migrate ? "legacy" : "modern",
 
1145
                                rc ? "available" : "ignored");
 
1146
                }
 
1147
        }
 
1148
        else {
 
1149
                printf("NVRAM: not present\n");
 
1150
        }
 
1151
 
 
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);
 
1168
                printf("\n");
 
1169
        }
 
1170
 
 
1171
        return EXIT_SUCCESS;
 
1172
}
 
1173
 
 
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,
 
1176
                          char *dir)
 
1177
{
 
1178
        if (old->src && asprintf(&mnt->src, "%s%s", dir, old->src) == -1)
 
1179
                goto fail;
 
1180
        if (old->dst && asprintf(&mnt->dst, "%s%s", dir, old->dst) == -1)
 
1181
                goto fail;
 
1182
        if (old->previous && asprintf(&mnt->previous, "%s%s", dir,
 
1183
                                      old->previous) == -1)
 
1184
                goto fail;
 
1185
        if (old->pending && asprintf(&mnt->pending, "%s%s", dir,
 
1186
                                     old->pending) == -1)
 
1187
                goto fail;
 
1188
        if (!(mnt->owner = strdup(old->owner)))
 
1189
                goto fail;
 
1190
        if (!(mnt->group = strdup(old->group)))
 
1191
                goto fail;
 
1192
        mnt->mode = old->mode;
 
1193
        mnt->submount = old->submount;
 
1194
 
 
1195
        return 0;
 
1196
 
 
1197
fail:
 
1198
        perror(__FUNCTION__);
 
1199
        return 1;
 
1200
}
 
1201
 
 
1202
static void prepare_paths(void)
 
1203
{
 
1204
        char *dir = NULL;
 
1205
        struct bind_mount *old;
 
1206
        struct bind_mount *mnt;
 
1207
 
 
1208
        mnt = bind_mounts = calloc(sizeof(bind_mounts_default) /
 
1209
                                        sizeof(*bind_mounts_default),
 
1210
                                   sizeof(*bind_mounts_default));
 
1211
        if (!mnt) {
 
1212
                perror("calloc");
 
1213
                exit(1);
 
1214
        }
 
1215
 
 
1216
        if ((dir = getenv("MOUNT_ENCRYPTED_ROOT")) != NULL) {
 
1217
                unsigned char digest[DIGEST_LENGTH];
 
1218
                gchar *hex;
 
1219
 
 
1220
                if (asprintf(&rootdir, "%s/", dir) == -1)
 
1221
                        goto fail;
 
1222
 
 
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));
 
1228
                hex[17] = '\0';
 
1229
                if (asprintf(&dmcrypt_name, "%s_%s", kCryptDevName,
 
1230
                                hex) == -1)
 
1231
                        goto fail;
 
1232
                g_free(hex);
 
1233
        } else {
 
1234
                rootdir = "/";
 
1235
                if (!(dmcrypt_name = strdup(kCryptDevName)))
 
1236
                        goto fail;
 
1237
        }
 
1238
 
 
1239
        if (asprintf(&stateful_mount, "%s%s", rootdir, STATEFUL_MNT) == -1)
 
1240
                goto fail;
 
1241
        if (asprintf(&key_path, "%s%s", rootdir,
 
1242
                     STATEFUL_MNT "/encrypted.key") == -1)
 
1243
                goto fail;
 
1244
        if (asprintf(&needs_finalization_path, "%s%s", rootdir,
 
1245
                     STATEFUL_MNT "/encrypted.needs-finalization") == -1)
 
1246
                goto fail;
 
1247
        if (asprintf(&block_path, "%s%s", rootdir,
 
1248
                     STATEFUL_MNT "/encrypted.block") == -1)
 
1249
                goto fail;
 
1250
        if (asprintf(&encrypted_mount, "%s%s", rootdir, ENCRYPTED_MNT) == -1)
 
1251
                goto fail;
 
1252
        if (asprintf(&dmcrypt_dev, "/dev/mapper/%s", dmcrypt_name) == -1)
 
1253
                goto fail;
 
1254
 
 
1255
        for (old = bind_mounts_default; old->src; ++old) {
 
1256
                if (dup_bind_mount(mnt++, old, rootdir))
 
1257
                        exit(1);
 
1258
        }
 
1259
 
 
1260
        return;
 
1261
 
 
1262
fail:
 
1263
        perror("asprintf");
 
1264
        exit(1);
 
1265
}
 
1266
 
 
1267
int main(int argc, char *argv[])
 
1268
{
 
1269
        int okay;
 
1270
        int mode = kModeProduction;
 
1271
 
 
1272
        INFO_INIT("Starting.");
 
1273
        prepare_paths();
 
1274
 
 
1275
        if (argc > 1) {
 
1276
                if (!strcmp(argv[1], "umount"))
 
1277
                        return shutdown();
 
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;
 
1284
                else {
 
1285
                        fprintf(stderr,
 
1286
                                "Usage: %s [info|finalize|umount|factory]\n",
 
1287
                                argv[0]);
 
1288
                        return 1;
 
1289
                }
 
1290
        }
 
1291
 
 
1292
        check_mount_states();
 
1293
 
 
1294
        okay = setup_encrypted(mode);
 
1295
        /* If we fail, let chromeos_startup handle the stateful wipe. */
 
1296
 
 
1297
        INFO_DONE("Done.");
 
1298
 
 
1299
        /* Continue boot. */
 
1300
        return okay ? EXIT_SUCCESS : EXIT_FAILURE;
 
1301
}