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