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