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