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