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