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