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