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