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