de63c52914ec218512ee9321fcc0ee06d54e92f6
[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  * - init_by_name()
22  * - unify units / uint64 etc
23  * - check translations
24  * - support device without superblock
25  * - audit alloc errors / error path
26  * - change command names (cryptsetup style)
27  * - extend superblock (UUID)
28  * - warn if block_size > PAGE_SIZE
29  */
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <errno.h>
35 #include <string.h>
36 #include <popt.h>
37
38 #include "cryptsetup.h"
39
40 #define PACKAGE_VERITY "veritysetup"
41
42 #define MODE_VERIFY     0
43 #define MODE_CREATE     1
44 #define MODE_ACTIVATE   2
45 #define MODE_DUMP       3
46
47 static int mode = -1;
48 static int use_superblock = 1; /* FIXME: no superblock not supported */
49
50 static const char *dm_device = NULL;
51 static const char *data_device = NULL;
52 static const char *hash_device = NULL;
53 static const char *hash_algorithm = NULL;
54 static const char *root_hash = NULL;
55
56 static int version = 1;
57 static int data_block_size = 4096;
58 static int hash_block_size = 4096;
59 static char *data_blocks_string = NULL;
60 static long long data_blocks = 0;
61 static char *hash_start_string = NULL;
62 static const char *salt_string = NULL;
63
64 static unsigned salt_size = 32;
65
66 static off_t superblock_position = 0;
67
68 static int opt_verbose = 0;
69 static int opt_debug = 0;
70 static int opt_version_mode = 0;
71
72 static int hex_to_bytes(const char *hex, char *result)
73 {
74         char buf[3] = "xx\0", *endp;
75         int i, len;
76
77         len = strlen(hex) / 2;
78         for (i = 0; i < len; i++) {
79                 memcpy(buf, &hex[i * 2], 2);
80                 result[i] = strtoul(buf, &endp, 16);
81                 if (endp != &buf[2])
82                         return -EINVAL;
83         }
84         return i;
85 }
86
87 __attribute__((format(printf, 5, 6)))
88 static void clogger(struct crypt_device *cd, int level, const char *file,
89                    int line, const char *format, ...)
90 {
91         va_list argp;
92         char *target = NULL;
93
94         va_start(argp, format);
95
96         if (vasprintf(&target, format, argp) > 0) {
97                 if (level >= 0) {
98                         crypt_log(cd, level, target);
99 #ifdef CRYPT_DEBUG
100                 } else if (opt_debug)
101                         printf("# %s:%d %s\n", file ?: "?", line, target);
102 #else
103                 } else if (opt_debug)
104                         printf("# %s\n", target);
105 #endif
106         }
107
108         va_end(argp);
109         free(target);
110 }
111
112 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
113 {
114         switch(level) {
115
116         case CRYPT_LOG_NORMAL:
117                 fputs(msg, stdout);
118                 break;
119         case CRYPT_LOG_VERBOSE:
120                 if (opt_verbose)
121                         fputs(msg, stdout);
122                 break;
123         case CRYPT_LOG_ERROR:
124                 fputs(msg, stderr);
125                 break;
126         case CRYPT_LOG_DEBUG:
127                 if (opt_debug)
128                         printf("# %s\n", msg);
129                 break;
130         default:
131                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
132                 break;
133         }
134 }
135
136 static int action_dump(void)
137 {
138         struct crypt_device *cd = NULL;
139         struct crypt_params_verity params = {};
140         int r;
141
142         if ((r = crypt_init(&cd, hash_device)))
143                 return r;
144
145         params.hash_area_offset = superblock_position;
146         r = crypt_load(cd, CRYPT_VERITY, &params);
147         if (!r)
148                 crypt_dump(cd);
149         crypt_free(cd);
150         return r;
151 }
152
153 static int action_activate(int verify)
154 {
155         struct crypt_device *cd = NULL;
156         struct crypt_params_verity params = {};
157         uint32_t activate_flags = CRYPT_ACTIVATE_READONLY;
158         char root_hash_bytes[128];
159         int r;
160
161         if ((r = crypt_init(&cd, hash_device)))
162                 goto out;
163
164         if (verify)
165                 params.flags |= CRYPT_VERITY_CHECK_HASH;
166
167         if (use_superblock) {
168                 params.hash_area_offset = superblock_position;
169                 r = crypt_load(cd, CRYPT_VERITY, &params);
170         } else {/*
171                 params.hash_name = hash_algorithm;
172                 params.salt = salt_bytes;
173                 params.salt_size = salt_size;
174                 params.data_block_size = data_block_size;
175                 params.hash_block_size = hash_block_size;
176
177                 params.data_size = data_blocks * data_block_size / 512;
178                 params.version = version;
179                 params.flags |= CRYPT_VERITY_NO_HEADER;
180                 r = crypt_load(cd, CRYPT_VERITY, &params);
181                 crypt_format(); */
182                 r = -EINVAL;
183                 goto out;
184         }
185         if (r < 0)
186                 goto out;
187         r = crypt_set_data_device(cd, data_device);
188         if (r < 0)
189                 goto out;
190
191         if (hex_to_bytes(root_hash, root_hash_bytes) !=
192             crypt_get_volume_key_size(cd)) {
193                 r = -EINVAL;
194                 goto out;
195         }
196         r = crypt_activate_by_volume_key(cd, dm_device, root_hash_bytes,
197                                          crypt_get_volume_key_size(cd),
198                                          activate_flags);
199 out:
200         if (!r)
201                 crypt_dump(cd);
202         crypt_free(cd);
203         return r;
204 }
205
206 static int action_create(void)
207 {
208         struct crypt_device *cd = NULL;
209         struct crypt_params_verity params = {};
210         char salt_bytes[512];
211         int r;
212
213         if ((r = crypt_init(&cd, hash_device)))
214                 goto out;
215
216         params.hash_name = hash_algorithm;
217         params.data_device = data_device;
218
219         if (salt_string) {
220                 if (hex_to_bytes(salt_string, salt_bytes) != salt_size) {
221                         r = -EINVAL;
222                         goto out;
223                 }
224                 params.salt = salt_bytes;
225         }
226
227         params.salt_size = salt_size;
228         params.data_block_size = data_block_size;
229         params.hash_block_size = hash_block_size;
230         params.data_size = data_blocks;
231         params.hash_area_offset = superblock_position;
232         params.version = version;
233         params.flags = CRYPT_VERITY_CREATE_HASH;
234         if (!use_superblock)
235                 params.flags |= CRYPT_VERITY_NO_HEADER;
236
237         r = crypt_format(cd, CRYPT_VERITY, NULL, NULL, NULL, NULL, 0, &params);
238         if (!r)
239                 crypt_dump(cd);
240 out:
241         crypt_free(cd);
242         return r;
243 }
244
245 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
246                                              int exitcode, const char *error,
247                                              const char *more)
248 {
249         poptPrintUsage(popt_context, stderr, 0);
250         if (error)
251                 log_err("%s: %s\n", more, error);
252         poptFreeContext(popt_context);
253         exit(exitcode);
254 }
255
256 static void help(poptContext popt_context,
257                  enum poptCallbackReason reason __attribute__((unused)),
258                  struct poptOption *key,
259                  const char *arg __attribute__((unused)),
260                  void *data __attribute__((unused)))
261 {
262         if (key->shortName == '?') {
263                 log_std("%s %s\n", PACKAGE_VERITY, PACKAGE_VERSION);
264                 poptPrintHelp(popt_context, stdout, 0);
265                 exit(EXIT_SUCCESS);
266         } else
267                 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
268 }
269
270 static void _dbg_version_and_cmd(int argc, const char **argv)
271 {
272         int i;
273
274         log_std("# %s %s processing \"", PACKAGE_VERITY, PACKAGE_VERSION);
275         for (i = 0; i < argc; i++) {
276                 if (i)
277                         log_std(" ");
278                 log_std("%s", argv[i]);
279         }
280         log_std("\"\n");
281 }
282
283 int main(int argc, const char **argv)
284 {
285         static struct poptOption popt_help_options[] = {
286                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
287                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
288                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
289                 POPT_TABLEEND
290         };
291         static struct poptOption popt_options[] = {
292                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
293                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
294                 { "verbose",            0 /*v*/,  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
295                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
296                 { "create",             'c',    POPT_ARG_VAL, &mode, MODE_CREATE, "Create hash", NULL },
297                 { "verify",             'v',    POPT_ARG_VAL, &mode, MODE_VERIFY, "Verify integrity", NULL },
298                 { "activate",           'a',    POPT_ARG_VAL, &mode, MODE_ACTIVATE, "Activate the device", NULL },
299                 { "dump",               'd',    POPT_ARG_VAL, &mode, MODE_DUMP, "Dump the device", NULL },
300                 { "no-superblock",      0,      POPT_ARG_VAL, &use_superblock, 0, "Do not create/use superblock" },
301                 { "format",             0,      POPT_ARG_INT, &version, 0, "Format version (1 - normal format, 0 - original Chromium OS format)", "number" },
302                 { "data-block-size",    0,      POPT_ARG_INT, &data_block_size, 0, "Block size on the data device", "bytes" },
303                 { "hash-block-size",    0,      POPT_ARG_INT, &hash_block_size, 0, "Block size on the hash device", "bytes" },
304                 { "data-blocks",        0,      POPT_ARG_STRING, &data_blocks_string, 0, "The number of blocks in the data file", "blocks" },
305                 { "hash-start",         0,      POPT_ARG_STRING, &hash_start_string, 0, "Starting block on the hash device", "512-byte sectors" },
306                 { "algorithm",          0,      POPT_ARG_STRING, &hash_algorithm, 0, "Hash algorithm (default sha256)", "string" },
307                 { "salt",               0,      POPT_ARG_STRING, &salt_string, 0, "Salt", "hex string" },
308                 POPT_TABLEEND
309         };
310         poptContext popt_context;
311         int r;
312         char *end;
313         static long long hash_start = 0;
314
315         crypt_set_log_callback(NULL, _log, NULL);
316
317         setlocale(LC_ALL, "");
318         bindtextdomain(PACKAGE, LOCALEDIR);
319         textdomain(PACKAGE);
320
321         popt_context = poptGetContext("verity", argc, argv, popt_options, 0);
322
323         poptSetOtherOptionHelp(popt_context, "[-c|-v|-a|-d] [<device name> if activating] <data device> <hash device> [<root hash> if activating or verifying] [OPTION...]");
324
325         if (argc <= 1) {
326                 poptPrintHelp(popt_context, stdout, 0);
327                 exit(1);
328         }
329
330         r = poptGetNextOpt(popt_context);
331         if (r < -1)
332                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
333                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
334         if (opt_version_mode) {
335                 log_std("%s %s\n", PACKAGE_VERITY, PACKAGE_VERSION);
336                 poptFreeContext(popt_context);
337                 exit(EXIT_SUCCESS);
338         }
339
340         if (mode < 0)
341                 usage(popt_context, EXIT_FAILURE, _("Unknown action."),
342                       poptGetInvocationName(popt_context));
343
344         if (mode == MODE_ACTIVATE) {
345                 dm_device = poptGetArg(popt_context);
346                 if (!dm_device || !*dm_device)
347                         usage(popt_context, EXIT_FAILURE,
348                               _("Missing activation device name."),
349                               poptGetInvocationName(popt_context));
350         }
351
352         data_device = poptGetArg(popt_context);
353         if (!data_device)
354                 usage(popt_context, EXIT_FAILURE, _("Missing data device name."),
355                       poptGetInvocationName(popt_context));
356
357         hash_device = poptGetArg(popt_context);
358         if (!hash_device)
359                 usage(popt_context, EXIT_FAILURE, _("Missing hash device name."),
360                       poptGetInvocationName(popt_context));
361
362         if (mode == MODE_ACTIVATE || mode == MODE_VERIFY) {
363                 root_hash = poptGetArg(popt_context);
364                 if (!root_hash)
365                 usage(popt_context, EXIT_FAILURE, _("Root hash not specified."),
366                       poptGetInvocationName(popt_context));
367         }
368
369         if (data_blocks_string) {
370                 data_blocks = strtoll(data_blocks_string, &end, 10);
371                 if (!*data_blocks_string || *end)
372                         usage(popt_context, EXIT_FAILURE,
373                               _("Invalid number of data blocks."),
374                               poptGetInvocationName(popt_context));
375         }
376
377         /* hash start */
378         if (hash_start_string) {
379                 hash_start = strtoll(hash_start_string, &end, 10);
380                 if (!*hash_start_string || *end)
381                         usage(popt_context, EXIT_FAILURE,
382                               _("Invalid hash device offset."),
383                               poptGetInvocationName(popt_context));
384         }
385
386         if (hash_start < 0 ||
387            (unsigned long long)hash_start * 512 / 512 != hash_start ||
388            (off_t)(hash_start * 512) < 0 ||
389            (off_t)(hash_start * 512) != hash_start * 512)
390                 usage(popt_context, EXIT_FAILURE,
391                       _("Invalid hash device offset."),
392                       poptGetInvocationName(popt_context));
393
394         if (use_superblock)
395                 superblock_position = hash_start * 512;
396
397         if (salt_string || !use_superblock) {
398                 if (!salt_string || !strcmp(salt_string, "-"))
399                         salt_string = "";
400                 salt_size = strlen(salt_string) / 2;
401         }
402
403         if (data_block_size < 512 || (data_block_size & (data_block_size - 1)) || data_block_size >= 1U << 31)
404                 usage(popt_context, EXIT_FAILURE, _("Invalid data block size."),
405                       poptGetInvocationName(popt_context));
406
407         if (hash_block_size < 512 || (hash_block_size & (hash_block_size - 1)) || hash_block_size >= 1U << 31)
408                 usage(popt_context, EXIT_FAILURE, _("Invalid hash block size."),
409                       poptGetInvocationName(popt_context));
410
411         if (data_blocks < 0 || (off_t)data_blocks < 0 || (off_t)data_blocks != data_blocks)
412                 usage(popt_context, EXIT_FAILURE, _("Invalid number of data blocks."),
413                       poptGetInvocationName(popt_context));
414
415         if (!hash_algorithm)
416                 hash_algorithm = "sha256";
417
418         if (opt_debug) {
419                 opt_verbose = 1;
420                 crypt_set_debug_level(-1);
421                 _dbg_version_and_cmd(argc, argv);
422         }
423
424         switch (mode) {
425                 case MODE_ACTIVATE:
426                         r = action_activate(0);
427                         break;
428                 case MODE_VERIFY:
429                         r = action_activate(1);
430                         break;
431                 case MODE_CREATE:
432                         r = action_create();
433                         break;
434                 case MODE_DUMP:
435                         r = action_dump();
436                         break;
437         }
438
439         poptFreeContext(popt_context);
440         return r;
441 }