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