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