3bc24c19f60c9bb076f735762fc5c4798d58c09f
[platform/upstream/cryptsetup.git] / src / cryptsetup.c
1 /*
2  * cryptsetup - setup cryptographic volumes for dm-crypt
3  *
4  * Copyright (C) 2004, Christophe Saout <christophe@saout.de>
5  * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
6  * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * version 2 as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include <string.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdint.h>
26 #include <stdarg.h>
27 #include <inttypes.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <ctype.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <assert.h>
34 #include <limits.h>
35 #include <libcryptsetup.h>
36 #include <popt.h>
37
38 #include "cryptsetup.h"
39
40 static int opt_verbose = 0;
41 static int opt_debug = 0;
42 static const char *opt_cipher = NULL;
43 static const char *opt_hash = NULL;
44 static int opt_verify_passphrase = 0;
45 static const char *opt_key_file = NULL;
46 static const char *opt_master_key_file = NULL;
47 static const char *opt_header_backup_file = NULL;
48 static const char *opt_uuid = NULL;
49 static const char *opt_header_device = NULL;
50 static int opt_key_size = 0;
51 static long opt_keyfile_size = 0;
52 static long opt_new_keyfile_size = 0;
53 static long opt_keyfile_offset = 0;
54 static long opt_new_keyfile_offset = 0;
55 static int opt_key_slot = CRYPT_ANY_SLOT;
56 static uint64_t opt_size = 0;
57 static uint64_t opt_offset = 0;
58 static uint64_t opt_skip = 0;
59 static int opt_skip_valid = 0;
60 static int opt_readonly = 0;
61 static int opt_iteration_time = 1000;
62 static int opt_batch_mode = 0;
63 static int opt_version_mode = 0;
64 static int opt_timeout = 0;
65 static int opt_tries = 3;
66 static int opt_align_payload = 0;
67 static int opt_random = 0;
68 static int opt_urandom = 0;
69 static int opt_dump_master_key = 0;
70 static int opt_shared = 0;
71 static int opt_allow_discards = 0;
72
73 static const char **action_argv;
74 static int action_argc;
75
76 static int action_create(int arg);
77 static int action_remove(int arg);
78 static int action_resize(int arg);
79 static int action_status(int arg);
80 static int action_luksFormat(int arg);
81 static int action_luksOpen(int arg);
82 static int action_luksAddKey(int arg);
83 static int action_luksKillSlot(int arg);
84 static int action_luksRemoveKey(int arg);
85 static int action_luksChangeKey(int arg);
86 static int action_isLuks(int arg);
87 static int action_luksUUID(int arg);
88 static int action_luksDump(int arg);
89 static int action_luksSuspend(int arg);
90 static int action_luksResume(int arg);
91 static int action_luksBackup(int arg);
92 static int action_luksRestore(int arg);
93 static int action_loopaesOpen(int arg);
94 static int action_luksRepair(int arg);
95
96 static struct action_type {
97         const char *type;
98         int (*handler)(int);
99         int arg;
100         int required_action_argc;
101         int required_memlock;
102         const char *arg_desc;
103         const char *desc;
104 } action_types[] = {
105         { "create",     action_create,          0, 2, 1, N_("<name> <device>"),N_("create device") },
106         { "remove",     action_remove,          0, 1, 1, N_("<name>"), N_("remove device") },
107         { "resize",     action_resize,          0, 1, 1, N_("<name>"), N_("resize active device") },
108         { "status",     action_status,          0, 1, 0, N_("<name>"), N_("show device status") },
109         { "repair",     action_luksRepair,      0, 1, 1, N_("<device>"), N_("try to repair on-disk metadata") },
110         { "luksFormat", action_luksFormat,      0, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
111         { "luksOpen",   action_luksOpen,        0, 2, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
112         { "luksAddKey", action_luksAddKey,      0, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
113         { "luksRemoveKey",action_luksRemoveKey, 0, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
114         { "luksChangeKey",action_luksChangeKey, 0, 1, 1, N_("<device> [<key file>]"), N_("changes supplied key or key file of LUKS device") },
115         { "luksKillSlot",  action_luksKillSlot, 0, 2, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
116         { "luksUUID",   action_luksUUID,        0, 1, 0, N_("<device>"), N_("print UUID of LUKS device") },
117         { "isLuks",     action_isLuks,          0, 1, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
118         { "luksClose",  action_remove,          0, 1, 1, N_("<name>"), N_("remove LUKS mapping") },
119         { "luksDump",   action_luksDump,        0, 1, 1, N_("<device>"), N_("dump LUKS partition information") },
120         { "luksSuspend",action_luksSuspend,     0, 1, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen).") },
121         { "luksResume", action_luksResume,      0, 1, 1, N_("<device>"), N_("Resume suspended LUKS device.") },
122         { "luksHeaderBackup",action_luksBackup, 0, 1, 1, N_("<device>"), N_("Backup LUKS device header and keyslots") },
123         { "luksHeaderRestore",action_luksRestore,0,1, 1, N_("<device>"), N_("Restore LUKS device header and keyslots") },
124         { "loopaesOpen",action_loopaesOpen,     0, 2, 1, N_("<device> <name> "), N_("open loop-AES device as mapping <name>") },
125         { "loopaesClose",action_remove,         0, 1, 1, N_("<name>"), N_("remove loop-AES mapping") },
126         { NULL, NULL, 0, 0, 0, NULL, NULL }
127 };
128
129 __attribute__((format(printf, 5, 6)))
130 static void clogger(struct crypt_device *cd, int level, const char *file,
131                    int line, const char *format, ...)
132 {
133         va_list argp;
134         char *target = NULL;
135
136         va_start(argp, format);
137
138         if (vasprintf(&target, format, argp) > 0) {
139                 if (level >= 0) {
140                         crypt_log(cd, level, target);
141 #ifdef CRYPT_DEBUG
142                 } else if (opt_debug)
143                         printf("# %s:%d %s\n", file ?: "?", line, target);
144 #else
145                 } else if (opt_debug)
146                         printf("# %s\n", target);
147 #endif
148         }
149
150         va_end(argp);
151         free(target);
152 }
153
154 static int _yesDialog(const char *msg, void *usrptr __attribute__((unused)))
155 {
156         char *answer = NULL;
157         size_t size = 0;
158         int r = 1;
159
160         if(isatty(STDIN_FILENO) && !opt_batch_mode) {
161                 log_std("\nWARNING!\n========\n");
162                 log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
163                 if(getline(&answer, &size, stdin) == -1) {
164                         perror("getline");
165                         free(answer);
166                         return 0;
167                 }
168                 if(strcmp(answer, "YES\n"))
169                         r = 0;
170                 free(answer);
171         }
172
173         return r;
174 }
175
176 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
177 {
178         switch(level) {
179
180         case CRYPT_LOG_NORMAL:
181                 fputs(msg, stdout);
182                 break;
183         case CRYPT_LOG_VERBOSE:
184                 if (opt_verbose)
185                         fputs(msg, stdout);
186                 break;
187         case CRYPT_LOG_ERROR:
188                 fputs(msg, stderr);
189                 break;
190         case CRYPT_LOG_DEBUG:
191                 if (opt_debug)
192                         printf("# %s\n", msg);
193                 break;
194         default:
195                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
196                 break;
197         }
198 }
199
200 static void _quiet_log(int level, const char *msg, void *usrptr)
201 {
202         if (!opt_verbose && (level == CRYPT_LOG_ERROR || level == CRYPT_LOG_NORMAL))
203                 level = CRYPT_LOG_VERBOSE;
204         _log(level, msg, usrptr);
205 }
206
207 static int _verify_passphrase(int def)
208 {
209         /* Batch mode switch off verify - if not overrided by -y */
210         if (opt_verify_passphrase)
211                 def = 1;
212         else if (opt_batch_mode)
213                 def = 0;
214
215         /* Non-tty input doesn't allow verify */
216         if (def && !isatty(STDIN_FILENO)) {
217                 if (opt_verify_passphrase)
218                         log_err(_("Can't do passphrase verification on non-tty inputs.\n"));
219                 def = 0;
220         }
221
222         return def;
223 }
224
225 static void show_status(int errcode)
226 {
227         char error[256], *error_;
228
229         if(!opt_verbose)
230                 return;
231
232         if(!errcode) {
233                 log_std(_("Command successful.\n"));
234                 return;
235         }
236
237         crypt_get_error(error, sizeof(error));
238
239         if (!error[0]) {
240                 error_ = strerror_r(-errcode, error, sizeof(error));
241                 if (error_ != error) {
242                         strncpy(error, error_, sizeof(error));
243                         error[sizeof(error) - 1] = '\0';
244                 }
245         }
246
247         log_err(_("Command failed with code %i"), -errcode);
248         if (*error)
249                 log_err(": %s\n", error);
250         else
251                 log_err(".\n");
252 }
253
254 static const char *uuid_or_device(const char *spec)
255 {
256         static char device[PATH_MAX];
257         char s, *ptr;
258         int i = 0, uuid_len = 5;
259
260         /* Check if it is correct UUID=<LUKS_UUID> format */
261         if (spec && !strncmp(spec, "UUID=", uuid_len)) {
262                 strcpy(device, "/dev/disk/by-uuid/");
263                 ptr = &device[strlen(device)];
264                 i = uuid_len;
265                 while ((s = spec[i++]) && i < PATH_MAX) {
266                         if (!isxdigit(s) && s != '-')
267                                 return spec; /* Bail it out */
268                         if (isalpha(s))
269                                 s = tolower(s);
270                         *ptr++ = s;
271                 }
272                 *ptr = '\0';
273                 return device;
274         }
275
276         return spec;
277 }
278
279 static int action_create(int arg __attribute__((unused)))
280 {
281         struct crypt_device *cd = NULL;
282         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
283         struct crypt_params_plain params = {
284                 .hash = opt_hash ?: DEFAULT_PLAIN_HASH,
285                 .skip = opt_skip,
286                 .offset = opt_offset,
287                 .size = opt_size,
288         };
289         char *password = NULL;
290         size_t passwordLen;
291         size_t key_size = (opt_key_size ?: DEFAULT_PLAIN_KEYBITS) / 8;
292         uint32_t activate_flags = 0;
293         int r;
294
295         if (params.hash && !strcmp(params.hash, "plain"))
296                 params.hash = NULL;
297
298         /* FIXME: temporary hack */
299         if (opt_key_file && strcmp(opt_key_file, "-"))
300                 params.hash = NULL;
301
302         if ((opt_keyfile_offset || opt_keyfile_size) && opt_key_file)
303                 log_std(("Ignoring keyfile offset and size options, keyfile read "
304                          "size is always the same as encryption key size.\n"));
305
306         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(PLAIN),
307                                       cipher, NULL, cipher_mode);
308         if (r < 0) {
309                 log_err("No known cipher specification pattern detected.\n");
310                 goto out;
311         }
312
313         if ((r = crypt_init(&cd, action_argv[1])))
314                 goto out;
315
316         crypt_set_timeout(cd, opt_timeout);
317         crypt_set_password_retry(cd, opt_tries);
318
319         r = crypt_format(cd, CRYPT_PLAIN,
320                          cipher, cipher_mode,
321                          NULL, NULL,
322                          key_size,
323                          &params);
324         if (r < 0)
325                 goto out;
326
327         if (opt_readonly)
328                 activate_flags |= CRYPT_ACTIVATE_READONLY;
329
330         if (opt_shared)
331                 activate_flags |= CRYPT_ACTIVATE_SHARED;
332
333         if (opt_allow_discards)
334                 activate_flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
335
336         if (opt_key_file)
337                 /* With hashing, read the whole keyfile */
338                 r = crypt_activate_by_keyfile_offset(cd, action_argv[0],
339                         CRYPT_ANY_SLOT, opt_key_file,
340                         params.hash ? 0 : key_size, 0,
341                         activate_flags);
342         else {
343                 r = crypt_get_key(_("Enter passphrase: "),
344                                   &password, &passwordLen,
345                                   opt_keyfile_offset, opt_keyfile_size,
346                                   NULL, opt_timeout,
347                                   _verify_passphrase(0),
348                                   cd);
349                 if (r < 0)
350                         goto out;
351
352                 r = crypt_activate_by_passphrase(cd, action_argv[0],
353                         CRYPT_ANY_SLOT, password, passwordLen, activate_flags);
354         }
355 out:
356         crypt_free(cd);
357         crypt_safe_free(password);
358
359         return r;
360 }
361
362 static int action_loopaesOpen(int arg __attribute__((unused)))
363 {
364         struct crypt_device *cd = NULL;
365         struct crypt_params_loopaes params = {
366                 .hash = opt_hash ?: NULL,
367                 .offset = opt_offset,
368                 .skip = opt_skip_valid ? opt_skip : opt_offset,
369         };
370         unsigned int key_size = (opt_key_size ?: DEFAULT_LOOPAES_KEYBITS) / 8;
371         uint32_t activate_flags = 0;
372         int r;
373
374         if (!opt_key_file) {
375                 log_err(_("Option --key-file is required.\n"));
376                 return -EINVAL;
377         }
378
379         if (opt_readonly)
380                 activate_flags |= CRYPT_ACTIVATE_READONLY;
381
382         if (opt_allow_discards)
383                 activate_flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
384
385         if ((r = crypt_init(&cd, action_argv[0])))
386                 goto out;
387
388         r = crypt_format(cd, CRYPT_LOOPAES, opt_cipher ?: DEFAULT_LOOPAES_CIPHER,
389                          NULL, NULL, NULL, key_size, &params);
390         if (r < 0)
391                 goto out;
392
393         r = crypt_activate_by_keyfile_offset(cd, action_argv[1], CRYPT_ANY_SLOT,
394                                       opt_key_file, opt_keyfile_size,
395                                       opt_keyfile_size, activate_flags);
396 out:
397         crypt_free(cd);
398
399         return r;
400 }
401
402 static int action_remove(int arg __attribute__((unused)))
403 {
404         struct crypt_device *cd = NULL;
405         int r;
406
407         r = crypt_init_by_name(&cd, action_argv[0]);
408         if (r == 0)
409                 r = crypt_deactivate(cd, action_argv[0]);
410
411         crypt_free(cd);
412         return r;
413 }
414
415 static int action_resize(int arg __attribute__((unused)))
416 {
417         struct crypt_device *cd = NULL;
418         int r;
419
420         r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device);
421         if (r == 0)
422                 r = crypt_resize(cd, action_argv[0], opt_size);
423
424         crypt_free(cd);
425         return r;
426 }
427
428 static int action_status(int arg __attribute__((unused)))
429 {
430         crypt_status_info ci;
431         struct crypt_active_device cad;
432         struct crypt_device *cd = NULL;
433         struct stat st;
434         char *backing_file;
435         const char *device;
436         int path = 0, r = 0;
437
438         /* perhaps a path, not a dm device name */
439         if (strchr(action_argv[0], '/') && !stat(action_argv[0], &st))
440                 path = 1;
441
442         ci = crypt_status(NULL, action_argv[0]);
443         switch (ci) {
444         case CRYPT_INVALID:
445                 r = -EINVAL;
446                 break;
447         case CRYPT_INACTIVE:
448                 if (path)
449                         log_std("%s is inactive.\n", action_argv[0]);
450                 else
451                         log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]);
452                 r = -ENODEV;
453                 break;
454         case CRYPT_ACTIVE:
455         case CRYPT_BUSY:
456                 if (path)
457                         log_std("%s is active%s.\n", action_argv[0],
458                                 ci == CRYPT_BUSY ? " and is in use" : "");
459                 else
460                         log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0],
461                                 ci == CRYPT_BUSY ? " and is in use" : "");
462
463                 r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device);
464                 if (r < 0 || !crypt_get_type(cd))
465                         goto out;
466
467                 log_std("  type:    %s\n", crypt_get_type(cd));
468
469                 r = crypt_get_active_device(cd, action_argv[0], &cad);
470                 if (r < 0)
471                         goto out;
472
473                 log_std("  cipher:  %s-%s\n", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
474                 log_std("  keysize: %d bits\n", crypt_get_volume_key_size(cd) * 8);
475                 device = crypt_get_device_name(cd);
476                 log_std("  device:  %s\n", device);
477                 if (crypt_loop_device(device)) {
478                         backing_file = crypt_loop_backing_file(device);
479                         log_std("  loop:    %s\n", backing_file);
480                         free(backing_file);
481                 }
482                 log_std("  offset:  %" PRIu64 " sectors\n", cad.offset);
483                 log_std("  size:    %" PRIu64 " sectors\n", cad.size);
484                 if (cad.iv_offset)
485                         log_std("  skipped: %" PRIu64 " sectors\n", cad.iv_offset);
486                 log_std("  mode:    %s\n", cad.flags & CRYPT_ACTIVATE_READONLY ?
487                                            "readonly" : "read/write");
488                 if (cad.flags & CRYPT_ACTIVATE_ALLOW_DISCARDS)
489                         log_std("  flags:   discards\n");
490         }
491 out:
492         crypt_free(cd);
493         return r;
494 }
495
496 static int _read_mk(const char *file, char **key, int keysize)
497 {
498         int fd;
499
500         *key = crypt_safe_alloc(keysize);
501         if (!*key)
502                 return -ENOMEM;
503
504         fd = open(file, O_RDONLY);
505         if (fd == -1) {
506                 log_err("Cannot read keyfile %s.\n", file);
507                 goto fail;
508         }
509         if ((read(fd, *key, keysize) != keysize)) {
510                 log_err("Cannot read %d bytes from keyfile %s.\n", keysize, file);
511                 close(fd);
512                 goto fail;
513         }
514         close(fd);
515         return 0;
516 fail:
517         crypt_safe_free(*key);
518         *key = NULL;
519         return -EINVAL;
520 }
521
522 static int action_luksRepair(int arg __attribute__((unused)))
523 {
524         struct crypt_device *cd = NULL;
525         int r;
526
527         if ((r = crypt_init(&cd, action_argv[0])))
528                 goto out;
529
530         /* Currently only LUKS1 allows repair */
531         crypt_set_log_callback(cd, _quiet_log, NULL);
532         r = crypt_load(cd, CRYPT_LUKS1, NULL);
533         crypt_set_log_callback(cd, _log, NULL);
534         if (r == 0) {
535                 log_verbose( _("No known problems detected for LUKS header.\n"));
536                 goto out;
537         }
538
539         r = _yesDialog(_("Really try to repair LUKS device header?"),
540                        NULL) ? 0 : -EINVAL;
541         if (r == 0)
542                 r = crypt_repair(cd, CRYPT_LUKS1, NULL);
543 out:
544         crypt_free(cd);
545         return r;
546 }
547
548 static int action_luksFormat(int arg __attribute__((unused)))
549 {
550         int r = -EINVAL, keysize;
551         const char *header_device;
552         char *msg = NULL, *key = NULL, cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
553         char *password = NULL;
554         size_t passwordLen;
555         struct crypt_device *cd = NULL;
556         struct crypt_params_luks1 params = {
557                 .hash = opt_hash ?: DEFAULT_LUKS1_HASH,
558                 .data_alignment = opt_align_payload,
559                 .data_device = opt_header_device ? action_argv[0] : NULL,
560         };
561
562         header_device = opt_header_device ?: action_argv[0];
563
564         if(asprintf(&msg, _("This will overwrite data on %s irrevocably."),
565                     header_device) == -1) {
566                 log_err(_("memory allocation error in action_luksFormat"));
567                 r = -ENOMEM;
568                 goto out;
569         }
570         r = _yesDialog(msg, NULL) ? 0 : -EINVAL;
571         free(msg);
572         if (r < 0)
573                 goto out;
574
575         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(LUKS1),
576                                       cipher, NULL, cipher_mode);
577         if (r < 0) {
578                 log_err(_("No known cipher specification pattern detected.\n"));
579                 goto out;
580         }
581
582         if ((r = crypt_init(&cd, header_device))) {
583                 if (opt_header_device)
584                         log_err(_("Cannot use %s as on-disk header.\n"), header_device);
585                 goto out;
586         }
587
588         keysize = (opt_key_size ?: DEFAULT_LUKS1_KEYBITS) / 8;
589
590         crypt_set_timeout(cd, opt_timeout);
591         if (opt_iteration_time)
592                 crypt_set_iteration_time(cd, opt_iteration_time);
593
594         if (opt_random)
595                 crypt_set_rng_type(cd, CRYPT_RNG_RANDOM);
596         else if (opt_urandom)
597                 crypt_set_rng_type(cd, CRYPT_RNG_URANDOM);
598
599         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
600                           opt_keyfile_offset, opt_keyfile_size, opt_key_file,
601                           opt_timeout, _verify_passphrase(1), cd);
602         if (r < 0)
603                 goto out;
604
605         if (opt_master_key_file) {
606                 r = _read_mk(opt_master_key_file, &key, keysize);
607                 if (r < 0)
608                         goto out;
609         }
610
611         r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode,
612                          opt_uuid, key, keysize, &params);
613         if (r < 0)
614                 goto out;
615
616         r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
617                                             key, keysize,
618                                             password, passwordLen);
619 out:
620         crypt_free(cd);
621         crypt_safe_free(key);
622         crypt_safe_free(password);
623
624         return r;
625 }
626
627 static int action_luksOpen(int arg __attribute__((unused)))
628 {
629         struct crypt_device *cd = NULL;
630         const char *data_device, *header_device;
631         char *key = NULL;
632         uint32_t flags = 0;
633         int r, keysize;
634
635         if (opt_header_device) {
636                 header_device = uuid_or_device(opt_header_device);
637                 data_device = action_argv[0];
638         } else {
639                 header_device = uuid_or_device(action_argv[0]);
640                 data_device = NULL;
641         }
642
643         if ((r = crypt_init(&cd, header_device)))
644                 goto out;
645
646         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
647                 goto out;
648
649         if (data_device &&
650             (r = crypt_set_data_device(cd, data_device)))
651                 goto out;
652
653         if (!data_device && (crypt_get_data_offset(cd) < 8)) {
654                 log_err(_("Reduced data offset is allowed only for detached LUKS header.\n"));
655                 r = -EINVAL;
656                 goto out;
657         }
658
659         crypt_set_timeout(cd, opt_timeout);
660         crypt_set_password_retry(cd, opt_tries);
661         crypt_set_password_verify(cd, _verify_passphrase(0));
662
663         if (opt_iteration_time)
664                 crypt_set_iteration_time(cd, opt_iteration_time);
665
666         if (opt_readonly)
667                 flags |= CRYPT_ACTIVATE_READONLY;
668
669         if (opt_allow_discards)
670                 flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
671
672         if (opt_master_key_file) {
673                 keysize = crypt_get_volume_key_size(cd);
674                 r = _read_mk(opt_master_key_file, &key, keysize);
675                 if (r < 0)
676                         goto out;
677                 r = crypt_activate_by_volume_key(cd, action_argv[1],
678                                                  key, keysize, flags);
679         } else if (opt_key_file) {
680                 crypt_set_password_retry(cd, 1);
681                 r = crypt_activate_by_keyfile_offset(cd, action_argv[1],
682                         opt_key_slot, opt_key_file, opt_keyfile_size,
683                         opt_keyfile_offset, flags);
684         } else
685                 r = crypt_activate_by_passphrase(cd, action_argv[1],
686                         opt_key_slot, NULL, 0, flags);
687 out:
688         crypt_safe_free(key);
689         crypt_free(cd);
690         return r;
691 }
692
693 static int verify_keyslot(struct crypt_device *cd, int key_slot,
694                           char *msg_last, char *msg_pass,
695                           const char *key_file, int keyfile_offset,
696                           int keyfile_size)
697 {
698         crypt_keyslot_info ki;
699         char *password = NULL;
700         size_t passwordLen;
701         int i, r;
702
703         ki = crypt_keyslot_status(cd, key_slot);
704         if (ki == CRYPT_SLOT_ACTIVE_LAST && msg_last && !_yesDialog(msg_last, NULL))
705                 return -EPERM;
706
707         r = crypt_get_key(msg_pass, &password, &passwordLen,
708                           keyfile_offset, keyfile_size, key_file, opt_timeout,
709                           _verify_passphrase(0), cd);
710         if(r < 0)
711                 goto out;
712
713         if (ki == CRYPT_SLOT_ACTIVE_LAST) {
714                 /* check the last keyslot */
715                 r = crypt_activate_by_passphrase(cd, NULL, key_slot,
716                                                  password, passwordLen, 0);
717         } else {
718                 /* try all other keyslots */
719                 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) {
720                         if (i == key_slot)
721                                 continue;
722                         ki = crypt_keyslot_status(cd, key_slot);
723                         if (ki == CRYPT_SLOT_ACTIVE)
724                         r = crypt_activate_by_passphrase(cd, NULL, i,
725                                                          password, passwordLen, 0);
726                         if (r == i)
727                                 break;
728                 }
729         }
730
731         if (r < 0)
732                 log_err(_("No key available with this passphrase.\n"));
733 out:
734         crypt_safe_free(password);
735         return r;
736 }
737
738 static int action_luksKillSlot(int arg __attribute__((unused)))
739 {
740         struct crypt_device *cd = NULL;
741         int r;
742
743         if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
744                 goto out;
745
746         crypt_set_confirm_callback(cd, _yesDialog, NULL);
747         crypt_set_timeout(cd, opt_timeout);
748
749         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
750                 goto out;
751
752         switch (crypt_keyslot_status(cd, opt_key_slot)) {
753         case CRYPT_SLOT_ACTIVE_LAST:
754         case CRYPT_SLOT_ACTIVE:
755                 log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
756                 break;
757         case CRYPT_SLOT_INACTIVE:
758                 log_err(_("Key %d not active. Can't wipe.\n"), opt_key_slot);
759         case CRYPT_SLOT_INVALID:
760                 r = -EINVAL;
761                 goto out;
762         }
763
764         if (!opt_batch_mode) {
765                 r = verify_keyslot(cd, opt_key_slot,
766                         _("This is the last keyslot. Device will become unusable after purging this key."),
767                         _("Enter any remaining LUKS passphrase: "),
768                         opt_key_file, opt_keyfile_offset, opt_keyfile_size);
769                 if (r < 0)
770                         goto out;
771         }
772
773         r = crypt_keyslot_destroy(cd, opt_key_slot);
774 out:
775         crypt_free(cd);
776         return r;
777 }
778
779 static int action_luksRemoveKey(int arg __attribute__((unused)))
780 {
781         struct crypt_device *cd = NULL;
782         char *password = NULL;
783         size_t passwordLen;
784         int r;
785
786         if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
787                 goto out;
788
789         crypt_set_confirm_callback(cd, _yesDialog, NULL);
790         crypt_set_timeout(cd, opt_timeout);
791
792         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
793                 goto out;
794
795         r = crypt_get_key(_("Enter LUKS passphrase to be deleted: "),
796                       &password, &passwordLen,
797                       opt_keyfile_offset, opt_keyfile_size, opt_key_file,
798                       opt_timeout,
799                       _verify_passphrase(0),
800                       cd);
801         if(r < 0)
802                 goto out;
803
804         r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT,
805                                          password, passwordLen, 0);
806         if (r < 0)
807                 goto out;
808
809         opt_key_slot = r;
810         log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
811
812         if (crypt_keyslot_status(cd, opt_key_slot) == CRYPT_SLOT_ACTIVE_LAST &&
813             !_yesDialog(_("This is the last keyslot. "
814                           "Device will become unusable after purging this key."),
815                         NULL)) {
816                 r = -EPERM;
817                 goto out;
818         }
819
820         r = crypt_keyslot_destroy(cd, opt_key_slot);
821 out:
822         crypt_safe_free(password);
823         crypt_free(cd);
824         return r;
825 }
826
827 static int action_luksAddKey(int arg __attribute__((unused)))
828 {
829         int r = -EINVAL, keysize = 0;
830         char *key = NULL;
831         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
832         struct crypt_device *cd = NULL;
833
834         if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
835                 goto out;
836
837         crypt_set_confirm_callback(cd, _yesDialog, NULL);
838
839         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
840                 goto out;
841
842         keysize = crypt_get_volume_key_size(cd);
843         /* FIXME: lib cannot properly set verification for new/old passphrase */
844         crypt_set_password_verify(cd, _verify_passphrase(0));
845         crypt_set_timeout(cd, opt_timeout);
846         if (opt_iteration_time)
847                 crypt_set_iteration_time(cd, opt_iteration_time);
848
849         if (opt_master_key_file) {
850                 r = _read_mk(opt_master_key_file, &key, keysize);
851                 if (r < 0)
852                         goto out;
853                 //FIXME: process keyfile arg
854                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
855                                                     key, keysize, NULL, 0);
856         } else if (opt_key_file || opt_new_key_file) {
857                 r = crypt_keyslot_add_by_keyfile_offset(cd, opt_key_slot,
858                         opt_key_file, opt_keyfile_size, opt_keyfile_offset,
859                         opt_new_key_file, opt_new_keyfile_size, opt_new_keyfile_offset);
860         } else {
861                 r = crypt_keyslot_add_by_passphrase(cd, opt_key_slot,
862                                                     NULL, 0, NULL, 0);
863         }
864 out:
865         crypt_free(cd);
866         crypt_safe_free(key);
867         return r;
868 }
869
870 static int _slots_full(struct crypt_device *cd)
871 {
872         int i;
873
874         for (i = 0; i < crypt_keyslot_max(crypt_get_type(cd)); i++)
875                 if (crypt_keyslot_status(cd, i) == CRYPT_SLOT_INACTIVE)
876                         return 0;
877         return 1;
878 }
879
880 static int action_luksChangeKey(int arg __attribute__((unused)))
881 {
882         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
883         struct crypt_device *cd = NULL;
884         char *vk = NULL, *password = NULL;
885         size_t passwordLen = 0;
886         size_t vk_size;
887         int new_key_slot, old_key_slot, r;
888
889         if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
890                 goto out;
891
892         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
893                 goto out;
894
895         if (opt_iteration_time)
896                 crypt_set_iteration_time(cd, opt_iteration_time);
897
898         r = crypt_get_key(_("Enter LUKS passphrase to be changed: "),
899                       &password, &passwordLen,
900                       opt_keyfile_offset, opt_keyfile_size, opt_key_file,
901                       opt_timeout, _verify_passphrase(0), cd);
902         if (r < 0)
903                 goto out;
904
905         vk_size = crypt_get_volume_key_size(cd);
906         vk = crypt_safe_alloc(vk_size);
907         if (!vk) {
908                 r = -ENOMEM;
909                 goto out;
910         }
911
912         r = crypt_volume_key_get(cd, opt_key_slot, vk, &vk_size,
913                                  password, passwordLen);
914         if (r < 0) {
915                 if (opt_key_slot != CRYPT_ANY_SLOT)
916                         log_err(_("No key available with this passphrase.\n"));
917                 goto out;
918         }
919
920         if (opt_key_slot != CRYPT_ANY_SLOT || _slots_full(cd)) {
921                 log_dbg("Key slot %d is going to be overwritten (%s).",
922                         r, opt_key_slot != CRYPT_ANY_SLOT ?
923                         "explicit key slot specified" : "no free key slot");
924                 old_key_slot = r;
925                 new_key_slot = r;
926         } else {
927                 log_dbg("Allocating new key slot.");
928                 old_key_slot = r;
929                 new_key_slot = CRYPT_ANY_SLOT;
930         }
931
932         crypt_safe_free(password);
933         password = NULL;
934         passwordLen = 0;
935         r = crypt_get_key(_("Enter new LUKS passphrase: "),
936                           &password, &passwordLen,
937                           opt_new_keyfile_offset, opt_new_keyfile_size,
938                           opt_new_key_file,
939                           opt_timeout, _verify_passphrase(0), cd);
940         if (r < 0)
941                 goto out;
942
943         if (new_key_slot == old_key_slot) {
944                 (void)crypt_keyslot_destroy(cd, old_key_slot);
945                 r = crypt_keyslot_add_by_volume_key(cd, new_key_slot,
946                                                     vk, vk_size,
947                                                     password, passwordLen);
948                 if (r >= 0)
949                         log_verbose(_("Key slot %d changed.\n"), r);
950         } else {
951                 r = crypt_keyslot_add_by_volume_key(cd, CRYPT_ANY_SLOT,
952                                                     vk, vk_size,
953                                                     password, passwordLen);
954                 if (r >= 0) {
955                         log_verbose(_("Replaced with key slot %d.\n"), r);
956                         r = crypt_keyslot_destroy(cd, old_key_slot);
957                 }
958         }
959         if (r < 0)
960                 log_err(_("Failed to swap new key slot.\n"));
961 out:
962         crypt_safe_free(vk);
963         crypt_safe_free(password);
964         crypt_free(cd);
965         return r;
966 }
967
968 static int action_isLuks(int arg __attribute__((unused)))
969 {
970         struct crypt_device *cd = NULL;
971         int r;
972
973         if ((r = crypt_init(&cd, action_argv[0])))
974                 goto out;
975
976         crypt_set_log_callback(cd, _quiet_log, NULL);
977         r = crypt_load(cd, CRYPT_LUKS1, NULL);
978 out:
979         crypt_free(cd);
980         return r;
981 }
982
983 static int action_luksUUID(int arg __attribute__((unused)))
984 {
985         struct crypt_device *cd = NULL;
986         const char *existing_uuid = NULL;
987         int r;
988
989         if ((r = crypt_init(&cd, action_argv[0])))
990                 goto out;
991
992         crypt_set_confirm_callback(cd, _yesDialog, NULL);
993
994         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
995                 goto out;
996
997         if (opt_uuid)
998                 r = crypt_set_uuid(cd, opt_uuid);
999         else {
1000                 existing_uuid = crypt_get_uuid(cd);
1001                 log_std("%s\n", existing_uuid ?: "");
1002                 r = existing_uuid ? 0 : 1;
1003         }
1004 out:
1005         crypt_free(cd);
1006         return r;
1007 }
1008
1009 static int luksDump_with_volume_key(struct crypt_device *cd)
1010 {
1011         char *vk = NULL, *password = NULL;
1012         size_t passwordLen = 0;
1013         size_t vk_size;
1014         unsigned i;
1015         int r;
1016
1017         crypt_set_confirm_callback(cd, _yesDialog, NULL);
1018         if (!_yesDialog(
1019             _("LUKS header dump with volume key is sensitive information\n"
1020               "which allows access to encrypted partition without passphrase.\n"
1021               "This dump should be always stored encrypted on safe place."),
1022               NULL))
1023                 return -EPERM;
1024
1025         vk_size = crypt_get_volume_key_size(cd);
1026         vk = crypt_safe_alloc(vk_size);
1027         if (!vk)
1028                 return -ENOMEM;
1029
1030         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
1031                           opt_keyfile_offset, opt_keyfile_size, opt_key_file,
1032                           opt_timeout, 0, cd);
1033         if (r < 0)
1034                 goto out;
1035
1036         r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size,
1037                                  password, passwordLen);
1038         if (r < 0)
1039                 goto out;
1040
1041         log_std("LUKS header information for %s\n", crypt_get_device_name(cd));
1042         log_std("Cipher name:   \t%s\n", crypt_get_cipher(cd));
1043         log_std("Cipher mode:   \t%s\n", crypt_get_cipher_mode(cd));
1044         log_std("Payload offset:\t%d\n", (int)crypt_get_data_offset(cd));
1045         log_std("UUID:          \t%s\n", crypt_get_uuid(cd));
1046         log_std("MK bits:       \t%d\n", (int)vk_size * 8);
1047         log_std("MK dump:\t");
1048
1049         for(i = 0; i < vk_size; i++) {
1050                 if (i && !(i % 16))
1051                         log_std("\n\t\t");
1052                 log_std("%02hhx ", (char)vk[i]);
1053         }
1054         log_std("\n");
1055
1056 out:
1057         crypt_safe_free(password);
1058         crypt_safe_free(vk);
1059         return r;
1060 }
1061
1062 static int action_luksDump(int arg __attribute__((unused)))
1063 {
1064         struct crypt_device *cd = NULL;
1065         int r;
1066
1067         if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
1068                 goto out;
1069
1070         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
1071                 goto out;
1072
1073         if (opt_dump_master_key)
1074                 r = luksDump_with_volume_key(cd);
1075         else
1076                 r = crypt_dump(cd);
1077 out:
1078         crypt_free(cd);
1079         return r;
1080 }
1081
1082 static int action_luksSuspend(int arg __attribute__((unused)))
1083 {
1084         struct crypt_device *cd = NULL;
1085         int r;
1086
1087         r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device);
1088         if (!r)
1089                 r = crypt_suspend(cd, action_argv[0]);
1090
1091         crypt_free(cd);
1092         return r;
1093 }
1094
1095 static int action_luksResume(int arg __attribute__((unused)))
1096 {
1097         struct crypt_device *cd = NULL;
1098         int r;
1099
1100         if ((r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device)))
1101                 goto out;
1102
1103         crypt_set_timeout(cd, opt_timeout);
1104         crypt_set_password_retry(cd, opt_tries);
1105         crypt_set_password_verify(cd, _verify_passphrase(0));
1106
1107         if (opt_key_file)
1108                 r = crypt_resume_by_keyfile_offset(cd, action_argv[0], CRYPT_ANY_SLOT,
1109                         opt_key_file, opt_keyfile_size, opt_keyfile_offset);
1110         else
1111                 r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
1112                                                NULL, 0);
1113 out:
1114         crypt_free(cd);
1115         return r;
1116 }
1117
1118 static int action_luksBackup(int arg __attribute__((unused)))
1119 {
1120         struct crypt_device *cd = NULL;
1121         int r;
1122
1123         if (!opt_header_backup_file) {
1124                 log_err(_("Option --header-backup-file is required.\n"));
1125                 return -EINVAL;
1126         }
1127
1128         if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
1129                 goto out;
1130
1131         crypt_set_confirm_callback(cd, _yesDialog, NULL);
1132
1133         r = crypt_header_backup(cd, CRYPT_LUKS1, opt_header_backup_file);
1134 out:
1135         crypt_free(cd);
1136         return r;
1137 }
1138
1139 static int action_luksRestore(int arg __attribute__((unused)))
1140 {
1141         struct crypt_device *cd = NULL;
1142         int r = 0;
1143
1144         if (!opt_header_backup_file) {
1145                 log_err(_("Option --header-backup-file is required.\n"));
1146                 return -EINVAL;
1147         }
1148
1149         if ((r = crypt_init(&cd, action_argv[0])))
1150                 goto out;
1151
1152         crypt_set_confirm_callback(cd, _yesDialog, NULL);
1153         r = crypt_header_restore(cd, CRYPT_LUKS1, opt_header_backup_file);
1154 out:
1155         crypt_free(cd);
1156         return r;
1157 }
1158
1159 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
1160                                              int exitcode, const char *error,
1161                                              const char *more)
1162 {
1163         poptPrintUsage(popt_context, stderr, 0);
1164         if (error)
1165                 log_err("%s: %s\n", more, error);
1166         poptFreeContext(popt_context);
1167         exit(exitcode);
1168 }
1169
1170 static void help(poptContext popt_context,
1171                  enum poptCallbackReason reason __attribute__((unused)),
1172                  struct poptOption *key,
1173                  const char *arg __attribute__((unused)),
1174                  void *data __attribute__((unused)))
1175 {
1176         if (key->shortName == '?') {
1177                 struct action_type *action;
1178
1179                 log_std("%s\n",PACKAGE_STRING);
1180
1181                 poptPrintHelp(popt_context, stdout, 0);
1182
1183                 log_std(_("\n"
1184                          "<action> is one of:\n"));
1185
1186                 for(action = action_types; action->type; action++)
1187                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
1188
1189                 log_std(_("\n"
1190                          "<name> is the device to create under %s\n"
1191                          "<device> is the encrypted device\n"
1192                          "<key slot> is the LUKS key slot number to modify\n"
1193                          "<key file> optional key file for the new key for luksAddKey action\n"),
1194                         crypt_get_dir());
1195
1196                 log_std(_("\nDefault compiled-in keyfile parameters:\n"
1197                          "\tMaximum keyfile size: %dkB, "
1198                          "Maximum interactive passphrase length %d (characters)\n"),
1199                          DEFAULT_KEYFILE_SIZE_MAXKB, DEFAULT_PASSPHRASE_SIZE_MAX);
1200
1201                 log_std(_("\nDefault compiled-in device cipher parameters:\n"
1202                          "\tloop-AES: %s, Key %d bits\n"
1203                          "\tplain: %s, Key: %d bits, Password hashing: %s\n"
1204                          "\tLUKS1: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
1205                          DEFAULT_LOOPAES_CIPHER, DEFAULT_LOOPAES_KEYBITS,
1206                          DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
1207                          DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
1208                          DEFAULT_RNG);
1209                 exit(EXIT_SUCCESS);
1210         } else
1211                 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1212 }
1213
1214 static void _dbg_version_and_cmd(int argc, const char **argv)
1215 {
1216         int i;
1217
1218         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
1219         for (i = 0; i < argc; i++) {
1220                 if (i)
1221                         log_std(" ");
1222                 log_std("%s", argv[i]);
1223         }
1224         log_std("\"\n");
1225 }
1226
1227 static int run_action(struct action_type *action)
1228 {
1229         int r;
1230
1231         log_dbg("Running command %s.", action->type);
1232
1233         if (action->required_memlock)
1234                 crypt_memory_lock(NULL, 1);
1235
1236         r = action->handler(action->arg);
1237
1238         if (action->required_memlock)
1239                 crypt_memory_lock(NULL, 0);
1240
1241         /* Some functions returns keyslot # */
1242         if (r > 0)
1243                 r = 0;
1244
1245         show_status(r);
1246
1247         /* Translate exit code to simple codes */
1248         switch (r) {
1249         case 0:         r = EXIT_SUCCESS; break;
1250         case -EEXIST:
1251         case -EBUSY:    r = 5; break;
1252         case -ENOTBLK:
1253         case -ENODEV:   r = 4; break;
1254         case -ENOMEM:   r = 3; break;
1255         case -EPERM:    r = 2; break;
1256         case -EINVAL:
1257         case -ENOENT:
1258         case -ENOSYS:
1259         default:        r = EXIT_FAILURE;
1260         }
1261         return r;
1262 }
1263
1264 int main(int argc, const char **argv)
1265 {
1266         static char *popt_tmp;
1267         static struct poptOption popt_help_options[] = {
1268                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
1269                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
1270                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
1271                 POPT_TABLEEND
1272         };
1273         static struct poptOption popt_options[] = {
1274                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1275                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
1276                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
1277                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
1278                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1279                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1280                 { "verify-passphrase", 'y',  POPT_ARG_NONE, &opt_verify_passphrase,     0, N_("Verifies the passphrase by asking for it twice"), NULL },
1281                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
1282                 { "master-key-file",  '\0',  POPT_ARG_STRING, &opt_master_key_file,     0, N_("Read the volume (master) key from file."), NULL },
1283                 { "dump-master-key",  '\0',  POPT_ARG_NONE, &opt_dump_master_key,       0, N_("Dump volume (master) key instead of keyslots info."), NULL },
1284                 { "key-size",          's',  POPT_ARG_INT, &opt_key_size,               0, N_("The size of the encryption key"), N_("BITS") },
1285                 { "keyfile-size",      'l',  POPT_ARG_LONG, &opt_keyfile_size,          0, N_("Limits the read from keyfile"), N_("bytes") },
1286                 { "keyfile-offset",   '\0',  POPT_ARG_LONG, &opt_keyfile_offset,        0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1287                 { "new-keyfile-size", '\0',  POPT_ARG_LONG, &opt_new_keyfile_size,      0, N_("Limits the read from newly added keyfile"), N_("bytes") },
1288                 { "new-keyfile-offset",'\0', POPT_ARG_LONG, &opt_new_keyfile_offset,    0, N_("Number of bytes to skip in newly added keyfile"), N_("bytes") },
1289                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Slot number for new key (default is first free)"), NULL },
1290                 { "size",              'b',  POPT_ARG_STRING, &popt_tmp,                1, N_("The size of the device"), N_("SECTORS") },
1291                 { "offset",            'o',  POPT_ARG_STRING, &popt_tmp,                2, N_("The start offset in the backend device"), N_("SECTORS") },
1292                 { "skip",              'p',  POPT_ARG_STRING, &popt_tmp,                3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
1293                 { "readonly",          'r',  POPT_ARG_NONE, &opt_readonly,              0, N_("Create a readonly mapping"), NULL },
1294                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1295                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
1296                 { "timeout",           't',  POPT_ARG_INT, &opt_timeout,                0, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs") },
1297                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
1298                 { "align-payload",     '\0', POPT_ARG_INT, &opt_align_payload,          0, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS") },
1299                 { "header-backup-file",'\0', POPT_ARG_STRING, &opt_header_backup_file,  0, N_("File with LUKS header and keyslots backup."), NULL },
1300                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
1301                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
1302                 { "shared",            '\0', POPT_ARG_NONE, &opt_shared,                0, N_("Share device with another non-overlapping crypt segment."), NULL },
1303                 { "uuid",              '\0', POPT_ARG_STRING, &opt_uuid,                0, N_("UUID for device to use."), NULL },
1304                 { "allow-discards",    '\0', POPT_ARG_NONE, &opt_allow_discards,        0, N_("Allow discards (aka TRIM) requests for device."), NULL },
1305                 { "header",            '\0', POPT_ARG_STRING, &opt_header_device,       0, N_("Device or file with separated LUKS header."), NULL },
1306                 POPT_TABLEEND
1307         };
1308         poptContext popt_context;
1309         struct action_type *action;
1310         const char *aname;
1311         int r;
1312         const char *null_action_argv[] = {NULL};
1313
1314         crypt_set_log_callback(NULL, _log, NULL);
1315
1316         setlocale(LC_ALL, "");
1317         bindtextdomain(PACKAGE, LOCALEDIR);
1318         textdomain(PACKAGE);
1319
1320         crypt_fips_self_check(NULL);
1321
1322         popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1323         poptSetOtherOptionHelp(popt_context,
1324                                N_("[OPTION...] <action> <action-specific>]"));
1325
1326         while((r = poptGetNextOpt(popt_context)) > 0) {
1327                 unsigned long long ull_value;
1328                 char *endp;
1329
1330                 errno = 0;
1331                 ull_value = strtoull(popt_tmp, &endp, 0);
1332                 if (*endp || !*popt_tmp ||
1333                     (errno == ERANGE && ull_value == ULLONG_MAX) ||
1334                     (errno != 0 && ull_value == 0))
1335                         r = POPT_ERROR_BADNUMBER;
1336
1337                 switch(r) {
1338                         case 1:
1339                                 opt_size = ull_value;
1340                                 break;
1341                         case 2:
1342                                 opt_offset = ull_value;
1343                                 break;
1344                         case 3:
1345                                 opt_skip = ull_value;
1346                                 opt_skip_valid = 1;
1347                                 break;
1348                 }
1349
1350                 if (r < 0)
1351                         break;
1352         }
1353
1354         if (r < -1)
1355                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1356                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1357         if (opt_version_mode) {
1358                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1359                 poptFreeContext(popt_context);
1360                 exit(EXIT_SUCCESS);
1361         }
1362
1363         if (!(aname = poptGetArg(popt_context)))
1364                 usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."),
1365                       poptGetInvocationName(popt_context));
1366         for(action = action_types; action->type; action++)
1367                 if (strcmp(action->type, aname) == 0)
1368                         break;
1369         if (!action->type)
1370                 usage(popt_context, EXIT_FAILURE, _("Unknown action."),
1371                       poptGetInvocationName(popt_context));
1372
1373         action_argc = 0;
1374         action_argv = poptGetArgs(popt_context);
1375         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
1376         if(!action_argv)
1377                 action_argv = null_action_argv;
1378
1379         /* Count args, somewhat unnice, change? */
1380         while(action_argv[action_argc] != NULL)
1381                 action_argc++;
1382
1383         if(action_argc < action->required_action_argc) {
1384                 char buf[128];
1385                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
1386                 usage(popt_context, EXIT_FAILURE, buf,
1387                       poptGetInvocationName(popt_context));
1388         }
1389
1390         /* FIXME: rewrite this from scratch */
1391
1392         if (opt_shared && strcmp(aname, "create")) {
1393                 usage(popt_context, EXIT_FAILURE,
1394                       _("Option --shared is allowed only for create operation.\n"),
1395                       poptGetInvocationName(popt_context));
1396         }
1397
1398         if (opt_allow_discards &&
1399             strcmp(aname, "luksOpen") &&
1400             strcmp(aname, "create") &&
1401             strcmp(aname, "loopaesOpen")) {
1402                 usage(popt_context, EXIT_FAILURE,
1403                       _("Option --allow-discards is allowed only for luksOpen, loopaesOpen and create operation.\n"),
1404                       poptGetInvocationName(popt_context));
1405         }
1406
1407         if (opt_key_size &&
1408            strcmp(aname, "luksFormat") &&
1409            strcmp(aname, "create") &&
1410            strcmp(aname, "loopaesOpen")) {
1411                 usage(popt_context, EXIT_FAILURE,
1412                       _("Option --key-size is allowed only for luksFormat, create and loopaesOpen.\n"
1413                         "To limit read from keyfile use --keyfile-size=(bytes)."),
1414                       poptGetInvocationName(popt_context));
1415         }
1416
1417         if (opt_key_size % 8)
1418                 usage(popt_context, EXIT_FAILURE,
1419                       _("Key size must be a multiple of 8 bits"),
1420                       poptGetInvocationName(popt_context));
1421
1422         if (!strcmp(aname, "luksKillSlot") && action_argc > 1)
1423                 opt_key_slot = atoi(action_argv[1]);
1424         if (opt_key_slot != CRYPT_ANY_SLOT &&
1425             (opt_key_slot < 0 || opt_key_slot >= crypt_keyslot_max(CRYPT_LUKS1)))
1426                 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1427                       poptGetInvocationName(popt_context));
1428
1429         if ((!strcmp(aname, "luksRemoveKey") ||
1430              !strcmp(aname, "luksFormat")) &&
1431              action_argc > 1) {
1432                 if (opt_key_file)
1433                         log_err(_("Option --key-file takes precedence over specified key file argument.\n"));
1434                 else
1435                         opt_key_file = action_argv[1];
1436         }
1437
1438         if (opt_keyfile_size < 0 || opt_new_keyfile_size < 0 || opt_key_size < 0 ||
1439             opt_keyfile_offset < 0 || opt_new_keyfile_offset < 0) {
1440                 usage(popt_context, EXIT_FAILURE,
1441                       _("Negative number for option not permitted."),
1442                       poptGetInvocationName(popt_context));
1443         }
1444
1445         if (opt_random && opt_urandom)
1446                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1447                       poptGetInvocationName(popt_context));
1448
1449         if ((opt_random || opt_urandom) && strcmp(aname, "luksFormat"))
1450                 usage(popt_context, EXIT_FAILURE, _("Option --use-[u]random is allowed only for luksFormat."),
1451                       poptGetInvocationName(popt_context));
1452
1453         if (opt_uuid && strcmp(aname, "luksFormat") && strcmp(aname, "luksUUID"))
1454                 usage(popt_context, EXIT_FAILURE, _("Option --uuid is allowed only for luksFormat and luksUUID."),
1455                       poptGetInvocationName(popt_context));
1456
1457         if (opt_align_payload && strcmp(aname, "luksFormat"))
1458                 usage(popt_context, EXIT_FAILURE, _("Option --align-payload is allowed only for luksFormat."),
1459                       poptGetInvocationName(popt_context));
1460
1461         if (opt_skip && strcmp(aname, "create") && strcmp(aname, "loopaesOpen"))
1462                 usage(popt_context, EXIT_FAILURE,
1463                 _("Option --skip is supported only for create and loopaesOpen commands.\n"),
1464                 poptGetInvocationName(popt_context));
1465
1466         if (opt_offset && strcmp(aname, "create") && strcmp(aname, "loopaesOpen"))
1467                 usage(popt_context, EXIT_FAILURE,
1468                 _("Option --offset is supported only for create and loopaesOpen commands.\n"),
1469                 poptGetInvocationName(popt_context));
1470
1471         if (opt_debug) {
1472                 opt_verbose = 1;
1473                 crypt_set_debug_level(-1);
1474                 _dbg_version_and_cmd(argc, argv);
1475         }
1476
1477         r = run_action(action);
1478         poptFreeContext(popt_context);
1479         return r;
1480 }