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