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