5a8c59980ac84204a3bab4e0fd0b932bb65c0416
[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 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stdarg.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <inttypes.h>
27 #include <popt.h>
28 #include <limits.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32
33 #include "cryptsetup.h"
34
35 #define PACKAGE_VERITY "veritysetup"
36
37 static int use_superblock = 1;
38
39 static const char *hash_algorithm = NULL;
40 static int hash_type = 1;
41 static int data_block_size = DEFAULT_VERITY_DATA_BLOCK;
42 static int hash_block_size = DEFAULT_VERITY_HASH_BLOCK;
43 static uint64_t data_blocks = 0;
44 static const char *salt_string = NULL;
45 static uint64_t hash_offset = 0;
46 static const char *opt_uuid = NULL;
47
48 static int opt_verbose = 0;
49 static int opt_debug = 0;
50 static int opt_version_mode = 0;
51
52 static const char **action_argv;
53 static int action_argc;
54
55 __attribute__((format(printf, 5, 6)))
56 static void clogger(struct crypt_device *cd, int level, const char *file,
57                    int line, const char *format, ...)
58 {
59         va_list argp;
60         char *target = NULL;
61
62         va_start(argp, format);
63
64         if (vasprintf(&target, format, argp) > 0) {
65                 if (level >= 0) {
66                         crypt_log(cd, level, target);
67 #ifdef CRYPT_DEBUG
68                 } else if (opt_debug)
69                         printf("# %s:%d %s\n", file ?: "?", line, target);
70 #else
71                 } else if (opt_debug)
72                         printf("# %s\n", target);
73 #endif
74         }
75
76         va_end(argp);
77         free(target);
78 }
79
80 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
81 {
82         switch(level) {
83
84         case CRYPT_LOG_NORMAL:
85                 fputs(msg, stdout);
86                 break;
87         case CRYPT_LOG_VERBOSE:
88                 if (opt_verbose)
89                         fputs(msg, stdout);
90                 break;
91         case CRYPT_LOG_ERROR:
92                 fputs(msg, stderr);
93                 break;
94         case CRYPT_LOG_DEBUG:
95                 if (opt_debug)
96                         printf("# %s\n", msg);
97                 break;
98         default:
99                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
100                 break;
101         }
102 }
103
104 static int _prepare_format(struct crypt_params_verity *params,
105                            const char *data_device,
106                            uint32_t flags)
107 {
108         char *salt = NULL;
109         int len;
110
111         params->hash_name = hash_algorithm ?: DEFAULT_VERITY_HASH;
112         params->data_device = data_device;
113
114         if (salt_string && !strcmp(salt_string, "-")) {
115                 params->salt_size = 0;
116                 params->salt = NULL;
117         } else if (salt_string) {
118                 len = crypt_hex_to_bytes(salt_string, &salt, 0);
119                 if (len < 0) {
120                         log_err(_("Invalid salt string specified.\n"));
121                         return -EINVAL;
122                 }
123                 params->salt_size = len;
124                 params->salt = salt;
125         } else {
126                 params->salt_size = DEFAULT_VERITY_SALT_SIZE;
127                 params->salt = NULL;
128         }
129
130         params->data_block_size = data_block_size;
131         params->hash_block_size = hash_block_size;
132         params->data_size = data_blocks;
133         params->hash_area_offset = hash_offset;
134         params->hash_type = hash_type;
135         params->flags = flags;
136
137         return 0;
138 }
139
140 static int action_format(int arg)
141 {
142         struct crypt_device *cd = NULL;
143         struct crypt_params_verity params = {};
144         uint32_t flags = CRYPT_VERITY_CREATE_HASH;
145         struct stat st;
146         int r;
147
148         /* Try to create hash image if doesn't exist */
149         if (stat(action_argv[1], &st) < 0) {
150                 log_dbg("Creating hash image %s.", action_argv[1]);
151                 r = open(action_argv[1], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
152                 if (r < 0) {
153                         log_err(_("Cannot create hash image %s for writing.\n"), action_argv[1]);
154                         return -EINVAL;
155                 }
156                 close(r);
157         }
158
159         if ((r = crypt_init(&cd, action_argv[1])))
160                 goto out;
161
162         if (!use_superblock)
163                 flags |= CRYPT_VERITY_NO_HEADER;
164
165         r = _prepare_format(&params, action_argv[0], flags);
166         if (r < 0)
167                 goto out;
168
169         r = crypt_format(cd, CRYPT_VERITY, NULL, NULL, opt_uuid, NULL, 0, &params);
170         if (!r)
171                 crypt_dump(cd);
172 out:
173         crypt_free(cd);
174         free(CONST_CAST(char*)params.salt);
175         return r;
176 }
177
178 static int _activate(const char *dm_device,
179                       const char *data_device,
180                       const char *hash_device,
181                       const char *root_hash,
182                       uint32_t flags)
183 {
184         struct crypt_device *cd = NULL;
185         struct crypt_params_verity params = {};
186         uint32_t activate_flags = CRYPT_ACTIVATE_READONLY;
187         char *root_hash_bytes = NULL;
188         ssize_t hash_size;
189         int r;
190
191         if ((r = crypt_init(&cd, hash_device)))
192                 goto out;
193
194         if (use_superblock) {
195                 params.flags = flags;
196                 params.hash_area_offset = hash_offset;
197                 r = crypt_load(cd, CRYPT_VERITY, &params);
198         } else {
199                 r = _prepare_format(&params, data_device, flags | CRYPT_VERITY_NO_HEADER);
200                 if (r < 0)
201                         goto out;
202                 r = crypt_format(cd, CRYPT_VERITY, NULL, NULL, NULL, NULL, 0, &params);
203         }
204         if (r < 0)
205                 goto out;
206         r = crypt_set_data_device(cd, data_device);
207         if (r < 0)
208                 goto out;
209
210         hash_size = crypt_get_volume_key_size(cd);
211         if (crypt_hex_to_bytes(root_hash, &root_hash_bytes, 0) != hash_size) {
212                 log_err(_("Invalid root hash string specified.\n"));
213                 r = -EINVAL;
214                 goto out;
215         }
216         r = crypt_activate_by_volume_key(cd, dm_device,
217                                          root_hash_bytes,
218                                          hash_size,
219                                          activate_flags);
220 out:
221         crypt_free(cd);
222         free(root_hash_bytes);
223         free(CONST_CAST(char*)params.salt);
224         return r;
225 }
226
227 static int action_create(int arg)
228 {
229         return _activate(action_argv[0],
230                          action_argv[1],
231                          action_argv[2],
232                          action_argv[3], 0);
233 }
234
235 static int action_verify(int arg)
236 {
237         return _activate(NULL,
238                          action_argv[0],
239                          action_argv[1],
240                          action_argv[2],
241                          CRYPT_VERITY_CHECK_HASH);
242 }
243
244 static int action_remove(int arg)
245 {
246         struct crypt_device *cd = NULL;
247         int r;
248
249         r = crypt_init_by_name(&cd, action_argv[0]);
250         if (r == 0)
251                 r = crypt_deactivate(cd, action_argv[0]);
252
253         crypt_free(cd);
254         return r;
255 }
256
257 static int action_status(int arg)
258 {
259         crypt_status_info ci;
260         struct crypt_active_device cad;
261         struct crypt_params_verity vp = {};
262         struct crypt_device *cd = NULL;
263         struct stat st;
264         char *backing_file;
265         unsigned i, path = 0;
266         int r = 0;
267
268         /* perhaps a path, not a dm device name */
269         if (strchr(action_argv[0], '/') && !stat(action_argv[0], &st))
270                 path = 1;
271
272         ci = crypt_status(NULL, action_argv[0]);
273         switch (ci) {
274         case CRYPT_INVALID:
275                 r = -EINVAL;
276                 break;
277         case CRYPT_INACTIVE:
278                 if (path)
279                         log_std("%s is inactive.\n", action_argv[0]);
280                 else
281                         log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]);
282                 r = -ENODEV;
283                 break;
284         case CRYPT_ACTIVE:
285         case CRYPT_BUSY:
286                 if (path)
287                         log_std("%s is active%s.\n", action_argv[0],
288                                 ci == CRYPT_BUSY ? " and is in use" : "");
289                 else
290                         log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0],
291                                 ci == CRYPT_BUSY ? " and is in use" : "");
292
293                 r = crypt_init_by_name_and_header(&cd, action_argv[0], NULL);
294                 if (r < 0 || !crypt_get_type(cd))
295                         goto out;
296
297                 log_std("  type:        %s\n", crypt_get_type(cd));
298
299                 r = crypt_get_active_device(cd, action_argv[0], &cad);
300                 if (r < 0)
301                         goto out;
302
303                 log_std("  status:      %s\n",
304                         cad.flags & CRYPT_ACTIVATE_CORRUPTED ? "corrupted" : "verified");
305
306                 r = crypt_get_verity_info(cd, &vp);
307                 if (r < 0)
308                         goto out;
309
310                 log_std("  hash type:   %u\n", vp.hash_type);
311                 log_std("  data block:  %u\n", vp.data_block_size);
312                 log_std("  hash block:  %u\n", vp.hash_block_size);
313                 log_std("  hash name:   %s\n", vp.hash_name);
314                 log_std("  salt:        ");
315                 if (vp.salt_size)
316                         for(i = 0; i < vp.salt_size; i++)
317                                 log_std("%02hhx", (const char)vp.salt[i]);
318                 else
319                         log_std("-");
320                 log_std("\n");
321
322                 log_std("  data device: %s\n", vp.data_device);
323                 if (crypt_loop_device(vp.data_device)) {
324                         backing_file = crypt_loop_backing_file(vp.data_device);
325                         log_std("  data loop:   %s\n", backing_file);
326                         free(backing_file);
327                 }
328                 log_std("  size:        %" PRIu64 " sectors\n", cad.size);
329                 log_std("  mode:        %s\n", cad.flags & CRYPT_ACTIVATE_READONLY ?
330                                            "readonly" : "read/write");
331
332                 log_std("  hash device: %s\n", vp.hash_device);
333                 if (crypt_loop_device(vp.hash_device)) {
334                         backing_file = crypt_loop_backing_file(vp.hash_device);
335                         log_std("  hash loop:   %s\n", backing_file);
336                         free(backing_file);
337                 }
338                 log_std("  hash offset: %" PRIu64 " sectors\n",
339                         vp.hash_area_offset * vp.hash_block_size / 512);
340         }
341 out:
342         crypt_free(cd);
343         if (r == -ENOTSUP)
344                 r = 0;
345         return r;
346 }
347
348 static int action_dump(int arg)
349 {
350         struct crypt_device *cd = NULL;
351         struct crypt_params_verity params = {};
352         int r;
353
354         if ((r = crypt_init(&cd, action_argv[0])))
355                 return r;
356
357         params.hash_area_offset = hash_offset;
358         r = crypt_load(cd, CRYPT_VERITY, &params);
359         if (!r)
360                 crypt_dump(cd);
361         crypt_free(cd);
362         return r;
363 }
364
365 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
366                                              int exitcode, const char *error,
367                                              const char *more)
368 {
369         poptPrintUsage(popt_context, stderr, 0);
370         if (error)
371                 log_err("%s: %s\n", more, error);
372         poptFreeContext(popt_context);
373         exit(exitcode);
374 }
375
376 static void _dbg_version_and_cmd(int argc, const char **argv)
377 {
378         int i;
379
380         log_std("# %s %s processing \"", PACKAGE_VERITY, PACKAGE_VERSION);
381         for (i = 0; i < argc; i++) {
382                 if (i)
383                         log_std(" ");
384                 log_std("%s", argv[i]);
385         }
386         log_std("\"\n");
387 }
388
389 static struct action_type {
390         const char *type;
391         int (*handler)(int);
392         int required_action_argc;
393         const char *arg_desc;
394         const char *desc;
395 } action_types[] = {
396         { "format",     action_format, 2, N_("<data_device> <hash_device>"),N_("format device") },
397         { "verify",     action_verify, 3, N_("<data_device> <hash_device> <root_hash>"),N_("verify device") },
398         { "create",     action_create, 4, N_("<name> <data_device> <hash_device> <root_hash>"),N_("create active device") },
399         { "remove",     action_remove, 1, N_("<name>"),N_("remove (deactivate) device") },
400         { "status",     action_status, 1, N_("<name>"),N_("show active device status") },
401         { "dump",       action_dump,   1, N_("<hash_device>"),N_("show on-disk information") },
402         { NULL, NULL, 0, NULL, NULL }
403 };
404
405 static void help(poptContext popt_context,
406                  enum poptCallbackReason reason __attribute__((unused)),
407                  struct poptOption *key,
408                  const char *arg __attribute__((unused)),
409                  void *data __attribute__((unused)))
410 {
411         struct action_type *action;
412
413         if (key->shortName == '?') {
414                 log_std("%s %s\n", PACKAGE_VERITY, PACKAGE_VERSION);
415                 poptPrintHelp(popt_context, stdout, 0);
416                 log_std(_("\n"
417                          "<action> is one of:\n"));
418                 for(action = action_types; action->type; action++)
419                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
420                 log_std(_("\n"
421                          "<name> is the device to create under %s\n"
422                          "<data_device> is the data device\n"
423                          "<hash_device> is the device containing verification data\n"
424                          "<root_hash> hash of the root node on <hash_device>\n"),
425                         crypt_get_dir());
426
427                 log_std(_("\nDefault compiled-in dm-verity parameters:\n"
428                          "\tHash: %s, Data block (bytes): %u, "
429                          "Hash block (bytes): %u, Salt size: %u, Hash format: %u\n"),
430                         DEFAULT_VERITY_HASH, DEFAULT_VERITY_DATA_BLOCK,
431                         DEFAULT_VERITY_HASH_BLOCK, DEFAULT_VERITY_SALT_SIZE,
432                         1);
433                 exit(EXIT_SUCCESS);
434         } else
435                 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
436 }
437
438 static void show_status(int errcode)
439 {
440         char error[256], *error_;
441
442         if(!opt_verbose)
443                 return;
444
445         if(!errcode) {
446                 log_std(_("Command successful.\n"));
447                 return;
448         }
449
450         crypt_get_error(error, sizeof(error));
451
452         if (!error[0]) {
453                 error_ = strerror_r(-errcode, error, sizeof(error));
454                 if (error_ != error) {
455                         strncpy(error, error_, sizeof(error));
456                         error[sizeof(error) - 1] = '\0';
457                 }
458         }
459
460         log_err(_("Command failed with code %i"), -errcode);
461         if (*error)
462                 log_err(": %s\n", error);
463         else
464                 log_err(".\n");
465 }
466
467 static int run_action(struct action_type *action)
468 {
469         int r;
470
471         log_dbg("Running command %s.", action->type);
472
473         r = action->handler(0);
474
475         show_status(r);
476
477         /* Translate exit code to simple codes */
478         switch (r) {
479         case 0:         r = EXIT_SUCCESS; break;
480         case -EEXIST:
481         case -EBUSY:    r = 5; break;
482         case -ENOTBLK:
483         case -ENODEV:   r = 4; break;
484         case -ENOMEM:   r = 3; break;
485         case -EPERM:    r = 2; break;
486         case -EINVAL:
487         case -ENOENT:
488         case -ENOSYS:
489         default:        r = EXIT_FAILURE;
490         }
491         return r;
492 }
493
494 int main(int argc, const char **argv)
495 {
496         static char *popt_tmp;
497         static const char *null_action_argv[] = {NULL};
498         static struct poptOption popt_help_options[] = {
499                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
500                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
501                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
502                 POPT_TABLEEND
503         };
504         static struct poptOption popt_options[] = {
505                 { NULL,              '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
506                 { "version",         '\0', POPT_ARG_NONE, &opt_version_mode, 0, N_("Print package version"), NULL },
507                 { "verbose",         'v',  POPT_ARG_NONE, &opt_verbose,      0, N_("Shows more detailed error messages"), NULL },
508                 { "debug",           '\0', POPT_ARG_NONE, &opt_debug,        0, N_("Show debug messages"), NULL },
509                 { "no-superblock",   0,    POPT_ARG_VAL,  &use_superblock,   0, N_("Do not use verity superblock"), NULL },
510                 { "format",          0,    POPT_ARG_INT,  &hash_type,        0, N_("Format type (1 - normal, 0 - original Chrome OS)"), N_("number") },
511                 { "data-block-size", 0,    POPT_ARG_INT,  &data_block_size,  0, N_("Block size on the data device"), N_("bytes") },
512                 { "hash-block-size", 0,    POPT_ARG_INT,  &hash_block_size,  0, N_("Block size on the hash device"), N_("bytes") },
513                 { "data-blocks",     0,    POPT_ARG_STRING, &popt_tmp,       1, N_("The number of blocks in the data file"), N_("blocks") },
514                 { "hash-offset",     0,    POPT_ARG_STRING, &popt_tmp,       2, N_("Starting offset on the hash device"), N_("bytes") },
515                 { "hash",            'h',  POPT_ARG_STRING, &hash_algorithm, 0, N_("Hash algorithm"), N_("string") },
516                 { "salt",            's',  POPT_ARG_STRING, &salt_string,    0, N_("Salt"), N_("hex string") },
517                 { "uuid",            '\0', POPT_ARG_STRING, &opt_uuid,       0, N_("UUID for device to use."), NULL },
518                 POPT_TABLEEND
519         };
520
521         poptContext popt_context;
522         struct action_type *action;
523         const char *aname;
524         int r;
525
526         crypt_set_log_callback(NULL, _log, NULL);
527
528         setlocale(LC_ALL, "");
529         bindtextdomain(PACKAGE, LOCALEDIR);
530         textdomain(PACKAGE);
531
532         popt_context = poptGetContext("verity", argc, argv, popt_options, 0);
533         poptSetOtherOptionHelp(popt_context,
534                                _("[OPTION...] <action> <action-specific>"));
535
536         while((r = poptGetNextOpt(popt_context)) > 0) {
537                 unsigned long long ull_value;
538                 char *endp;
539
540                 errno = 0;
541                 ull_value = strtoull(popt_tmp, &endp, 10);
542                 if (*endp || !*popt_tmp || !isdigit(*popt_tmp) ||
543                     (errno == ERANGE && ull_value == ULLONG_MAX) ||
544                     (errno != 0 && ull_value == 0))
545                         r = POPT_ERROR_BADNUMBER;
546
547                 switch(r) {
548                         case 1:
549                                 data_blocks = ull_value;
550                                 break;
551                         case 2:
552                                 hash_offset = ull_value;
553                                 break;
554                 }
555
556                 if (r < 0)
557                         break;
558         }
559
560         if (r < -1)
561                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
562                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
563
564         if (opt_version_mode) {
565                 log_std("%s %s\n", PACKAGE_VERITY, PACKAGE_VERSION);
566                 poptFreeContext(popt_context);
567                 exit(EXIT_SUCCESS);
568         }
569
570         if (!(aname = poptGetArg(popt_context)))
571                 usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."),
572                       poptGetInvocationName(popt_context));
573         for(action = action_types; action->type; action++)
574                 if (strcmp(action->type, aname) == 0)
575                         break;
576         if (!action->type)
577                 usage(popt_context, EXIT_FAILURE, _("Unknown action."),
578                       poptGetInvocationName(popt_context));
579
580         action_argc = 0;
581         action_argv = poptGetArgs(popt_context);
582         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
583         if(!action_argv)
584                 action_argv = null_action_argv;
585
586         /* Count args, somewhat unnice, change? */
587         while(action_argv[action_argc] != NULL)
588                 action_argc++;
589
590         if(action_argc < action->required_action_argc) {
591                 char buf[128];
592                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
593                 usage(popt_context, EXIT_FAILURE, buf,
594                       poptGetInvocationName(popt_context));
595         }
596
597         if (data_block_size < 0 || hash_block_size < 0 || hash_type < 0) {
598                 usage(popt_context, EXIT_FAILURE,
599                       _("Negative number for option not permitted."),
600                       poptGetInvocationName(popt_context));
601         }
602
603         if (opt_debug) {
604                 opt_verbose = 1;
605                 crypt_set_debug_level(-1);
606                 _dbg_version_and_cmd(argc, argv);
607         }
608
609         r = run_action(action);
610         poptFreeContext(popt_context);
611         return r;
612 }