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