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