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