Merge branch 'master' into veritysetup
[platform/upstream/cryptsetup.git] / src / veritysetup.c
1 /*
2  * veritysetup - setup cryptographic volumes for dm-verity
3  *
4  * Copyright (C) 2012, Red Hat, Inc. All rights reserved.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * version 2 as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 #define _FILE_OFFSET_BITS       64
21
22 #include "config.h"
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdint.h>
27 #include <stdarg.h>
28 #include <unistd.h>
29 #include <errno.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <sys/ioctl.h>
34 #include <sys/mount.h>
35 #include <arpa/inet.h>
36 #include <popt.h>
37
38 #include "crypto_backend.h"
39
40 #define DEFAULT_BLOCK_SIZE      4096
41 #define DM_VERITY_MAX_LEVELS    63
42
43 #define DEFAULT_SALT_SIZE       32
44 #define MAX_SALT_SIZE           384
45
46 #define MODE_VERIFY     0
47 #define MODE_CREATE     1
48 #define MODE_ACTIVATE   2
49
50 #define MAX_FORMAT_VERSION      1
51
52 static int mode = -1;
53 static int use_superblock = 1;
54
55 static const char *dm_device;
56 static const char *data_device;
57 static const char *hash_device;
58 static const char *hash_algorithm = NULL;
59 static const char *root_hash;
60
61 static int version = -1;
62 static int data_block_size = 0;
63 static int hash_block_size = 0;
64 static char *data_blocks_string = NULL;
65 static long long data_blocks = 0;
66 static char *hash_start_string = NULL;
67 static long long hash_start = 0;
68 static const char *salt_string = NULL;
69
70 static FILE *data_file;
71 static FILE *hash_file;
72
73 static off_t data_file_blocks;
74 static off_t hash_file_blocks;
75 static off_t used_hash_blocks;
76
77 static char *root_hash_bytes;
78 static char *calculated_digest;
79
80 static char *salt_bytes;
81 static unsigned salt_size;
82
83 static unsigned digest_size;
84 static unsigned char digest_size_bits;
85 static unsigned char levels;
86 static unsigned char hash_per_block_bits;
87
88 static off_t hash_level_block[DM_VERITY_MAX_LEVELS];
89 static off_t hash_level_size[DM_VERITY_MAX_LEVELS];
90
91 static off_t superblock_position;
92
93 static int retval = 0;
94
95 static int opt_debug = 0;
96
97 struct superblock {
98         uint8_t signature[8];
99         uint8_t version;
100         uint8_t data_block_bits;
101         uint8_t hash_block_bits;
102         uint8_t pad1[1];
103         uint16_t salt_size;
104         uint8_t pad2[2];
105         uint32_t data_blocks_hi;
106         uint32_t data_blocks_lo;
107         uint8_t algorithm[16];
108         uint8_t salt[MAX_SALT_SIZE];
109         uint8_t pad3[88];
110 };
111
112 #define DM_VERITY_SIGNATURE     "verity\0\0"
113 #define DM_VERITY_VERSION       0
114
115 __attribute__((format(printf, 5, 6)))
116 void logger(struct crypt_device *cd, int level, const char *file,
117            int line, const char *format, ...)
118 {
119         va_list argp;
120         char *target = NULL;
121
122         va_start(argp, format);
123
124         if (vasprintf(&target, format, argp) > 0) {
125                 if (level >= 0) {
126                         printf("%s\n", target);
127                 } else if (opt_debug)
128                         printf("# %s\n", target);
129         }
130
131         va_end(argp);
132         free(target);
133 }
134
135 __attribute__((__noreturn__))
136 static void help(poptContext popt_context,
137                  enum poptCallbackReason reason,
138                  struct poptOption *key,
139                  const char *arg,
140                  void *data)
141 {
142         if (!strcmp(key->longName, "help")) {
143                 poptPrintHelp(popt_context, stdout, 0);
144         } else {
145                 printf("veritysetup");
146                 printf("\n");
147         }
148         exit(0);
149 }
150
151 static struct poptOption popt_help_options[] = {
152         { NULL,                 0,      POPT_ARG_CALLBACK, help, 0, NULL, NULL },
153         { "help",               'h',    POPT_ARG_NONE, NULL, 0, "Show help", NULL },
154         { "version",            0,      POPT_ARG_NONE, NULL, 0, "Show version", NULL },
155         POPT_TABLEEND
156 };
157
158 static struct poptOption popt_options[] = {
159         { NULL,                 '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, NULL, NULL },
160         { "create",             'c',    POPT_ARG_VAL, &mode, MODE_CREATE, "Create hash", NULL },
161         { "verify",             'v',    POPT_ARG_VAL, &mode, MODE_VERIFY, "Verify integrity", NULL },
162         { "activate",           'a',    POPT_ARG_VAL, &mode, MODE_ACTIVATE, "Activate the device", NULL },
163         { "no-superblock",      0,      POPT_ARG_VAL, &use_superblock, 0, "Do not create/use superblock" },
164         { "format",             0,      POPT_ARG_INT, &version, 0, "Format version (1 - normal format, 0 - original Chromium OS format)", "number" },
165         { "data-block-size",    0,      POPT_ARG_INT, &data_block_size, 0, "Block size on the data device", "bytes" },
166         { "hash-block-size",    0,      POPT_ARG_INT, &hash_block_size, 0, "Block size on the hash device", "bytes" },
167         { "data-blocks",        0,      POPT_ARG_STRING, &data_blocks_string, 0, "The number of blocks in the data file", "blocks" },
168         { "hash-start",         0,      POPT_ARG_STRING, &hash_start_string, 0, "Starting block on the hash device", "512-byte sectors" },
169         { "algorithm",          0,      POPT_ARG_STRING, &hash_algorithm, 0, "Hash algorithm (default sha256)", "string" },
170         { "salt",               0,      POPT_ARG_STRING, &salt_string, 0, "Salt", "hex string" },
171         POPT_TABLEEND
172 };
173
174 __attribute__((__format__(__printf__, 1, 2), __noreturn__))
175 static void exit_err(const char *msg, ...)
176 {
177         va_list args;
178         va_start(args, msg);
179         vfprintf(stderr, msg, args);
180         va_end(args);
181         fputc('\n', stderr);
182         exit(2);
183 }
184
185 __attribute__((__noreturn__))
186 static void stream_err(FILE *f, const char *msg)
187 {
188         if (ferror(f)) {
189                 perror(msg);
190                 exit(2);
191         } else if (feof(f)) {
192                 exit_err("eof on %s", msg);
193         } else {
194                 exit_err("unknown error on %s", msg);
195         }
196 }
197
198 static void *xmalloc(size_t s)
199 {
200         void *ptr = malloc(!s ? 1 : s);
201         if (!ptr) exit_err("out of memory");
202         return ptr;
203 }
204
205 static char *xstrdup(const char *str)
206 {
207         return strcpy(xmalloc(strlen(str) + 1), str);
208 }
209
210 static char *xprint(unsigned long long num)
211 {
212         size_t s = snprintf(NULL, 0, "%llu", num);
213         char *p = xmalloc(s + 1);
214         snprintf(p, s + 1, "%llu", num);
215         return p;
216 }
217
218 static char *xhexprint(char *bytes, size_t len)
219 {
220         size_t i;
221         char *p = xmalloc(len * 2 + 1);
222         p[0] = 0;
223         for (i = 0; i < len; i++)
224                 snprintf(p + i * 2, 3, "%02x", bytes[i]);
225         return p;
226 }
227
228 static off_t get_size(FILE *f, const char *name)
229 {
230         struct stat st;
231         int h = fileno(f);
232         if (h < 0) {
233                 perror("fileno");
234                 exit(2);
235         }
236         if (fstat(h, &st)) {
237                 perror("fstat");
238                 exit(2);
239         }
240         if (S_ISREG(st.st_mode)) {
241                 return st.st_size;
242         } else if (S_ISBLK(st.st_mode)) {
243                 unsigned long long size64;
244                 unsigned long sizeul;
245                 if (!ioctl(h, BLKGETSIZE64, &size64)) {
246                         return_size64:
247                         if ((off_t)size64 < 0 || (off_t)size64 != size64) {
248                                 size_overflow:
249                                 exit_err("%s: device size overflow", name);
250                         }
251                         return size64;
252                 }
253                 if (!ioctl(h, BLKGETSIZE, &sizeul)) {
254                         size64 = (unsigned long long)sizeul * 512;
255                         if (size64 / 512 != sizeul) goto size_overflow;
256                         goto return_size64;
257                 }
258                 perror("BLKGETSIZE");
259                 exit(2);
260         } else {
261                 exit_err("%s is not a file or a block device", name);
262         }
263         return -1;      /* never reached, shut up warning */
264 }
265
266 static void block_fseek(FILE *f, off_t block, int block_size)
267 {
268         unsigned long long pos = (unsigned long long)block * block_size;
269         if (pos / block_size != block ||
270             (off_t)pos < 0 ||
271             (off_t)pos != pos)
272                 exit_err("seek position overflow");
273         if (fseeko(f, pos, SEEK_SET)) {
274                 perror("fseek");
275                 exit(2);
276         }
277 }
278
279 static off_t verity_position_at_level(off_t block, int level)
280 {
281         return block >> (level * hash_per_block_bits);
282 }
283
284 static void calculate_positions(void)
285 {
286         unsigned long long hash_position;
287         int i;
288
289         digest_size_bits = 0;
290         while (1 << digest_size_bits < digest_size)
291                 digest_size_bits++;
292         hash_per_block_bits = 0;
293         while (((hash_block_size / digest_size) >> hash_per_block_bits) > 1)
294                 hash_per_block_bits++;
295         if (!hash_per_block_bits)
296                 exit_err("at least two hashes must fit in a hash file block");
297         levels = 0;
298
299         if (data_file_blocks) {
300                 while (hash_per_block_bits * levels < 64 &&
301                        (unsigned long long)(data_file_blocks - 1) >>
302                        (hash_per_block_bits * levels))
303                         levels++;
304         }
305
306         if (levels > DM_VERITY_MAX_LEVELS)
307                 exit_err("too many tree levels");
308
309         hash_position = hash_start * 512 / hash_block_size;
310         for (i = levels - 1; i >= 0; i--) {
311                 off_t s;
312                 hash_level_block[i] = hash_position;
313                 s = verity_position_at_level(data_file_blocks, i);
314                 s = (s >> hash_per_block_bits) +
315                     !!(s & ((1 << hash_per_block_bits) - 1));
316                 hash_level_size[i] = s;
317                 if (hash_position + s < hash_position ||
318                     (off_t)(hash_position + s) < 0 ||
319                     (off_t)(hash_position + s) != hash_position + s)
320                         exit_err("hash device offset overflow");
321                 hash_position += s;
322         }
323         used_hash_blocks = hash_position;
324 }
325
326 static void create_or_verify_zero(FILE *wr, char *left_block, unsigned left_bytes)
327 {
328         if (left_bytes) {
329                 if (mode != MODE_CREATE) {
330                         unsigned x;
331                         if (fread(left_block, left_bytes, 1, wr) != 1)
332                                 stream_err(wr, "read");
333                         for (x = 0; x < left_bytes; x++) if (left_block[x]) {
334                                 retval = 1;
335                                 fprintf(stderr, "spare area is not zeroed at position %lld\n", (long long)ftello(wr) - left_bytes);
336                         }
337                 } else {
338                         if (fwrite(left_block, left_bytes, 1, wr) != 1)
339                                 stream_err(wr, "write");
340                 }
341         }
342 }
343
344 static void create_or_verify_stream(FILE *rd, FILE *wr, int block_size, off_t blocks)
345 {
346         char *left_block = xmalloc(hash_block_size);
347         char *data_buffer = xmalloc(block_size);
348         char *read_digest = mode != MODE_CREATE ? xmalloc(digest_size) : NULL;
349         off_t blocks_to_write = (blocks >> hash_per_block_bits) +
350                                 !!(blocks & ((1 << hash_per_block_bits) - 1));
351         struct crypt_hash *ctx = NULL;
352
353         if (crypt_hash_init(&ctx, hash_algorithm))
354                 exit_err("hash_init failed");
355
356         memset(left_block, 0, hash_block_size);
357         while (blocks_to_write--) {
358                 unsigned x;
359                 unsigned left_bytes = hash_block_size;
360                 for (x = 0; x < 1 << hash_per_block_bits; x++) {
361                         if (!blocks)
362                                 break;
363                         blocks--;
364                         if (fread(data_buffer, block_size, 1, rd) != 1)
365                                 stream_err(rd, "read");
366                         if (version >= 1) {
367                                 if (crypt_hash_write(ctx, salt_bytes, salt_size))
368                                         exit_err("hash_write failed");
369                         }
370                         if (crypt_hash_write(ctx, data_buffer, block_size))
371                                 exit_err("hash_write failed");
372                         if (!version) {
373                                 if (crypt_hash_write(ctx, salt_bytes, salt_size))
374                                         exit_err("hash_write failed");
375                         }
376                         if (crypt_hash_final(ctx, calculated_digest, digest_size))
377                                         exit_err("hash_final failed");
378                         if (!wr)
379                                 break;
380                         if (mode != MODE_CREATE) {
381                                 if (fread(read_digest, digest_size, 1, wr) != 1)
382                                         stream_err(wr, "read");
383                                 if (memcmp(read_digest, calculated_digest, digest_size)) {
384                                         retval = 1;
385                                         fprintf(stderr, "verification failed at position %lld in %s file\n", (long long)ftello(rd) - block_size, rd == data_file ? "data" : "metadata");
386                                 }
387                         } else {
388                                 if (fwrite(calculated_digest, digest_size, 1, wr) != 1)
389                                         stream_err(wr, "write");
390                         }
391                         if (!version) {
392                                 left_bytes -= digest_size;
393                         } else {
394                                 create_or_verify_zero(wr, left_block, (1 << digest_size_bits) - digest_size);
395                                 left_bytes -= 1 << digest_size_bits;
396                         }
397                 }
398                 if (wr)
399                         create_or_verify_zero(wr, left_block, left_bytes);
400         }
401         if (mode == MODE_CREATE && wr) {
402                 if (fflush(wr)) {
403                         perror("fflush");
404                         exit(1);
405                 }
406                 if (ferror(wr)) {
407                         stream_err(wr, "write");
408                 }
409         }
410         crypt_hash_destroy(ctx);
411         free(left_block);
412         free(data_buffer);
413         if (mode != MODE_CREATE)
414                 free(read_digest);
415 }
416
417 static char **make_target_line(void)
418 {
419         const int line_elements = 14;
420         char **line = xmalloc(line_elements * sizeof(char *));
421         int i = 0;
422         char *algorithm_copy = xstrdup(hash_algorithm);
423                 /* transform ripemdXXX to rmdXXX */
424         if (!strncmp(algorithm_copy, "ripemd", 6))
425                 memmove(algorithm_copy + 1, algorithm_copy + 4, strlen(algorithm_copy + 4) + 1);
426         if (!strcmp(algorithm_copy, "whirlpool"))
427                 strcpy(algorithm_copy, "wp512");
428         line[i++] = xstrdup("0");
429         line[i++] = xprint((unsigned long long)data_file_blocks * data_block_size / 512);
430         line[i++] = xstrdup("verity");
431         line[i++] = xprint(version);
432         line[i++] = xstrdup(data_device);
433         line[i++] = xstrdup(hash_device);
434         line[i++] = xprint(data_block_size);
435         line[i++] = xprint(hash_block_size);
436         line[i++] = xprint(data_file_blocks);
437         line[i++] = xprint(hash_start * 512 / hash_block_size);
438         line[i++] = algorithm_copy;
439         line[i++] = xhexprint(calculated_digest, digest_size);
440         line[i++] = !salt_size ? xstrdup("-") : xhexprint(salt_bytes, salt_size);
441         line[i++] = NULL;
442         if (i > line_elements)
443                 exit_err("INTERNAL ERROR: insufficient array size");
444         return line;
445 }
446
447 static void free_target_line(char **line)
448 {
449         int i;
450         for (i = 0; line[i]; i++)
451                 free(line[i]);
452         free(line);
453 }
454
455 static void create_or_verify(void)
456 {
457         int i;
458
459         memset(calculated_digest, 0, digest_size);
460         if (mode != MODE_ACTIVATE)
461                 for (i = 0; i < levels; i++) {
462                         block_fseek(hash_file, hash_level_block[i], hash_block_size);
463                         if (!i) {
464                                 block_fseek(data_file, 0, data_block_size);
465                                 create_or_verify_stream(data_file, hash_file, data_block_size, data_file_blocks);
466                         } else {
467                                 FILE *hash_file_2 = fopen(hash_device, "r");
468                                 if (!hash_file_2) {
469                                         perror(hash_device);
470                                         exit(2);
471                                 }
472                                 block_fseek(hash_file_2, hash_level_block[i - 1], hash_block_size);
473                                 create_or_verify_stream(hash_file_2, hash_file, hash_block_size, hash_level_size[i - 1]);
474                                 fclose(hash_file_2);
475                         }
476                 }
477
478         if (levels) {
479                 block_fseek(hash_file, hash_level_block[levels - 1], hash_block_size);
480                 create_or_verify_stream(hash_file, NULL, hash_block_size, 1);
481         } else {
482                 block_fseek(data_file, 0, data_block_size);
483                 create_or_verify_stream(data_file, NULL, data_block_size, data_file_blocks);
484         }
485
486         if (mode != MODE_CREATE) {
487                 if (memcmp(calculated_digest, root_hash_bytes, digest_size)) {
488                         fprintf(stderr, "verification failed in the root block\n");
489                         retval = 1;
490                 }
491                 if (!retval && mode == MODE_VERIFY)
492                         fprintf(stderr, "hash successfully verified\n");
493         } else {
494                 char **target_line;
495                 char *p;
496                 if (fsync(fileno(hash_file))) {
497                         perror("fsync");
498                         exit(1);
499                 }
500                 printf("hash device size: %llu\n", (unsigned long long)used_hash_blocks * hash_block_size);
501                 printf("data block size %u, hash block size %u, %u tree levels\n", data_block_size, hash_block_size, levels);
502                 if (salt_size)
503                         p = xhexprint(salt_bytes, salt_size);
504                 else
505                         p = xstrdup("-");
506                 printf("salt: %s\n", p);
507                 free(p);
508                 p = xhexprint(calculated_digest, digest_size);
509                 printf("root hash: %s\n", p);
510                 free(p);
511                 printf("target line:");
512                 target_line = make_target_line();
513                 for (i = 0; target_line[i]; i++)
514                         printf(" %s", target_line[i]);
515                 free_target_line(target_line);
516                 printf("\n");
517         }
518 }
519
520 __attribute__((__noreturn__))
521 static void activate(void)
522 {
523         int i;
524         size_t len = 1;
525         char *table_arg;
526         char **target_line = make_target_line();
527         for (i = 0; target_line[i]; i++) {
528                 if (i)
529                         len++;
530                 len += strlen(target_line[i]);
531         }
532         table_arg = xmalloc(len);
533         table_arg[0] = 0;
534         for (i = 0; target_line[i]; i++) {
535                 if (i)
536                         strcat(table_arg, " ");
537                 strcat(table_arg, target_line[i]);
538         }
539         free_target_line(target_line);
540         execlp("dmsetup", "dmsetup", "-r", "create", dm_device, "--table", table_arg, NULL);
541         perror("dmsetup");
542         exit(2);
543 }
544
545 static void get_hex(const char *string, char **result, size_t len, const char *description)
546 {
547         size_t rl = strlen(string);
548         unsigned u;
549         if (strspn(string, "0123456789ABCDEFabcdef") != rl)
550                 exit_err("invalid %s", description);
551         if (rl != len * 2)
552                 exit_err("invalid length of %s", description);
553         *result = xmalloc(len);
554         memset(*result, 0, len);
555         for (u = 0; u < rl; u++) {
556                 unsigned char c = (string[u] & 15) + (string[u] > '9' ? 9 : 0);
557                 (*result)[u / 2] |= c << (((u & 1) ^ 1) << 2);
558         }
559 }
560
561 static struct superblock superblock;
562
563 static void load_superblock(void)
564 {
565         long long sb_data_blocks;
566
567         block_fseek(hash_file, superblock_position, 1);
568         if (fread(&superblock, sizeof(struct superblock), 1, hash_file) != 1)
569                 stream_err(hash_file, "read");
570         if (memcmp(superblock.signature, DM_VERITY_SIGNATURE, sizeof(superblock.signature)))
571                 exit_err("superblock not found on the hash device");
572         if (superblock.version > MAX_FORMAT_VERSION)
573                 exit_err("unknown version");
574         if (superblock.data_block_bits < 9 || superblock.data_block_bits >= 31)
575                 exit_err("invalid data_block_bits in the superblock");
576         if (superblock.hash_block_bits < 9 || superblock.hash_block_bits >= 31)
577                 exit_err("invalid data_block_bits in the superblock");
578         sb_data_blocks = ((unsigned long long)ntohl(superblock.data_blocks_hi) << 31 << 1) | ntohl(superblock.data_blocks_lo);
579         if (sb_data_blocks < 0 || (off_t)sb_data_blocks < 0 || (off_t)sb_data_blocks != sb_data_blocks)
580                 exit_err("invalid data blocks in the superblock");
581         if (!memchr(superblock.algorithm, 0, sizeof(superblock.algorithm)))
582                 exit_err("invalid hash algorithm in the superblock");
583         if (ntohs(superblock.salt_size) > MAX_SALT_SIZE)
584                 exit_err("invalid salt_size in the superblock");
585
586         if (version == -1) {
587                 version = superblock.version;
588         } else {
589                 if (version != superblock.version)
590                         exit_err("version (%d) does not match superblock value (%d)", version, superblock.version);
591         }
592
593         if (!data_block_size) {
594                 data_block_size = 1 << superblock.data_block_bits;
595         } else {
596                 if (data_block_size != 1 << superblock.data_block_bits)
597                         exit_err("data block size (%d) does not match superblock value (%d)", data_block_size, 1 << superblock.data_block_bits);
598         }
599
600         if (!hash_block_size) {
601                 hash_block_size = 1 << superblock.hash_block_bits;
602         } else {
603                 if (hash_block_size != 1 << superblock.hash_block_bits)
604                         exit_err("hash block size (%d) does not match superblock value (%d)", hash_block_size, 1 << superblock.hash_block_bits);
605         }
606
607         if (!data_blocks_string) {
608                 data_blocks = sb_data_blocks;
609                 data_blocks_string = (char *)"";
610         } else {
611                 if (data_blocks != sb_data_blocks)
612                         exit_err("data blocks (%lld) does not match superblock value (%lld)", data_blocks, sb_data_blocks);
613         }
614
615         if (!hash_algorithm) {
616                 hash_algorithm = (char *)superblock.algorithm;
617         } else {
618                 if (strcmp(hash_algorithm, (char *)superblock.algorithm))
619                         exit_err("hash algorithm (%s) does not match superblock value (%s)", hash_algorithm, superblock.algorithm);
620         }
621
622         if (!salt_bytes) {
623                 salt_size = ntohs(superblock.salt_size);
624                 salt_bytes = xmalloc(salt_size);
625                 memcpy(salt_bytes, superblock.salt, salt_size);
626         } else {
627                 if (salt_size != ntohs(superblock.salt_size) ||
628                     memcmp(salt_bytes, superblock.salt, salt_size))
629                         exit_err("salt does not match superblock value");
630         }
631 }
632
633 static void save_superblock(void)
634 {
635         memset(&superblock, 0, sizeof(struct superblock));
636
637         memcpy(&superblock.signature, DM_VERITY_SIGNATURE, sizeof(superblock.signature));
638         superblock.version = version;
639         superblock.data_block_bits = ffs(data_block_size) - 1;
640         superblock.hash_block_bits = ffs(hash_block_size) - 1;
641         superblock.salt_size = htons(salt_size);
642         superblock.data_blocks_hi = htonl(data_file_blocks >> 31 >> 1);
643         superblock.data_blocks_lo = htonl(data_file_blocks & 0xFFFFFFFF);
644         strncpy((char *)superblock.algorithm, hash_algorithm, sizeof superblock.algorithm);
645         memcpy(superblock.salt, salt_bytes, salt_size);
646
647         block_fseek(hash_file, superblock_position, 1);
648         if (fwrite(&superblock, sizeof(struct superblock), 1, hash_file) != 1)
649                 stream_err(hash_file, "write");
650 }
651
652 int main(int argc, const char **argv)
653 {
654         poptContext popt_context;
655         int r;
656         const char *s;
657         char *end;
658
659         if (sizeof(struct superblock) != 512)
660                 exit_err("INTERNAL ERROR: bad superblock size %ld", (long)sizeof(struct superblock));
661
662         popt_context = poptGetContext("verity", argc, argv, popt_options, 0);
663
664         poptSetOtherOptionHelp(popt_context, "[-c | -v | -a] [<device name> if activating] <data device> <hash device> [<root hash> if activating or verifying] [OPTION...]");
665
666         if (argc <= 1) {
667                 poptPrintHelp(popt_context, stdout, 0);
668                 exit(1);
669         }
670
671         r = poptGetNextOpt(popt_context);
672         if (r < -1)
673                 exit_err("bad option %s", poptBadOption(popt_context, 0));
674
675         if (mode < 0)
676                 exit_err("verify, create or activate mode not specified");
677
678         if (mode == MODE_ACTIVATE) {
679                 dm_device = poptGetArg(popt_context);
680                 if (!dm_device)
681                         exit_err("device name is missing");
682                 if (!*dm_device || strchr(dm_device, '/'))
683                         exit_err("invalid device name to activate");
684         }
685
686         data_device = poptGetArg(popt_context);
687         if (!data_device)
688                 exit_err("data device is missing");
689
690         hash_device = poptGetArg(popt_context);
691         if (!hash_device)
692                 exit_err("metadata device is missing");
693
694         if (mode != MODE_CREATE) {
695                 root_hash = poptGetArg(popt_context);
696                 if (!root_hash)
697                         exit_err("root hash not specified");
698         }
699
700         s = poptGetArg(popt_context);
701         if (s)
702                 exit_err("extra argument %s", s);
703
704         data_file = fopen(data_device, "r");
705         if (!data_file) {
706                 perror(data_device);
707                 exit(2);
708         }
709
710         hash_file = fopen(hash_device, mode != MODE_CREATE ? "r" : "r+");
711         if (!hash_file && errno == ENOENT && mode == MODE_CREATE)
712                 hash_file = fopen(hash_device, "w+");
713         if (!hash_file) {
714                 perror(hash_device);
715                 exit(2);
716         }
717
718         if (data_blocks_string) {
719                 data_blocks = strtoll(data_blocks_string, &end, 10);
720                 if (!*data_blocks_string || *end)
721                         exit_err("invalid number of data blocks");
722         }
723
724         if (hash_start_string) {
725                 hash_start = strtoll(hash_start_string, &end, 10);
726                 if (!*hash_start_string || *end)
727                         exit_err("invalid hash start");
728         }
729
730         if (hash_start < 0 ||
731            (unsigned long long)hash_start * 512 / 512 != hash_start ||
732            (off_t)(hash_start * 512) < 0 ||
733            (off_t)(hash_start * 512) != hash_start * 512) exit_err("invalid hash start");
734
735         if (salt_string || !use_superblock) {
736                 if (!salt_string || !strcmp(salt_string, "-"))
737                         salt_string = "";
738                 salt_size = strlen(salt_string) / 2;
739                 if (salt_size > MAX_SALT_SIZE)
740                         exit_err("too long salt (max %d bytes)", MAX_SALT_SIZE);
741                 get_hex(salt_string, &salt_bytes, salt_size, "salt");
742         }
743
744         if (use_superblock) {
745                 superblock_position = hash_start * 512;
746                 if (mode != MODE_CREATE)
747                         load_superblock();
748         }
749
750         if (version == -1)
751                 version = MAX_FORMAT_VERSION;
752         if (version < 0 || version > MAX_FORMAT_VERSION)
753                 exit_err("invalid format version");
754
755         if (!data_block_size)
756                 data_block_size = DEFAULT_BLOCK_SIZE;
757         if (!hash_block_size)
758                 hash_block_size = data_block_size;
759
760         if (data_block_size < 512 || (data_block_size & (data_block_size - 1)) || data_block_size >= 1U << 31)
761                 exit_err("invalid data block size");
762
763         if (hash_block_size < 512 || (hash_block_size & (hash_block_size - 1)) || hash_block_size >= 1U << 31)
764                 exit_err("invalid hash block size");
765
766         if (data_blocks < 0 || (off_t)data_blocks < 0 || (off_t)data_blocks != data_blocks)
767                 exit_err("invalid number of data blocks");
768
769         data_file_blocks = get_size(data_file, data_device) / data_block_size;
770         hash_file_blocks = get_size(hash_file, hash_device) / hash_block_size;
771
772         if (data_file_blocks < data_blocks)
773                 exit_err("data file is too small");
774         if (data_blocks_string)
775                 data_file_blocks = data_blocks;
776
777         if (use_superblock) {
778                 hash_start = hash_start + (sizeof(struct superblock) + 511) / 512;
779                 hash_start = (hash_start + (hash_block_size / 512 - 1)) & ~(long long)(hash_block_size / 512 - 1);
780         }
781
782         if ((unsigned long long)hash_start * 512 % hash_block_size)
783                 exit_err("hash start not aligned on block size");
784
785         if (!hash_algorithm)
786                 hash_algorithm = "sha256";
787         if (strlen(hash_algorithm) >= sizeof(superblock.algorithm) && use_superblock)
788                 exit_err("hash algorithm name is too long");
789
790         if (crypt_backend_init(NULL))
791                 exit_err("cannot initialize crypto backend");
792
793         digest_size = crypt_hash_size(hash_algorithm);
794         if (!digest_size) exit_err("hash algorithm %s not found", hash_algorithm);
795
796         if (!salt_bytes) {
797                 salt_size = DEFAULT_SALT_SIZE;
798                 salt_bytes = xmalloc(salt_size);
799                 if (crypt_backend_rng(salt_bytes, salt_size, CRYPT_RND_SALT, 0))
800                         exit_err("rng failed");
801         }
802
803         calculated_digest = xmalloc(digest_size);
804
805         if (mode != MODE_CREATE) {
806                 get_hex(root_hash, &root_hash_bytes, digest_size, "root_hash");
807         }
808
809         calculate_positions();
810
811         create_or_verify();
812
813         if (use_superblock) {
814                 if (mode == MODE_CREATE)
815                         save_superblock();
816         }
817
818         fclose(data_file);
819         fclose(hash_file);
820
821         if (mode == MODE_ACTIVATE && !retval)
822                 activate();
823
824         free(salt_bytes);
825         free(calculated_digest);
826         if (mode != MODE_CREATE)
827                 free(root_hash_bytes);
828         poptFreeContext(popt_context);
829
830         return retval;
831 }