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