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