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