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