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