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