3e66975e84f25df0412d6340bccbde173fadfdb3
[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), 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), 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), 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), 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), 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), 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         char *password = NULL, *password_new = NULL;
884         size_t password_size = 0, password_new_size = 0;
885         struct crypt_device *cd = NULL;
886
887         if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
888                 goto out;
889
890         crypt_set_confirm_callback(cd, yesDialog, NULL);
891
892         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
893                 goto out;
894
895         keysize = crypt_get_volume_key_size(cd);
896         /* FIXME: lib cannot properly set verification for new/old passphrase */
897         crypt_set_password_verify(cd, _verify_passphrase(0));
898         crypt_set_timeout(cd, opt_timeout);
899         if (opt_iteration_time)
900                 crypt_set_iteration_time(cd, opt_iteration_time);
901
902         if (opt_master_key_file) {
903                 r = _read_mk(opt_master_key_file, &key, keysize);
904                 if (r < 0)
905                         goto out;
906                 //FIXME: process keyfile arg
907                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
908                                                     key, keysize, NULL, 0);
909         } else if (opt_key_file || opt_new_key_file) {
910                 r = crypt_keyslot_add_by_keyfile_offset(cd, opt_key_slot,
911                         opt_key_file, opt_keyfile_size, opt_keyfile_offset,
912                         opt_new_key_file, opt_new_keyfile_size, opt_new_keyfile_offset);
913         } else {
914                 r = tools_get_key(_("Enter any passphrase: "),
915                               &password, &password_size, 0, 0, NULL,
916                               opt_timeout, _verify_passphrase(0), 0, cd);
917
918                 if (r < 0)
919                         goto out;
920
921                 /* Check password before asking for new one */
922                 r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT,
923                                                  password, password_size, 0);
924                 check_signal(&r);
925                 if (r < 0)
926                         goto out;
927
928                 r = tools_get_key(_("Enter new passphrase for key slot: "),
929                                   &password_new, &password_new_size, 0, 0, NULL,
930                                   opt_timeout, _verify_passphrase(0), 1, cd);
931                 if (r < 0)
932                         goto out;
933
934                 r = crypt_keyslot_add_by_passphrase(cd, opt_key_slot,
935                                                     password, password_size,
936                                                     password_new, password_new_size);
937         }
938 out:
939         crypt_safe_free(password);
940         crypt_safe_free(password_new);
941         crypt_safe_free(key);
942         crypt_free(cd);
943         return r;
944 }
945
946 static int action_luksChangeKey(void)
947 {
948         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
949         struct crypt_device *cd = NULL;
950         char *password = NULL, *password_new = NULL;
951         size_t password_size = 0, password_new_size = 0;
952         int r;
953
954         if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
955                 goto out;
956
957         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
958                 goto out;
959
960         if (opt_iteration_time)
961                 crypt_set_iteration_time(cd, opt_iteration_time);
962
963         r = tools_get_key(_("Enter LUKS passphrase to be changed: "),
964                       &password, &password_size,
965                       opt_keyfile_offset, opt_keyfile_size, opt_key_file,
966                       opt_timeout, _verify_passphrase(0), 0, cd);
967         if (r < 0)
968                 goto out;
969
970         /* Check password before asking for new one */
971         r = crypt_activate_by_passphrase(cd, NULL, opt_key_slot,
972                                          password, password_size, 0);
973         check_signal(&r);
974         if (r < 0)
975                 goto out;
976
977         r = tools_get_key(_("Enter new LUKS passphrase: "),
978                           &password_new, &password_new_size,
979                           opt_new_keyfile_offset, opt_new_keyfile_size,
980                           opt_new_key_file,
981                           opt_timeout, _verify_passphrase(0), 1, cd);
982         if (r < 0)
983                 goto out;
984
985         r = crypt_keyslot_change_by_passphrase(cd, opt_key_slot, opt_key_slot,
986                 password, password_size, password_new, password_new_size);
987 out:
988         crypt_safe_free(password);
989         crypt_safe_free(password_new);
990         crypt_free(cd);
991         return r;
992 }
993
994 static int action_isLuks(void)
995 {
996         struct crypt_device *cd = NULL;
997         int r;
998
999         if ((r = crypt_init(&cd, action_argv[0])))
1000                 goto out;
1001
1002         crypt_set_log_callback(cd, quiet_log, NULL);
1003         r = crypt_load(cd, CRYPT_LUKS1, NULL);
1004 out:
1005         crypt_free(cd);
1006         return r;
1007 }
1008
1009 static int action_luksUUID(void)
1010 {
1011         struct crypt_device *cd = NULL;
1012         const char *existing_uuid = NULL;
1013         int r;
1014
1015         if ((r = crypt_init(&cd, action_argv[0])))
1016                 goto out;
1017
1018         crypt_set_confirm_callback(cd, yesDialog, NULL);
1019
1020         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
1021                 goto out;
1022
1023         if (opt_uuid)
1024                 r = crypt_set_uuid(cd, opt_uuid);
1025         else {
1026                 existing_uuid = crypt_get_uuid(cd);
1027                 log_std("%s\n", existing_uuid ?: "");
1028                 r = existing_uuid ? 0 : 1;
1029         }
1030 out:
1031         crypt_free(cd);
1032         return r;
1033 }
1034
1035 static int luksDump_with_volume_key(struct crypt_device *cd)
1036 {
1037         char *vk = NULL, *password = NULL;
1038         size_t passwordLen = 0;
1039         size_t vk_size;
1040         unsigned i;
1041         int r;
1042
1043         crypt_set_confirm_callback(cd, yesDialog, NULL);
1044         if (!yesDialog(
1045             _("Header dump with volume key is sensitive information\n"
1046               "which allows access to encrypted partition without passphrase.\n"
1047               "This dump should be always stored encrypted on safe place."),
1048               NULL))
1049                 return -EPERM;
1050
1051         vk_size = crypt_get_volume_key_size(cd);
1052         vk = crypt_safe_alloc(vk_size);
1053         if (!vk)
1054                 return -ENOMEM;
1055
1056         r = tools_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
1057                           opt_keyfile_offset, opt_keyfile_size, opt_key_file,
1058                           opt_timeout, 0, 0, cd);
1059         if (r < 0)
1060                 goto out;
1061
1062         r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size,
1063                                  password, passwordLen);
1064         check_signal(&r);
1065         if (r < 0)
1066                 goto out;
1067
1068         log_std("LUKS header information for %s\n", crypt_get_device_name(cd));
1069         log_std("Cipher name:   \t%s\n", crypt_get_cipher(cd));
1070         log_std("Cipher mode:   \t%s\n", crypt_get_cipher_mode(cd));
1071         log_std("Payload offset:\t%d\n", (int)crypt_get_data_offset(cd));
1072         log_std("UUID:          \t%s\n", crypt_get_uuid(cd));
1073         log_std("MK bits:       \t%d\n", (int)vk_size * 8);
1074         log_std("MK dump:\t");
1075
1076         for(i = 0; i < vk_size; i++) {
1077                 if (i && !(i % 16))
1078                         log_std("\n\t\t");
1079                 log_std("%02hhx ", (char)vk[i]);
1080         }
1081         log_std("\n");
1082
1083 out:
1084         crypt_safe_free(password);
1085         crypt_safe_free(vk);
1086         return r;
1087 }
1088
1089 static int action_luksDump(void)
1090 {
1091         struct crypt_device *cd = NULL;
1092         int r;
1093
1094         if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
1095                 goto out;
1096
1097         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
1098                 goto out;
1099
1100         if (opt_dump_master_key)
1101                 r = luksDump_with_volume_key(cd);
1102         else
1103                 r = crypt_dump(cd);
1104 out:
1105         crypt_free(cd);
1106         return r;
1107 }
1108
1109 static int action_luksSuspend(void)
1110 {
1111         struct crypt_device *cd = NULL;
1112         int r;
1113
1114         r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device);
1115         if (!r)
1116                 r = crypt_suspend(cd, action_argv[0]);
1117
1118         crypt_free(cd);
1119         return r;
1120 }
1121
1122 static int action_luksResume(void)
1123 {
1124         struct crypt_device *cd = NULL;
1125         int r;
1126
1127         if ((r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device)))
1128                 goto out;
1129
1130         crypt_set_timeout(cd, opt_timeout);
1131         crypt_set_password_retry(cd, opt_tries);
1132         crypt_set_password_verify(cd, _verify_passphrase(0));
1133
1134         if (opt_key_file)
1135                 r = crypt_resume_by_keyfile_offset(cd, action_argv[0], CRYPT_ANY_SLOT,
1136                         opt_key_file, opt_keyfile_size, opt_keyfile_offset);
1137         else
1138                 r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
1139                                                NULL, 0);
1140 out:
1141         crypt_free(cd);
1142         return r;
1143 }
1144
1145 static int action_luksBackup(void)
1146 {
1147         struct crypt_device *cd = NULL;
1148         int r;
1149
1150         if (!opt_header_backup_file) {
1151                 log_err(_("Option --header-backup-file is required.\n"));
1152                 return -EINVAL;
1153         }
1154
1155         if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
1156                 goto out;
1157
1158         crypt_set_confirm_callback(cd, yesDialog, NULL);
1159
1160         r = crypt_header_backup(cd, CRYPT_LUKS1, opt_header_backup_file);
1161 out:
1162         crypt_free(cd);
1163         return r;
1164 }
1165
1166 static int action_luksRestore(void)
1167 {
1168         struct crypt_device *cd = NULL;
1169         int r = 0;
1170
1171         if (!opt_header_backup_file) {
1172                 log_err(_("Option --header-backup-file is required.\n"));
1173                 return -EINVAL;
1174         }
1175
1176         if ((r = crypt_init(&cd, action_argv[0])))
1177                 goto out;
1178
1179         crypt_set_confirm_callback(cd, yesDialog, NULL);
1180         r = crypt_header_restore(cd, CRYPT_LUKS1, opt_header_backup_file);
1181 out:
1182         crypt_free(cd);
1183         return r;
1184 }
1185
1186 static int action_open(void)
1187 {
1188         if (!opt_type)
1189                 return -EINVAL;
1190
1191         if (!strcmp(opt_type, "luks") || !strcmp(opt_type, "luks1")) {
1192                 if (action_argc < 2 && !opt_test_passphrase)
1193                         goto args;
1194                 return action_open_luks();
1195         } else if (!strcmp(opt_type, "plain")) {
1196                 if (action_argc < 2)
1197                         goto args;
1198                 return action_open_plain();
1199         } else if (!strcmp(opt_type, "loopaes")) {
1200                 if (action_argc < 2)
1201                         goto args;
1202                 return action_open_loopaes();
1203         } else if (!strcmp(opt_type, "tcrypt")) {
1204                 if (action_argc < 2 && !opt_test_passphrase)
1205                         goto args;
1206                 return action_open_tcrypt();
1207         }
1208
1209         log_err(_("Unrecognized metadata device type %s.\n"), opt_type);
1210         return -EINVAL;
1211 args:
1212         log_err(_("Command requires device and mapped name as arguments.\n"));
1213         return -EINVAL;
1214 }
1215
1216 static struct action_type {
1217         const char *type;
1218         int (*handler)(void);
1219         int required_action_argc;
1220         int required_memlock;
1221         const char *arg_desc;
1222         const char *desc;
1223 } action_types[] = {
1224         { "open",         action_open,         1, 1, N_("<device> [--type <type>] [<name>]"),N_("open device as mapping <name>") },
1225         { "close",        action_close,        1, 1, N_("<name>"), N_("close device (remove mapping)") },
1226         { "resize",       action_resize,       1, 1, N_("<name>"), N_("resize active device") },
1227         { "status",       action_status,       1, 0, N_("<name>"), N_("show device status") },
1228         { "benchmark",    action_benchmark,    0, 0, N_("<name>"), N_("benchmark cipher") },
1229         { "repair",       action_luksRepair,   1, 1, N_("<device>"), N_("try to repair on-disk metadata") },
1230         { "luksFormat",   action_luksFormat,   1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
1231         { "luksAddKey",   action_luksAddKey,   1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
1232         { "luksRemoveKey",action_luksRemoveKey,1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
1233         { "luksChangeKey",action_luksChangeKey,1, 1, N_("<device> [<key file>]"), N_("changes supplied key or key file of LUKS device") },
1234         { "luksKillSlot", action_luksKillSlot, 2, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
1235         { "luksUUID",     action_luksUUID,     1, 0, N_("<device>"), N_("print UUID of LUKS device") },
1236         { "isLuks",       action_isLuks,       1, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
1237         { "luksDump",     action_luksDump,     1, 1, N_("<device>"), N_("dump LUKS partition information") },
1238         { "tcryptDump",   action_tcryptDump,   1, 1, N_("<device>"), N_("dump TCRYPT device information") },
1239         { "luksSuspend",  action_luksSuspend,  1, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen).") },
1240         { "luksResume",   action_luksResume,   1, 1, N_("<device>"), N_("Resume suspended LUKS device.") },
1241         { "luksHeaderBackup", action_luksBackup,1,1, N_("<device>"), N_("Backup LUKS device header and keyslots") },
1242         { "luksHeaderRestore",action_luksRestore,1,1,N_("<device>"), N_("Restore LUKS device header and keyslots") },
1243         {}
1244 };
1245
1246 static void help(poptContext popt_context,
1247                  enum poptCallbackReason reason __attribute__((unused)),
1248                  struct poptOption *key,
1249                  const char *arg __attribute__((unused)),
1250                  void *data __attribute__((unused)))
1251 {
1252         if (key->shortName == '?') {
1253                 struct action_type *action;
1254
1255                 log_std("%s\n",PACKAGE_STRING);
1256
1257                 poptPrintHelp(popt_context, stdout, 0);
1258
1259                 log_std(_("\n"
1260                          "<action> is one of:\n"));
1261
1262                 for(action = action_types; action->type; action++)
1263                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
1264
1265                 log_std(_("\n"
1266                           "You can also use old <action> syntax aliases:\n"
1267                           "\topen: create (plainOpen), luksOpen, loopaesOpen, tcryptOpen\n"
1268                           "\tclose: remove (plainClose), luksClose, loopaesClose, tcryptClose\n"));
1269                 log_std(_("\n"
1270                          "<name> is the device to create under %s\n"
1271                          "<device> is the encrypted device\n"
1272                          "<key slot> is the LUKS key slot number to modify\n"
1273                          "<key file> optional key file for the new key for luksAddKey action\n"),
1274                         crypt_get_dir());
1275
1276                 log_std(_("\nDefault compiled-in key and passphrase parameters:\n"
1277                          "\tMaximum keyfile size: %dkB, "
1278                          "Maximum interactive passphrase length %d (characters)\n"
1279                          "Default PBKDF2 iteration time for LUKS: %d (ms)\n"),
1280                          DEFAULT_KEYFILE_SIZE_MAXKB, DEFAULT_PASSPHRASE_SIZE_MAX,
1281                          DEFAULT_LUKS1_ITER_TIME);
1282
1283                 log_std(_("\nDefault compiled-in device cipher parameters:\n"
1284                          "\tloop-AES: %s, Key %d bits\n"
1285                          "\tplain: %s, Key: %d bits, Password hashing: %s\n"
1286                          "\tLUKS1: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
1287                          DEFAULT_LOOPAES_CIPHER, DEFAULT_LOOPAES_KEYBITS,
1288                          DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
1289                          DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
1290                          DEFAULT_RNG);
1291                 exit(EXIT_SUCCESS);
1292         } else
1293                 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1294 }
1295
1296 static void help_args(struct action_type *action, poptContext popt_context)
1297 {
1298         char buf[128];
1299
1300         snprintf(buf, sizeof(buf), _("%s: requires %s as arguments"), action->type, action->arg_desc);
1301         usage(popt_context, EXIT_FAILURE, buf, poptGetInvocationName(popt_context));
1302 }
1303
1304 static int run_action(struct action_type *action)
1305 {
1306         int r;
1307
1308         log_dbg("Running command %s.", action->type);
1309
1310         if (action->required_memlock)
1311                 crypt_memory_lock(NULL, 1);
1312
1313         set_int_handler(0);
1314         r = action->handler();
1315
1316         if (action->required_memlock)
1317                 crypt_memory_lock(NULL, 0);
1318
1319         /* Some functions returns keyslot # */
1320         if (r > 0)
1321                 r = 0;
1322         check_signal(&r);
1323
1324         show_status(r);
1325         return translate_errno(r);
1326 }
1327
1328 int main(int argc, const char **argv)
1329 {
1330         static char *popt_tmp;
1331         static struct poptOption popt_help_options[] = {
1332                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
1333                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
1334                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
1335                 POPT_TABLEEND
1336         };
1337         static struct poptOption popt_options[] = {
1338                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1339                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
1340                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
1341                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
1342                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1343                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1344                 { "verify-passphrase", 'y',  POPT_ARG_NONE, &opt_verify_passphrase,     0, N_("Verifies the passphrase by asking for it twice"), NULL },
1345                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            5, N_("Read the key from a file."), NULL },
1346                 { "master-key-file",  '\0',  POPT_ARG_STRING, &opt_master_key_file,     0, N_("Read the volume (master) key from file."), NULL },
1347                 { "dump-master-key",  '\0',  POPT_ARG_NONE, &opt_dump_master_key,       0, N_("Dump volume (master) key instead of keyslots info."), NULL },
1348                 { "key-size",          's',  POPT_ARG_INT, &opt_key_size,               0, N_("The size of the encryption key"), N_("BITS") },
1349                 { "keyfile-size",      'l',  POPT_ARG_LONG, &opt_keyfile_size,          0, N_("Limits the read from keyfile"), N_("bytes") },
1350                 { "keyfile-offset",   '\0',  POPT_ARG_LONG, &opt_keyfile_offset,        0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1351                 { "new-keyfile-size", '\0',  POPT_ARG_LONG, &opt_new_keyfile_size,      0, N_("Limits the read from newly added keyfile"), N_("bytes") },
1352                 { "new-keyfile-offset",'\0', POPT_ARG_LONG, &opt_new_keyfile_offset,    0, N_("Number of bytes to skip in newly added keyfile"), N_("bytes") },
1353                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Slot number for new key (default is first free)"), NULL },
1354                 { "size",              'b',  POPT_ARG_STRING, &popt_tmp,                1, N_("The size of the device"), N_("SECTORS") },
1355                 { "offset",            'o',  POPT_ARG_STRING, &popt_tmp,                2, N_("The start offset in the backend device"), N_("SECTORS") },
1356                 { "skip",              'p',  POPT_ARG_STRING, &popt_tmp,                3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
1357                 { "readonly",          'r',  POPT_ARG_NONE, &opt_readonly,              0, N_("Create a readonly mapping"), NULL },
1358                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1359                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
1360                 { "timeout",           't',  POPT_ARG_INT, &opt_timeout,                0, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs") },
1361                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
1362                 { "align-payload",     '\0', POPT_ARG_INT, &opt_align_payload,          0, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS") },
1363                 { "header-backup-file",'\0', POPT_ARG_STRING, &opt_header_backup_file,  0, N_("File with LUKS header and keyslots backup."), NULL },
1364                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
1365                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
1366                 { "shared",            '\0', POPT_ARG_NONE, &opt_shared,                0, N_("Share device with another non-overlapping crypt segment."), NULL },
1367                 { "uuid",              '\0', POPT_ARG_STRING, &opt_uuid,                0, N_("UUID for device to use."), NULL },
1368                 { "allow-discards",    '\0', POPT_ARG_NONE, &opt_allow_discards,        0, N_("Allow discards (aka TRIM) requests for device."), NULL },
1369                 { "header",            '\0', POPT_ARG_STRING, &opt_header_device,       0, N_("Device or file with separated LUKS header."), NULL },
1370                 { "test-passphrase",   '\0', POPT_ARG_NONE, &opt_test_passphrase,       0, N_("Do not activate device, just check passphrase."), NULL },
1371                 { "hidden",            '\0', POPT_ARG_NONE, &opt_hidden,                0, N_("Use hidden header (hidden TCRYPT device) ."), NULL },
1372                 { "type",              'M',  POPT_ARG_STRING, &opt_type,                0, N_("Type of device metadata: luks, plain, loopaes, tcrypt."), NULL },
1373                 POPT_TABLEEND
1374         };
1375         poptContext popt_context;
1376         struct action_type *action;
1377         const char *aname;
1378         int r;
1379
1380         crypt_set_log_callback(NULL, tool_log, NULL);
1381
1382         setlocale(LC_ALL, "");
1383         bindtextdomain(PACKAGE, LOCALEDIR);
1384         textdomain(PACKAGE);
1385
1386         crypt_fips_self_check(NULL);
1387
1388         popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1389         poptSetOtherOptionHelp(popt_context,
1390                                _("[OPTION...] <action> <action-specific>"));
1391
1392         while((r = poptGetNextOpt(popt_context)) > 0) {
1393                 unsigned long long ull_value;
1394                 char *endp;
1395
1396                 if (r == 5) {
1397                         if (opt_keyfiles_count < MAX_KEYFILES)
1398                                 opt_keyfiles[opt_keyfiles_count++] = poptGetOptArg(popt_context);
1399                         continue;
1400                 }
1401
1402                 errno = 0;
1403                 ull_value = strtoull(popt_tmp, &endp, 0);
1404                 if (*endp || !*popt_tmp ||
1405                     (errno == ERANGE && ull_value == ULLONG_MAX) ||
1406                     (errno != 0 && ull_value == 0))
1407                         r = POPT_ERROR_BADNUMBER;
1408
1409                 switch(r) {
1410                         case 1:
1411                                 opt_size = ull_value;
1412                                 break;
1413                         case 2:
1414                                 opt_offset = ull_value;
1415                                 break;
1416                         case 3:
1417                                 opt_skip = ull_value;
1418                                 opt_skip_valid = 1;
1419                                 break;
1420                 }
1421
1422                 if (r < 0)
1423                         break;
1424         }
1425
1426         if (r < -1)
1427                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1428                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1429         if (opt_version_mode) {
1430                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1431                 poptFreeContext(popt_context);
1432                 exit(EXIT_SUCCESS);
1433         }
1434
1435         if (!(aname = poptGetArg(popt_context)))
1436                 usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."),
1437                       poptGetInvocationName(popt_context));
1438
1439         action_argc = 0;
1440         action_argv = poptGetArgs(popt_context);
1441         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
1442         if(!action_argv)
1443                 action_argv = null_action_argv;
1444
1445         /* Count args, somewhat unnice, change? */
1446         while(action_argv[action_argc] != NULL)
1447                 action_argc++;
1448
1449         /* Handle aliases */
1450         if (!strcmp(aname, "create")) {
1451                 /* create command had historically switched arguments */
1452                 if (action_argv[0] && action_argv[1]) {
1453                         const char *tmp = action_argv[0];
1454                         action_argv[0] = action_argv[1];
1455                         action_argv[1] = tmp;
1456                 }
1457                 aname = "open";
1458                 opt_type = "plain";
1459         } else if (!strcmp(aname, "plainOpen")) {
1460                 aname = "open";
1461                 opt_type = "plain";
1462         } else if (!strcmp(aname, "luksOpen")) {
1463                 aname = "open";
1464                 opt_type = "luks";
1465         } else if (!strcmp(aname, "loopaesOpen")) {
1466                 aname = "open";
1467                 opt_type = "loopaes";
1468         } else if (!strcmp(aname, "tcryptOpen")) {
1469                 aname = "open";
1470                 opt_type = "tcrypt";
1471         } else if (!strcmp(aname, "remove") ||
1472                    !strcmp(aname, "plainClose") ||
1473                    !strcmp(aname, "luksClose") ||
1474                    !strcmp(aname, "loopaesClose") ||
1475                    !strcmp(aname, "tcryptClose")) {
1476                 aname = "close";
1477         }
1478
1479         for(action = action_types; action->type; action++)
1480                 if (strcmp(action->type, aname) == 0)
1481                         break;
1482
1483         if (!action->type)
1484                 usage(popt_context, EXIT_FAILURE, _("Unknown action."),
1485                       poptGetInvocationName(popt_context));
1486
1487         if(action_argc < action->required_action_argc)
1488                 help_args(action, popt_context);
1489
1490         /* FIXME: rewrite this from scratch */
1491
1492         if (opt_shared && (strcmp(aname, "open") || strcmp(opt_type, "plain")) )
1493                 usage(popt_context, EXIT_FAILURE,
1494                       _("Option --shared is allowed only for open of plain device.\n"),
1495                       poptGetInvocationName(popt_context));
1496
1497         if (opt_allow_discards && strcmp(aname, "open"))
1498                 usage(popt_context, EXIT_FAILURE,
1499                       _("Option --allow-discards is allowed only for open operation.\n"),
1500                       poptGetInvocationName(popt_context));
1501
1502         if (opt_key_size &&
1503            strcmp(aname, "luksFormat") &&
1504            strcmp(aname, "open") &&
1505            strcmp(aname, "benchmark"))
1506                 usage(popt_context, EXIT_FAILURE,
1507                       _("Option --key-size is allowed only for luksFormat, open and benchmark.\n"
1508                         "To limit read from keyfile use --keyfile-size=(bytes)."),
1509                       poptGetInvocationName(popt_context));
1510
1511         if (opt_test_passphrase && (strcmp(aname, "open") ||
1512             (strcmp(opt_type, "luks") && strcmp(opt_type, "tcrypt"))))
1513                 usage(popt_context, EXIT_FAILURE,
1514                       _("Option --test-passphrase is allowed only for open of LUKS and TCRYPT devices.\n"),
1515                       poptGetInvocationName(popt_context));
1516
1517         if (opt_key_size % 8)
1518                 usage(popt_context, EXIT_FAILURE,
1519                       _("Key size must be a multiple of 8 bits"),
1520                       poptGetInvocationName(popt_context));
1521
1522         if (!strcmp(aname, "luksKillSlot") && action_argc > 1)
1523                 opt_key_slot = atoi(action_argv[1]);
1524         if (opt_key_slot != CRYPT_ANY_SLOT &&
1525             (opt_key_slot < 0 || opt_key_slot >= crypt_keyslot_max(CRYPT_LUKS1)))
1526                 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1527                       poptGetInvocationName(popt_context));
1528
1529         if ((!strcmp(aname, "luksRemoveKey") ||
1530              !strcmp(aname, "luksFormat")) &&
1531              action_argc > 1) {
1532                 if (opt_key_file)
1533                         log_err(_("Option --key-file takes precedence over specified key file argument.\n"));
1534                 else
1535                         opt_key_file = action_argv[1];
1536         }
1537
1538         if (opt_keyfile_size < 0 || opt_new_keyfile_size < 0 || opt_key_size < 0 ||
1539             opt_keyfile_offset < 0 || opt_new_keyfile_offset < 0)
1540                 usage(popt_context, EXIT_FAILURE,
1541                       _("Negative number for option not permitted."),
1542                       poptGetInvocationName(popt_context));
1543
1544         if (opt_random && opt_urandom)
1545                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1546                       poptGetInvocationName(popt_context));
1547
1548         if ((opt_random || opt_urandom) && strcmp(aname, "luksFormat"))
1549                 usage(popt_context, EXIT_FAILURE, _("Option --use-[u]random is allowed only for luksFormat."),
1550                       poptGetInvocationName(popt_context));
1551
1552         if (opt_uuid && strcmp(aname, "luksFormat") && strcmp(aname, "luksUUID"))
1553                 usage(popt_context, EXIT_FAILURE, _("Option --uuid is allowed only for luksFormat and luksUUID."),
1554                       poptGetInvocationName(popt_context));
1555
1556         if (opt_align_payload && strcmp(aname, "luksFormat"))
1557                 usage(popt_context, EXIT_FAILURE, _("Option --align-payload is allowed only for luksFormat."),
1558                       poptGetInvocationName(popt_context));
1559
1560         if (opt_skip && (strcmp(aname, "open") ||
1561             (strcmp(opt_type, "plain") && strcmp(opt_type, "loopaes"))))
1562                 usage(popt_context, EXIT_FAILURE,
1563                 _("Option --skip is supported only for open of plain and loopaes devices.\n"),
1564                 poptGetInvocationName(popt_context));
1565
1566         if (opt_offset && (strcmp(aname, "open") ||
1567             (strcmp(opt_type, "plain") && strcmp(opt_type, "loopaes"))))
1568                 usage(popt_context, EXIT_FAILURE,
1569                 _("Option --offset is supported only for open of plain and loopaes devices.\n"),
1570                 poptGetInvocationName(popt_context));
1571
1572         if (opt_hidden && strcmp(aname, "tcryptDump") &&
1573             (strcmp(aname, "open") || strcmp(opt_type, "tcrypt")))
1574                 usage(popt_context, EXIT_FAILURE,
1575                 _("Option --hidden is supported only for TCRYPT device.\n"),
1576                 poptGetInvocationName(popt_context));
1577
1578         if (opt_debug) {
1579                 opt_verbose = 1;
1580                 crypt_set_debug_level(-1);
1581                 dbg_version_and_cmd(argc, argv);
1582         }
1583
1584         r = run_action(action);
1585         poptFreeContext(popt_context);
1586         return r;
1587 }