Fails if more device arguments are present for isLuks.
[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  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 #include "cryptsetup.h"
22
23 #define PACKAGE_VERITY "veritysetup"
24
25 static int use_superblock = 1;
26
27 static const char *hash_algorithm = NULL;
28 static int hash_type = 1;
29 static int data_block_size = DEFAULT_VERITY_DATA_BLOCK;
30 static int hash_block_size = DEFAULT_VERITY_HASH_BLOCK;
31 static uint64_t data_blocks = 0;
32 static const char *salt_string = NULL;
33 static uint64_t hash_offset = 0;
34 static const char *opt_uuid = NULL;
35
36 static int opt_version_mode = 0;
37
38 static const char **action_argv;
39 static int action_argc;
40
41 static int _prepare_format(struct crypt_params_verity *params,
42                            const char *data_device,
43                            uint32_t flags)
44 {
45         char *salt = NULL;
46         int len;
47
48         params->hash_name = hash_algorithm ?: DEFAULT_VERITY_HASH;
49         params->data_device = data_device;
50
51         if (salt_string && !strcmp(salt_string, "-")) {
52                 params->salt_size = 0;
53                 params->salt = NULL;
54         } else if (salt_string) {
55                 len = crypt_hex_to_bytes(salt_string, &salt, 0);
56                 if (len < 0) {
57                         log_err(_("Invalid salt string specified.\n"));
58                         return -EINVAL;
59                 }
60                 params->salt_size = len;
61                 params->salt = salt;
62         } else {
63                 params->salt_size = DEFAULT_VERITY_SALT_SIZE;
64                 params->salt = NULL;
65         }
66
67         params->data_block_size = data_block_size;
68         params->hash_block_size = hash_block_size;
69         params->data_size = data_blocks;
70         params->hash_area_offset = hash_offset;
71         params->hash_type = hash_type;
72         params->flags = flags;
73
74         return 0;
75 }
76
77 static int action_format(int arg)
78 {
79         struct crypt_device *cd = NULL;
80         struct crypt_params_verity params = {};
81         uint32_t flags = CRYPT_VERITY_CREATE_HASH;
82         int r;
83
84         /* Try to create hash image if doesn't exist */
85         r = open(action_argv[1], O_WRONLY | O_EXCL | O_CREAT, S_IRUSR | S_IWUSR);
86         if (r < 0 && errno != EEXIST) {
87                 log_err(_("Cannot create hash image %s for writing.\n"), action_argv[1]);
88                 return -EINVAL;
89         } else if (r >= 0) {
90                 log_dbg("Created hash image %s.", action_argv[1]);
91                 close(r);
92         }
93
94         if ((r = crypt_init(&cd, action_argv[1])))
95                 goto out;
96
97         if (!use_superblock)
98                 flags |= CRYPT_VERITY_NO_HEADER;
99
100         r = _prepare_format(&params, action_argv[0], flags);
101         if (r < 0)
102                 goto out;
103
104         r = crypt_format(cd, CRYPT_VERITY, NULL, NULL, opt_uuid, NULL, 0, &params);
105         if (!r)
106                 crypt_dump(cd);
107 out:
108         crypt_free(cd);
109         free(CONST_CAST(char*)params.salt);
110         return r;
111 }
112
113 static int _activate(const char *dm_device,
114                       const char *data_device,
115                       const char *hash_device,
116                       const char *root_hash,
117                       uint32_t flags)
118 {
119         struct crypt_device *cd = NULL;
120         struct crypt_params_verity params = {};
121         uint32_t activate_flags = CRYPT_ACTIVATE_READONLY;
122         char *root_hash_bytes = NULL;
123         ssize_t hash_size;
124         int r;
125
126         if ((r = crypt_init(&cd, hash_device)))
127                 goto out;
128
129         if (use_superblock) {
130                 params.flags = flags;
131                 params.hash_area_offset = hash_offset;
132                 r = crypt_load(cd, CRYPT_VERITY, &params);
133         } else {
134                 r = _prepare_format(&params, data_device, flags | CRYPT_VERITY_NO_HEADER);
135                 if (r < 0)
136                         goto out;
137                 r = crypt_format(cd, CRYPT_VERITY, NULL, NULL, NULL, NULL, 0, &params);
138         }
139         if (r < 0)
140                 goto out;
141         r = crypt_set_data_device(cd, data_device);
142         if (r < 0)
143                 goto out;
144
145         hash_size = crypt_get_volume_key_size(cd);
146         if (crypt_hex_to_bytes(root_hash, &root_hash_bytes, 0) != hash_size) {
147                 log_err(_("Invalid root hash string specified.\n"));
148                 r = -EINVAL;
149                 goto out;
150         }
151         r = crypt_activate_by_volume_key(cd, dm_device,
152                                          root_hash_bytes,
153                                          hash_size,
154                                          activate_flags);
155 out:
156         crypt_free(cd);
157         free(root_hash_bytes);
158         free(CONST_CAST(char*)params.salt);
159         return r;
160 }
161
162 static int action_create(int arg)
163 {
164         return _activate(action_argv[0],
165                          action_argv[1],
166                          action_argv[2],
167                          action_argv[3], 0);
168 }
169
170 static int action_verify(int arg)
171 {
172         return _activate(NULL,
173                          action_argv[0],
174                          action_argv[1],
175                          action_argv[2],
176                          CRYPT_VERITY_CHECK_HASH);
177 }
178
179 static int action_remove(int arg)
180 {
181         struct crypt_device *cd = NULL;
182         int r;
183
184         r = crypt_init_by_name(&cd, action_argv[0]);
185         if (r == 0)
186                 r = crypt_deactivate(cd, action_argv[0]);
187
188         crypt_free(cd);
189         return r;
190 }
191
192 static int action_status(int arg)
193 {
194         crypt_status_info ci;
195         struct crypt_active_device cad;
196         struct crypt_params_verity vp = {};
197         struct crypt_device *cd = NULL;
198         struct stat st;
199         char *backing_file;
200         unsigned i, path = 0;
201         int r = 0;
202
203         /* perhaps a path, not a dm device name */
204         if (strchr(action_argv[0], '/') && !stat(action_argv[0], &st))
205                 path = 1;
206
207         ci = crypt_status(NULL, action_argv[0]);
208         switch (ci) {
209         case CRYPT_INVALID:
210                 r = -EINVAL;
211                 break;
212         case CRYPT_INACTIVE:
213                 if (path)
214                         log_std("%s is inactive.\n", action_argv[0]);
215                 else
216                         log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]);
217                 r = -ENODEV;
218                 break;
219         case CRYPT_ACTIVE:
220         case CRYPT_BUSY:
221                 if (path)
222                         log_std("%s is active%s.\n", action_argv[0],
223                                 ci == CRYPT_BUSY ? " and is in use" : "");
224                 else
225                         log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0],
226                                 ci == CRYPT_BUSY ? " and is in use" : "");
227
228                 r = crypt_init_by_name_and_header(&cd, action_argv[0], NULL);
229                 if (r < 0 || !crypt_get_type(cd))
230                         goto out;
231
232                 log_std("  type:        %s\n", crypt_get_type(cd));
233
234                 r = crypt_get_active_device(cd, action_argv[0], &cad);
235                 if (r < 0)
236                         goto out;
237
238                 log_std("  status:      %s\n",
239                         cad.flags & CRYPT_ACTIVATE_CORRUPTED ? "corrupted" : "verified");
240
241                 r = crypt_get_verity_info(cd, &vp);
242                 if (r < 0)
243                         goto out;
244
245                 log_std("  hash type:   %u\n", vp.hash_type);
246                 log_std("  data block:  %u\n", vp.data_block_size);
247                 log_std("  hash block:  %u\n", vp.hash_block_size);
248                 log_std("  hash name:   %s\n", vp.hash_name);
249                 log_std("  salt:        ");
250                 if (vp.salt_size)
251                         for(i = 0; i < vp.salt_size; i++)
252                                 log_std("%02hhx", (const char)vp.salt[i]);
253                 else
254                         log_std("-");
255                 log_std("\n");
256
257                 log_std("  data device: %s\n", vp.data_device);
258                 if (crypt_loop_device(vp.data_device)) {
259                         backing_file = crypt_loop_backing_file(vp.data_device);
260                         log_std("  data loop:   %s\n", backing_file);
261                         free(backing_file);
262                 }
263                 log_std("  size:        %" PRIu64 " sectors\n", cad.size);
264                 log_std("  mode:        %s\n", cad.flags & CRYPT_ACTIVATE_READONLY ?
265                                            "readonly" : "read/write");
266
267                 log_std("  hash device: %s\n", vp.hash_device);
268                 if (crypt_loop_device(vp.hash_device)) {
269                         backing_file = crypt_loop_backing_file(vp.hash_device);
270                         log_std("  hash loop:   %s\n", backing_file);
271                         free(backing_file);
272                 }
273                 log_std("  hash offset: %" PRIu64 " sectors\n",
274                         vp.hash_area_offset * vp.hash_block_size / 512);
275         }
276 out:
277         crypt_free(cd);
278         if (r == -ENOTSUP)
279                 r = 0;
280         return r;
281 }
282
283 static int action_dump(int arg)
284 {
285         struct crypt_device *cd = NULL;
286         struct crypt_params_verity params = {};
287         int r;
288
289         if ((r = crypt_init(&cd, action_argv[0])))
290                 return r;
291
292         params.hash_area_offset = hash_offset;
293         r = crypt_load(cd, CRYPT_VERITY, &params);
294         if (!r)
295                 crypt_dump(cd);
296         crypt_free(cd);
297         return r;
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 int run_action(struct action_type *action)
350 {
351         int r;
352
353         log_dbg("Running command %s.", action->type);
354
355         r = action->handler(0);
356
357         show_status(r);
358         return translate_errno(r);
359 }
360
361 int main(int argc, const char **argv)
362 {
363         static char *popt_tmp;
364         static const char *null_action_argv[] = {NULL};
365         static struct poptOption popt_help_options[] = {
366                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
367                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
368                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
369                 POPT_TABLEEND
370         };
371         static struct poptOption popt_options[] = {
372                 { NULL,              '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
373                 { "version",         '\0', POPT_ARG_NONE, &opt_version_mode, 0, N_("Print package version"), NULL },
374                 { "verbose",         'v',  POPT_ARG_NONE, &opt_verbose,      0, N_("Shows more detailed error messages"), NULL },
375                 { "debug",           '\0', POPT_ARG_NONE, &opt_debug,        0, N_("Show debug messages"), NULL },
376                 { "no-superblock",   0,    POPT_ARG_VAL,  &use_superblock,   0, N_("Do not use verity superblock"), NULL },
377                 { "format",          0,    POPT_ARG_INT,  &hash_type,        0, N_("Format type (1 - normal, 0 - original Chrome OS)"), N_("number") },
378                 { "data-block-size", 0,    POPT_ARG_INT,  &data_block_size,  0, N_("Block size on the data device"), N_("bytes") },
379                 { "hash-block-size", 0,    POPT_ARG_INT,  &hash_block_size,  0, N_("Block size on the hash device"), N_("bytes") },
380                 { "data-blocks",     0,    POPT_ARG_STRING, &popt_tmp,       1, N_("The number of blocks in the data file"), N_("blocks") },
381                 { "hash-offset",     0,    POPT_ARG_STRING, &popt_tmp,       2, N_("Starting offset on the hash device"), N_("bytes") },
382                 { "hash",            'h',  POPT_ARG_STRING, &hash_algorithm, 0, N_("Hash algorithm"), N_("string") },
383                 { "salt",            's',  POPT_ARG_STRING, &salt_string,    0, N_("Salt"), N_("hex string") },
384                 { "uuid",            '\0', POPT_ARG_STRING, &opt_uuid,       0, N_("UUID for device to use."), NULL },
385                 POPT_TABLEEND
386         };
387
388         poptContext popt_context;
389         struct action_type *action;
390         const char *aname;
391         int r;
392
393         crypt_set_log_callback(NULL, tool_log, NULL);
394
395         setlocale(LC_ALL, "");
396         bindtextdomain(PACKAGE, LOCALEDIR);
397         textdomain(PACKAGE);
398
399         popt_context = poptGetContext("verity", argc, argv, popt_options, 0);
400         poptSetOtherOptionHelp(popt_context,
401                                _("[OPTION...] <action> <action-specific>"));
402
403         while((r = poptGetNextOpt(popt_context)) > 0) {
404                 unsigned long long ull_value;
405                 char *endp;
406
407                 errno = 0;
408                 ull_value = strtoull(popt_tmp, &endp, 10);
409                 if (*endp || !*popt_tmp || !isdigit(*popt_tmp) ||
410                     (errno == ERANGE && ull_value == ULLONG_MAX) ||
411                     (errno != 0 && ull_value == 0))
412                         r = POPT_ERROR_BADNUMBER;
413
414                 switch(r) {
415                         case 1:
416                                 data_blocks = ull_value;
417                                 break;
418                         case 2:
419                                 hash_offset = ull_value;
420                                 break;
421                 }
422
423                 if (r < 0)
424                         break;
425         }
426
427         if (r < -1)
428                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
429                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
430
431         if (opt_version_mode) {
432                 log_std("%s %s\n", PACKAGE_VERITY, PACKAGE_VERSION);
433                 poptFreeContext(popt_context);
434                 exit(EXIT_SUCCESS);
435         }
436
437         if (!(aname = poptGetArg(popt_context)))
438                 usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."),
439                       poptGetInvocationName(popt_context));
440         for(action = action_types; action->type; action++)
441                 if (strcmp(action->type, aname) == 0)
442                         break;
443         if (!action->type)
444                 usage(popt_context, EXIT_FAILURE, _("Unknown action."),
445                       poptGetInvocationName(popt_context));
446
447         action_argc = 0;
448         action_argv = poptGetArgs(popt_context);
449         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
450         if(!action_argv)
451                 action_argv = null_action_argv;
452
453         /* Count args, somewhat unnice, change? */
454         while(action_argv[action_argc] != NULL)
455                 action_argc++;
456
457         if(action_argc < action->required_action_argc) {
458                 char buf[128];
459                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
460                 usage(popt_context, EXIT_FAILURE, buf,
461                       poptGetInvocationName(popt_context));
462         }
463
464         if (data_block_size < 0 || hash_block_size < 0 || hash_type < 0) {
465                 usage(popt_context, EXIT_FAILURE,
466                       _("Negative number for option not permitted."),
467                       poptGetInvocationName(popt_context));
468         }
469
470         if (opt_debug) {
471                 opt_verbose = 1;
472                 crypt_set_debug_level(-1);
473                 dbg_version_and_cmd(argc, argv);
474         }
475
476         r = run_action(action);
477         poptFreeContext(popt_context);
478         return r;
479 }