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