2 * cryptsetup - setup cryptographic volumes for dm-crypt
4 * Copyright (C) 2004, Christophe Saout <christophe@saout.de>
5 * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
6 * Copyright (C) 2009-2011, Red Hat, Inc. All rights reserved.
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.
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.
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.
35 #include <libcryptsetup.h>
38 #include "cryptsetup.h"
40 static int opt_verbose = 0;
41 static int opt_debug = 0;
42 static const char *opt_cipher = NULL;
43 static const char *opt_hash = NULL;
44 static int opt_verify_passphrase = 0;
45 static const char *opt_key_file = NULL;
46 static const char *opt_master_key_file = NULL;
47 static const char *opt_header_backup_file = NULL;
48 static const char *opt_uuid = NULL;
49 static const char *opt_header_device = NULL;
50 static int opt_key_size = 0;
51 static long opt_keyfile_size = 0;
52 static long opt_new_keyfile_size = 0;
53 static long opt_keyfile_offset = 0;
54 static long opt_new_keyfile_offset = 0;
55 static int opt_key_slot = CRYPT_ANY_SLOT;
56 static uint64_t opt_size = 0;
57 static uint64_t opt_offset = 0;
58 static uint64_t opt_skip = 0;
59 static int opt_skip_valid = 0;
60 static int opt_readonly = 0;
61 static int opt_iteration_time = 1000;
62 static int opt_batch_mode = 0;
63 static int opt_version_mode = 0;
64 static int opt_timeout = 0;
65 static int opt_tries = 3;
66 static int opt_align_payload = 0;
67 static int opt_random = 0;
68 static int opt_urandom = 0;
69 static int opt_dump_master_key = 0;
70 static int opt_shared = 0;
71 static int opt_allow_discards = 0;
73 static const char **action_argv;
74 static int action_argc;
76 static int action_create(int arg);
77 static int action_remove(int arg);
78 static int action_resize(int arg);
79 static int action_status(int arg);
80 static int action_luksFormat(int arg);
81 static int action_luksOpen(int arg);
82 static int action_luksAddKey(int arg);
83 static int action_luksKillSlot(int arg);
84 static int action_luksRemoveKey(int arg);
85 static int action_luksChangeKey(int arg);
86 static int action_isLuks(int arg);
87 static int action_luksUUID(int arg);
88 static int action_luksDump(int arg);
89 static int action_luksSuspend(int arg);
90 static int action_luksResume(int arg);
91 static int action_luksBackup(int arg);
92 static int action_luksRestore(int arg);
93 static int action_loopaesOpen(int arg);
94 static int action_luksRepair(int arg);
96 static struct action_type {
100 int required_action_argc;
101 int required_memlock;
102 const char *arg_desc;
105 { "create", action_create, 0, 2, 1, N_("<name> <device>"),N_("create device") },
106 { "remove", action_remove, 0, 1, 1, N_("<name>"), N_("remove device") },
107 { "resize", action_resize, 0, 1, 1, N_("<name>"), N_("resize active device") },
108 { "status", action_status, 0, 1, 0, N_("<name>"), N_("show device status") },
109 { "repair", action_luksRepair, 0, 1, 1, N_("<device>"), N_("try to repair on-disk metadata") },
110 { "luksFormat", action_luksFormat, 0, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
111 { "luksOpen", action_luksOpen, 0, 2, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
112 { "luksAddKey", action_luksAddKey, 0, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
113 { "luksRemoveKey",action_luksRemoveKey, 0, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
114 { "luksChangeKey",action_luksChangeKey, 0, 1, 1, N_("<device> [<key file>]"), N_("changes supplied key or key file of LUKS device") },
115 { "luksKillSlot", action_luksKillSlot, 0, 2, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
116 { "luksUUID", action_luksUUID, 0, 1, 0, N_("<device>"), N_("print UUID of LUKS device") },
117 { "isLuks", action_isLuks, 0, 1, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
118 { "luksClose", action_remove, 0, 1, 1, N_("<name>"), N_("remove LUKS mapping") },
119 { "luksDump", action_luksDump, 0, 1, 1, N_("<device>"), N_("dump LUKS partition information") },
120 { "luksSuspend",action_luksSuspend, 0, 1, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen).") },
121 { "luksResume", action_luksResume, 0, 1, 1, N_("<device>"), N_("Resume suspended LUKS device.") },
122 { "luksHeaderBackup",action_luksBackup, 0, 1, 1, N_("<device>"), N_("Backup LUKS device header and keyslots") },
123 { "luksHeaderRestore",action_luksRestore,0,1, 1, N_("<device>"), N_("Restore LUKS device header and keyslots") },
124 { "loopaesOpen",action_loopaesOpen, 0, 2, 1, N_("<device> <name> "), N_("open loop-AES device as mapping <name>") },
125 { "loopaesClose",action_remove, 0, 1, 1, N_("<name>"), N_("remove loop-AES mapping") },
126 { NULL, NULL, 0, 0, 0, NULL, NULL }
129 __attribute__((format(printf, 5, 6)))
130 static void clogger(struct crypt_device *cd, int level, const char *file,
131 int line, const char *format, ...)
136 va_start(argp, format);
138 if (vasprintf(&target, format, argp) > 0) {
140 crypt_log(cd, level, target);
142 } else if (opt_debug)
143 printf("# %s:%d %s\n", file ?: "?", line, target);
145 } else if (opt_debug)
146 printf("# %s\n", target);
154 static int _yesDialog(const char *msg, void *usrptr __attribute__((unused)))
160 if(isatty(STDIN_FILENO) && !opt_batch_mode) {
161 log_std("\nWARNING!\n========\n");
162 log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
163 if(getline(&answer, &size, stdin) == -1) {
168 if(strcmp(answer, "YES\n"))
176 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
180 case CRYPT_LOG_NORMAL:
183 case CRYPT_LOG_VERBOSE:
187 case CRYPT_LOG_ERROR:
190 case CRYPT_LOG_DEBUG:
192 printf("# %s\n", msg);
195 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
200 static void _quiet_log(int level, const char *msg, void *usrptr)
202 if (!opt_verbose && (level == CRYPT_LOG_ERROR || level == CRYPT_LOG_NORMAL))
203 level = CRYPT_LOG_VERBOSE;
204 _log(level, msg, usrptr);
207 static int _verify_passphrase(int def)
209 /* Batch mode switch off verify - if not overrided by -y */
210 if (opt_verify_passphrase)
212 else if (opt_batch_mode)
215 /* Non-tty input doesn't allow verify */
216 if (def && !isatty(STDIN_FILENO)) {
217 if (opt_verify_passphrase)
218 log_err(_("Can't do passphrase verification on non-tty inputs.\n"));
225 static void show_status(int errcode)
227 char error[256], *error_;
233 log_std(_("Command successful.\n"));
237 crypt_get_error(error, sizeof(error));
240 error_ = strerror_r(-errcode, error, sizeof(error));
241 if (error_ != error) {
242 strncpy(error, error_, sizeof(error));
243 error[sizeof(error) - 1] = '\0';
247 log_err(_("Command failed with code %i"), -errcode);
249 log_err(": %s\n", error);
254 static const char *uuid_or_device(const char *spec)
256 static char device[PATH_MAX];
258 int i = 0, uuid_len = 5;
260 /* Check if it is correct UUID=<LUKS_UUID> format */
261 if (spec && !strncmp(spec, "UUID=", uuid_len)) {
262 strcpy(device, "/dev/disk/by-uuid/");
263 ptr = &device[strlen(device)];
265 while ((s = spec[i++]) && i < PATH_MAX) {
266 if (!isxdigit(s) && s != '-')
267 return spec; /* Bail it out */
279 static int action_create(int arg __attribute__((unused)))
281 struct crypt_device *cd = NULL;
282 char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
283 struct crypt_params_plain params = {
284 .hash = opt_hash ?: DEFAULT_PLAIN_HASH,
286 .offset = opt_offset,
289 char *password = NULL;
291 size_t key_size = (opt_key_size ?: DEFAULT_PLAIN_KEYBITS) / 8;
292 uint32_t activate_flags = 0;
295 if (params.hash && !strcmp(params.hash, "plain"))
298 /* FIXME: temporary hack */
299 if (opt_key_file && strcmp(opt_key_file, "-"))
302 if ((opt_keyfile_offset || opt_keyfile_size) && opt_key_file)
303 log_std(("Ignoring keyfile offset and size options, keyfile read "
304 "size is always the same as encryption key size.\n"));
306 r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(PLAIN),
307 cipher, NULL, cipher_mode);
309 log_err("No known cipher specification pattern detected.\n");
313 if ((r = crypt_init(&cd, action_argv[1])))
316 crypt_set_timeout(cd, opt_timeout);
317 crypt_set_password_retry(cd, opt_tries);
319 r = crypt_format(cd, CRYPT_PLAIN,
328 activate_flags |= CRYPT_ACTIVATE_READONLY;
331 activate_flags |= CRYPT_ACTIVATE_SHARED;
333 if (opt_allow_discards)
334 activate_flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
337 /* With hashing, read the whole keyfile */
338 r = crypt_activate_by_keyfile_offset(cd, action_argv[0],
339 CRYPT_ANY_SLOT, opt_key_file,
340 params.hash ? 0 : key_size, 0,
343 r = crypt_get_key(_("Enter passphrase: "),
344 &password, &passwordLen,
345 opt_keyfile_offset, opt_keyfile_size,
347 _verify_passphrase(0),
352 r = crypt_activate_by_passphrase(cd, action_argv[0],
353 CRYPT_ANY_SLOT, password, passwordLen, activate_flags);
357 crypt_safe_free(password);
362 static int action_loopaesOpen(int arg __attribute__((unused)))
364 struct crypt_device *cd = NULL;
365 struct crypt_params_loopaes params = {
366 .hash = opt_hash ?: NULL,
367 .offset = opt_offset,
368 .skip = opt_skip_valid ? opt_skip : opt_offset,
370 unsigned int key_size = (opt_key_size ?: DEFAULT_LOOPAES_KEYBITS) / 8;
371 uint32_t activate_flags = 0;
375 log_err(_("Option --key-file is required.\n"));
380 activate_flags |= CRYPT_ACTIVATE_READONLY;
382 if (opt_allow_discards)
383 activate_flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
385 if ((r = crypt_init(&cd, action_argv[0])))
388 r = crypt_format(cd, CRYPT_LOOPAES, opt_cipher ?: DEFAULT_LOOPAES_CIPHER,
389 NULL, NULL, NULL, key_size, ¶ms);
393 r = crypt_activate_by_keyfile_offset(cd, action_argv[1], CRYPT_ANY_SLOT,
394 opt_key_file, opt_keyfile_size,
395 opt_keyfile_size, activate_flags);
402 static int action_remove(int arg __attribute__((unused)))
404 struct crypt_device *cd = NULL;
407 r = crypt_init_by_name(&cd, action_argv[0]);
409 r = crypt_deactivate(cd, action_argv[0]);
415 static int action_resize(int arg __attribute__((unused)))
417 struct crypt_device *cd = NULL;
420 r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device);
422 r = crypt_resize(cd, action_argv[0], opt_size);
428 static int action_status(int arg __attribute__((unused)))
430 crypt_status_info ci;
431 struct crypt_active_device cad;
432 struct crypt_device *cd = NULL;
438 /* perhaps a path, not a dm device name */
439 if (strchr(action_argv[0], '/') && !stat(action_argv[0], &st))
442 ci = crypt_status(NULL, action_argv[0]);
449 log_std("%s is inactive.\n", action_argv[0]);
451 log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]);
457 log_std("%s is active%s.\n", action_argv[0],
458 ci == CRYPT_BUSY ? " and is in use" : "");
460 log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0],
461 ci == CRYPT_BUSY ? " and is in use" : "");
463 r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device);
464 if (r < 0 || !crypt_get_type(cd))
467 log_std(" type: %s\n", crypt_get_type(cd));
469 r = crypt_get_active_device(cd, action_argv[0], &cad);
473 log_std(" cipher: %s-%s\n", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
474 log_std(" keysize: %d bits\n", crypt_get_volume_key_size(cd) * 8);
475 device = crypt_get_device_name(cd);
476 log_std(" device: %s\n", device);
477 if (crypt_loop_device(device)) {
478 backing_file = crypt_loop_backing_file(device);
479 log_std(" loop: %s\n", backing_file);
482 log_std(" offset: %" PRIu64 " sectors\n", cad.offset);
483 log_std(" size: %" PRIu64 " sectors\n", cad.size);
485 log_std(" skipped: %" PRIu64 " sectors\n", cad.iv_offset);
486 log_std(" mode: %s\n", cad.flags & CRYPT_ACTIVATE_READONLY ?
487 "readonly" : "read/write");
488 if (cad.flags & CRYPT_ACTIVATE_ALLOW_DISCARDS)
489 log_std(" flags: discards\n");
496 static int _read_mk(const char *file, char **key, int keysize)
500 *key = crypt_safe_alloc(keysize);
504 fd = open(file, O_RDONLY);
506 log_err("Cannot read keyfile %s.\n", file);
509 if ((read(fd, *key, keysize) != keysize)) {
510 log_err("Cannot read %d bytes from keyfile %s.\n", keysize, file);
517 crypt_safe_free(*key);
522 static int action_luksRepair(int arg __attribute__((unused)))
524 struct crypt_device *cd = NULL;
527 if ((r = crypt_init(&cd, action_argv[0])))
530 /* Currently only LUKS1 allows repair */
531 crypt_set_log_callback(cd, _quiet_log, NULL);
532 r = crypt_load(cd, CRYPT_LUKS1, NULL);
533 crypt_set_log_callback(cd, _log, NULL);
535 log_verbose( _("No known problems detected for LUKS header.\n"));
539 r = _yesDialog(_("Really try to repair LUKS device header?"),
542 r = crypt_repair(cd, CRYPT_LUKS1, NULL);
548 static int action_luksFormat(int arg __attribute__((unused)))
550 int r = -EINVAL, keysize;
551 const char *header_device;
552 char *msg = NULL, *key = NULL, cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
553 char *password = NULL;
555 struct crypt_device *cd = NULL;
556 struct crypt_params_luks1 params = {
557 .hash = opt_hash ?: DEFAULT_LUKS1_HASH,
558 .data_alignment = opt_align_payload,
559 .data_device = opt_header_device ? action_argv[0] : NULL,
562 header_device = opt_header_device ?: action_argv[0];
564 if(asprintf(&msg, _("This will overwrite data on %s irrevocably."),
565 header_device) == -1) {
566 log_err(_("memory allocation error in action_luksFormat"));
570 r = _yesDialog(msg, NULL) ? 0 : -EINVAL;
575 r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(LUKS1),
576 cipher, NULL, cipher_mode);
578 log_err(_("No known cipher specification pattern detected.\n"));
582 if ((r = crypt_init(&cd, header_device))) {
583 if (opt_header_device)
584 log_err(_("Cannot use %s as on-disk header.\n"), header_device);
588 keysize = (opt_key_size ?: DEFAULT_LUKS1_KEYBITS) / 8;
590 crypt_set_timeout(cd, opt_timeout);
591 if (opt_iteration_time)
592 crypt_set_iteration_time(cd, opt_iteration_time);
595 crypt_set_rng_type(cd, CRYPT_RNG_RANDOM);
596 else if (opt_urandom)
597 crypt_set_rng_type(cd, CRYPT_RNG_URANDOM);
599 r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
600 opt_keyfile_offset, opt_keyfile_size, opt_key_file,
601 opt_timeout, _verify_passphrase(1), cd);
605 if (opt_master_key_file) {
606 r = _read_mk(opt_master_key_file, &key, keysize);
611 r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode,
612 opt_uuid, key, keysize, ¶ms);
616 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
618 password, passwordLen);
621 crypt_safe_free(key);
622 crypt_safe_free(password);
627 static int action_luksOpen(int arg __attribute__((unused)))
629 struct crypt_device *cd = NULL;
630 const char *data_device, *header_device;
635 if (opt_header_device) {
636 header_device = uuid_or_device(opt_header_device);
637 data_device = action_argv[0];
639 header_device = uuid_or_device(action_argv[0]);
643 if ((r = crypt_init(&cd, header_device)))
646 if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
650 (r = crypt_set_data_device(cd, data_device)))
653 if (!data_device && (crypt_get_data_offset(cd) < 8)) {
654 log_err(_("Reduced data offset is allowed only for detached LUKS header.\n"));
659 crypt_set_timeout(cd, opt_timeout);
660 crypt_set_password_retry(cd, opt_tries);
661 crypt_set_password_verify(cd, _verify_passphrase(0));
663 if (opt_iteration_time)
664 crypt_set_iteration_time(cd, opt_iteration_time);
667 flags |= CRYPT_ACTIVATE_READONLY;
669 if (opt_allow_discards)
670 flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
672 if (opt_master_key_file) {
673 keysize = crypt_get_volume_key_size(cd);
674 r = _read_mk(opt_master_key_file, &key, keysize);
677 r = crypt_activate_by_volume_key(cd, action_argv[1],
678 key, keysize, flags);
679 } else if (opt_key_file) {
680 crypt_set_password_retry(cd, 1);
681 r = crypt_activate_by_keyfile_offset(cd, action_argv[1],
682 opt_key_slot, opt_key_file, opt_keyfile_size,
683 opt_keyfile_offset, flags);
685 r = crypt_activate_by_passphrase(cd, action_argv[1],
686 opt_key_slot, NULL, 0, flags);
688 crypt_safe_free(key);
693 static int verify_keyslot(struct crypt_device *cd, int key_slot,
694 char *msg_last, char *msg_pass,
695 const char *key_file, int keyfile_offset,
698 crypt_keyslot_info ki;
699 char *password = NULL;
703 ki = crypt_keyslot_status(cd, key_slot);
704 if (ki == CRYPT_SLOT_ACTIVE_LAST && msg_last && !_yesDialog(msg_last, NULL))
707 r = crypt_get_key(msg_pass, &password, &passwordLen,
708 keyfile_offset, keyfile_size, key_file, opt_timeout,
709 _verify_passphrase(0), cd);
713 if (ki == CRYPT_SLOT_ACTIVE_LAST) {
714 /* check the last keyslot */
715 r = crypt_activate_by_passphrase(cd, NULL, key_slot,
716 password, passwordLen, 0);
718 /* try all other keyslots */
719 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) {
722 ki = crypt_keyslot_status(cd, key_slot);
723 if (ki == CRYPT_SLOT_ACTIVE)
724 r = crypt_activate_by_passphrase(cd, NULL, i,
725 password, passwordLen, 0);
732 log_err(_("No key available with this passphrase.\n"));
734 crypt_safe_free(password);
738 static int action_luksKillSlot(int arg __attribute__((unused)))
740 struct crypt_device *cd = NULL;
743 if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
746 crypt_set_confirm_callback(cd, _yesDialog, NULL);
747 crypt_set_timeout(cd, opt_timeout);
749 if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
752 switch (crypt_keyslot_status(cd, opt_key_slot)) {
753 case CRYPT_SLOT_ACTIVE_LAST:
754 case CRYPT_SLOT_ACTIVE:
755 log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
757 case CRYPT_SLOT_INACTIVE:
758 log_err(_("Key %d not active. Can't wipe.\n"), opt_key_slot);
759 case CRYPT_SLOT_INVALID:
764 if (!opt_batch_mode) {
765 r = verify_keyslot(cd, opt_key_slot,
766 _("This is the last keyslot. Device will become unusable after purging this key."),
767 _("Enter any remaining LUKS passphrase: "),
768 opt_key_file, opt_keyfile_offset, opt_keyfile_size);
773 r = crypt_keyslot_destroy(cd, opt_key_slot);
779 static int action_luksRemoveKey(int arg __attribute__((unused)))
781 struct crypt_device *cd = NULL;
782 char *password = NULL;
786 if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
789 crypt_set_confirm_callback(cd, _yesDialog, NULL);
790 crypt_set_timeout(cd, opt_timeout);
792 if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
795 r = crypt_get_key(_("Enter LUKS passphrase to be deleted: "),
796 &password, &passwordLen,
797 opt_keyfile_offset, opt_keyfile_size, opt_key_file,
799 _verify_passphrase(0),
804 r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT,
805 password, passwordLen, 0);
810 log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
812 if (crypt_keyslot_status(cd, opt_key_slot) == CRYPT_SLOT_ACTIVE_LAST &&
813 !_yesDialog(_("This is the last keyslot. "
814 "Device will become unusable after purging this key."),
820 r = crypt_keyslot_destroy(cd, opt_key_slot);
822 crypt_safe_free(password);
827 static int action_luksAddKey(int arg __attribute__((unused)))
829 int r = -EINVAL, keysize = 0;
831 const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
832 struct crypt_device *cd = NULL;
834 if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
837 crypt_set_confirm_callback(cd, _yesDialog, NULL);
839 if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
842 keysize = crypt_get_volume_key_size(cd);
843 /* FIXME: lib cannot properly set verification for new/old passphrase */
844 crypt_set_password_verify(cd, _verify_passphrase(0));
845 crypt_set_timeout(cd, opt_timeout);
846 if (opt_iteration_time)
847 crypt_set_iteration_time(cd, opt_iteration_time);
849 if (opt_master_key_file) {
850 r = _read_mk(opt_master_key_file, &key, keysize);
853 //FIXME: process keyfile arg
854 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
855 key, keysize, NULL, 0);
856 } else if (opt_key_file || opt_new_key_file) {
857 r = crypt_keyslot_add_by_keyfile_offset(cd, opt_key_slot,
858 opt_key_file, opt_keyfile_size, opt_keyfile_offset,
859 opt_new_key_file, opt_new_keyfile_size, opt_new_keyfile_offset);
861 r = crypt_keyslot_add_by_passphrase(cd, opt_key_slot,
866 crypt_safe_free(key);
870 static int _slots_full(struct crypt_device *cd)
874 for (i = 0; i < crypt_keyslot_max(crypt_get_type(cd)); i++)
875 if (crypt_keyslot_status(cd, i) == CRYPT_SLOT_INACTIVE)
880 static int action_luksChangeKey(int arg __attribute__((unused)))
882 const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
883 struct crypt_device *cd = NULL;
884 char *vk = NULL, *password = NULL;
885 size_t passwordLen = 0;
887 int new_key_slot, old_key_slot, r;
889 if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
892 if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
895 if (opt_iteration_time)
896 crypt_set_iteration_time(cd, opt_iteration_time);
898 r = crypt_get_key(_("Enter LUKS passphrase to be changed: "),
899 &password, &passwordLen,
900 opt_keyfile_offset, opt_keyfile_size, opt_key_file,
901 opt_timeout, _verify_passphrase(0), cd);
905 vk_size = crypt_get_volume_key_size(cd);
906 vk = crypt_safe_alloc(vk_size);
912 r = crypt_volume_key_get(cd, opt_key_slot, vk, &vk_size,
913 password, passwordLen);
915 if (opt_key_slot != CRYPT_ANY_SLOT)
916 log_err(_("No key available with this passphrase.\n"));
920 if (opt_key_slot != CRYPT_ANY_SLOT || _slots_full(cd)) {
921 log_dbg("Key slot %d is going to be overwritten (%s).",
922 r, opt_key_slot != CRYPT_ANY_SLOT ?
923 "explicit key slot specified" : "no free key slot");
927 log_dbg("Allocating new key slot.");
929 new_key_slot = CRYPT_ANY_SLOT;
932 crypt_safe_free(password);
935 r = crypt_get_key(_("Enter new LUKS passphrase: "),
936 &password, &passwordLen,
937 opt_new_keyfile_offset, opt_new_keyfile_size,
939 opt_timeout, _verify_passphrase(0), cd);
943 if (new_key_slot == old_key_slot) {
944 (void)crypt_keyslot_destroy(cd, old_key_slot);
945 r = crypt_keyslot_add_by_volume_key(cd, new_key_slot,
947 password, passwordLen);
949 log_verbose(_("Key slot %d changed.\n"), r);
951 r = crypt_keyslot_add_by_volume_key(cd, CRYPT_ANY_SLOT,
953 password, passwordLen);
955 log_verbose(_("Replaced with key slot %d.\n"), r);
956 r = crypt_keyslot_destroy(cd, old_key_slot);
960 log_err(_("Failed to swap new key slot.\n"));
963 crypt_safe_free(password);
968 static int action_isLuks(int arg __attribute__((unused)))
970 struct crypt_device *cd = NULL;
973 if ((r = crypt_init(&cd, action_argv[0])))
976 crypt_set_log_callback(cd, _quiet_log, NULL);
977 r = crypt_load(cd, CRYPT_LUKS1, NULL);
983 static int action_luksUUID(int arg __attribute__((unused)))
985 struct crypt_device *cd = NULL;
986 const char *existing_uuid = NULL;
989 if ((r = crypt_init(&cd, action_argv[0])))
992 crypt_set_confirm_callback(cd, _yesDialog, NULL);
994 if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
998 r = crypt_set_uuid(cd, opt_uuid);
1000 existing_uuid = crypt_get_uuid(cd);
1001 log_std("%s\n", existing_uuid ?: "");
1002 r = existing_uuid ? 0 : 1;
1009 static int luksDump_with_volume_key(struct crypt_device *cd)
1011 char *vk = NULL, *password = NULL;
1012 size_t passwordLen = 0;
1017 crypt_set_confirm_callback(cd, _yesDialog, NULL);
1019 _("LUKS header dump with volume key is sensitive information\n"
1020 "which allows access to encrypted partition without passphrase.\n"
1021 "This dump should be always stored encrypted on safe place."),
1025 vk_size = crypt_get_volume_key_size(cd);
1026 vk = crypt_safe_alloc(vk_size);
1030 r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
1031 opt_keyfile_offset, opt_keyfile_size, opt_key_file,
1032 opt_timeout, 0, cd);
1036 r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size,
1037 password, passwordLen);
1041 log_std("LUKS header information for %s\n", crypt_get_device_name(cd));
1042 log_std("Cipher name: \t%s\n", crypt_get_cipher(cd));
1043 log_std("Cipher mode: \t%s\n", crypt_get_cipher_mode(cd));
1044 log_std("Payload offset:\t%d\n", (int)crypt_get_data_offset(cd));
1045 log_std("UUID: \t%s\n", crypt_get_uuid(cd));
1046 log_std("MK bits: \t%d\n", (int)vk_size * 8);
1047 log_std("MK dump:\t");
1049 for(i = 0; i < vk_size; i++) {
1052 log_std("%02hhx ", (char)vk[i]);
1057 crypt_safe_free(password);
1058 crypt_safe_free(vk);
1062 static int action_luksDump(int arg __attribute__((unused)))
1064 struct crypt_device *cd = NULL;
1067 if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
1070 if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
1073 if (opt_dump_master_key)
1074 r = luksDump_with_volume_key(cd);
1082 static int action_luksSuspend(int arg __attribute__((unused)))
1084 struct crypt_device *cd = NULL;
1087 r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device);
1089 r = crypt_suspend(cd, action_argv[0]);
1095 static int action_luksResume(int arg __attribute__((unused)))
1097 struct crypt_device *cd = NULL;
1100 if ((r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device)))
1103 crypt_set_timeout(cd, opt_timeout);
1104 crypt_set_password_retry(cd, opt_tries);
1105 crypt_set_password_verify(cd, _verify_passphrase(0));
1108 r = crypt_resume_by_keyfile_offset(cd, action_argv[0], CRYPT_ANY_SLOT,
1109 opt_key_file, opt_keyfile_size, opt_keyfile_offset);
1111 r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
1118 static int action_luksBackup(int arg __attribute__((unused)))
1120 struct crypt_device *cd = NULL;
1123 if (!opt_header_backup_file) {
1124 log_err(_("Option --header-backup-file is required.\n"));
1128 if ((r = crypt_init(&cd, uuid_or_device(action_argv[0]))))
1131 crypt_set_confirm_callback(cd, _yesDialog, NULL);
1133 r = crypt_header_backup(cd, CRYPT_LUKS1, opt_header_backup_file);
1139 static int action_luksRestore(int arg __attribute__((unused)))
1141 struct crypt_device *cd = NULL;
1144 if (!opt_header_backup_file) {
1145 log_err(_("Option --header-backup-file is required.\n"));
1149 if ((r = crypt_init(&cd, action_argv[0])))
1152 crypt_set_confirm_callback(cd, _yesDialog, NULL);
1153 r = crypt_header_restore(cd, CRYPT_LUKS1, opt_header_backup_file);
1159 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
1160 int exitcode, const char *error,
1163 poptPrintUsage(popt_context, stderr, 0);
1165 log_err("%s: %s\n", more, error);
1166 poptFreeContext(popt_context);
1170 static void help(poptContext popt_context,
1171 enum poptCallbackReason reason __attribute__((unused)),
1172 struct poptOption *key,
1173 const char *arg __attribute__((unused)),
1174 void *data __attribute__((unused)))
1176 if (key->shortName == '?') {
1177 struct action_type *action;
1179 log_std("%s\n",PACKAGE_STRING);
1181 poptPrintHelp(popt_context, stdout, 0);
1184 "<action> is one of:\n"));
1186 for(action = action_types; action->type; action++)
1187 log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
1190 "<name> is the device to create under %s\n"
1191 "<device> is the encrypted device\n"
1192 "<key slot> is the LUKS key slot number to modify\n"
1193 "<key file> optional key file for the new key for luksAddKey action\n"),
1196 log_std(_("\nDefault compiled-in keyfile parameters:\n"
1197 "\tMaximum keyfile size: %dkB, "
1198 "Maximum interactive passphrase length %d (characters)\n"),
1199 DEFAULT_KEYFILE_SIZE_MAXKB, DEFAULT_PASSPHRASE_SIZE_MAX);
1201 log_std(_("\nDefault compiled-in device cipher parameters:\n"
1202 "\tloop-AES: %s, Key %d bits\n"
1203 "\tplain: %s, Key: %d bits, Password hashing: %s\n"
1204 "\tLUKS1: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
1205 DEFAULT_LOOPAES_CIPHER, DEFAULT_LOOPAES_KEYBITS,
1206 DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
1207 DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
1211 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1214 static void _dbg_version_and_cmd(int argc, const char **argv)
1218 log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
1219 for (i = 0; i < argc; i++) {
1222 log_std("%s", argv[i]);
1227 static int run_action(struct action_type *action)
1231 log_dbg("Running command %s.", action->type);
1233 if (action->required_memlock)
1234 crypt_memory_lock(NULL, 1);
1236 r = action->handler(action->arg);
1238 if (action->required_memlock)
1239 crypt_memory_lock(NULL, 0);
1241 /* Some functions returns keyslot # */
1247 /* Translate exit code to simple codes */
1249 case 0: r = EXIT_SUCCESS; break;
1251 case -EBUSY: r = 5; break;
1253 case -ENODEV: r = 4; break;
1254 case -ENOMEM: r = 3; break;
1255 case -EPERM: r = 2; break;
1259 default: r = EXIT_FAILURE;
1264 int main(int argc, const char **argv)
1266 static char *popt_tmp;
1267 static struct poptOption popt_help_options[] = {
1268 { NULL, '\0', POPT_ARG_CALLBACK, help, 0, NULL, NULL },
1269 { "help", '?', POPT_ARG_NONE, NULL, 0, N_("Show this help message"), NULL },
1270 { "usage", '\0', POPT_ARG_NONE, NULL, 0, N_("Display brief usage"), NULL },
1273 static struct poptOption popt_options[] = {
1274 { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1275 { "version", '\0', POPT_ARG_NONE, &opt_version_mode, 0, N_("Print package version"), NULL },
1276 { "verbose", 'v', POPT_ARG_NONE, &opt_verbose, 0, N_("Shows more detailed error messages"), NULL },
1277 { "debug", '\0', POPT_ARG_NONE, &opt_debug, 0, N_("Show debug messages"), NULL },
1278 { "cipher", 'c', POPT_ARG_STRING, &opt_cipher, 0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1279 { "hash", 'h', POPT_ARG_STRING, &opt_hash, 0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1280 { "verify-passphrase", 'y', POPT_ARG_NONE, &opt_verify_passphrase, 0, N_("Verifies the passphrase by asking for it twice"), NULL },
1281 { "key-file", 'd', POPT_ARG_STRING, &opt_key_file, 0, N_("Read the key from a file."), NULL },
1282 { "master-key-file", '\0', POPT_ARG_STRING, &opt_master_key_file, 0, N_("Read the volume (master) key from file."), NULL },
1283 { "dump-master-key", '\0', POPT_ARG_NONE, &opt_dump_master_key, 0, N_("Dump volume (master) key instead of keyslots info."), NULL },
1284 { "key-size", 's', POPT_ARG_INT, &opt_key_size, 0, N_("The size of the encryption key"), N_("BITS") },
1285 { "keyfile-size", 'l', POPT_ARG_LONG, &opt_keyfile_size, 0, N_("Limits the read from keyfile"), N_("bytes") },
1286 { "keyfile-offset", '\0', POPT_ARG_LONG, &opt_keyfile_offset, 0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1287 { "new-keyfile-size", '\0', POPT_ARG_LONG, &opt_new_keyfile_size, 0, N_("Limits the read from newly added keyfile"), N_("bytes") },
1288 { "new-keyfile-offset",'\0', POPT_ARG_LONG, &opt_new_keyfile_offset, 0, N_("Number of bytes to skip in newly added keyfile"), N_("bytes") },
1289 { "key-slot", 'S', POPT_ARG_INT, &opt_key_slot, 0, N_("Slot number for new key (default is first free)"), NULL },
1290 { "size", 'b', POPT_ARG_STRING, &popt_tmp, 1, N_("The size of the device"), N_("SECTORS") },
1291 { "offset", 'o', POPT_ARG_STRING, &popt_tmp, 2, N_("The start offset in the backend device"), N_("SECTORS") },
1292 { "skip", 'p', POPT_ARG_STRING, &popt_tmp, 3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
1293 { "readonly", 'r', POPT_ARG_NONE, &opt_readonly, 0, N_("Create a readonly mapping"), NULL },
1294 { "iter-time", 'i', POPT_ARG_INT, &opt_iteration_time, 0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1295 { "batch-mode", 'q', POPT_ARG_NONE, &opt_batch_mode, 0, N_("Do not ask for confirmation"), NULL },
1296 { "timeout", 't', POPT_ARG_INT, &opt_timeout, 0, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs") },
1297 { "tries", 'T', POPT_ARG_INT, &opt_tries, 0, N_("How often the input of the passphrase can be retried"), NULL },
1298 { "align-payload", '\0', POPT_ARG_INT, &opt_align_payload, 0, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS") },
1299 { "header-backup-file",'\0', POPT_ARG_STRING, &opt_header_backup_file, 0, N_("File with LUKS header and keyslots backup."), NULL },
1300 { "use-random", '\0', POPT_ARG_NONE, &opt_random, 0, N_("Use /dev/random for generating volume key."), NULL },
1301 { "use-urandom", '\0', POPT_ARG_NONE, &opt_urandom, 0, N_("Use /dev/urandom for generating volume key."), NULL },
1302 { "shared", '\0', POPT_ARG_NONE, &opt_shared, 0, N_("Share device with another non-overlapping crypt segment."), NULL },
1303 { "uuid", '\0', POPT_ARG_STRING, &opt_uuid, 0, N_("UUID for device to use."), NULL },
1304 { "allow-discards", '\0', POPT_ARG_NONE, &opt_allow_discards, 0, N_("Allow discards (aka TRIM) requests for device."), NULL },
1305 { "header", '\0', POPT_ARG_STRING, &opt_header_device, 0, N_("Device or file with separated LUKS header."), NULL },
1308 poptContext popt_context;
1309 struct action_type *action;
1312 const char *null_action_argv[] = {NULL};
1314 crypt_set_log_callback(NULL, _log, NULL);
1316 setlocale(LC_ALL, "");
1317 bindtextdomain(PACKAGE, LOCALEDIR);
1318 textdomain(PACKAGE);
1320 popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1321 poptSetOtherOptionHelp(popt_context,
1322 N_("[OPTION...] <action> <action-specific>]"));
1324 while((r = poptGetNextOpt(popt_context)) > 0) {
1325 unsigned long long ull_value;
1329 ull_value = strtoull(popt_tmp, &endp, 0);
1330 if (*endp || !*popt_tmp ||
1331 (errno == ERANGE && ull_value == ULLONG_MAX) ||
1332 (errno != 0 && ull_value == 0))
1333 r = POPT_ERROR_BADNUMBER;
1337 opt_size = ull_value;
1340 opt_offset = ull_value;
1343 opt_skip = ull_value;
1353 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1354 poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1355 if (opt_version_mode) {
1356 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1357 poptFreeContext(popt_context);
1361 if (!(aname = poptGetArg(popt_context)))
1362 usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."),
1363 poptGetInvocationName(popt_context));
1364 for(action = action_types; action->type; action++)
1365 if (strcmp(action->type, aname) == 0)
1368 usage(popt_context, EXIT_FAILURE, _("Unknown action."),
1369 poptGetInvocationName(popt_context));
1372 action_argv = poptGetArgs(popt_context);
1373 /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
1375 action_argv = null_action_argv;
1377 /* Count args, somewhat unnice, change? */
1378 while(action_argv[action_argc] != NULL)
1381 if(action_argc < action->required_action_argc) {
1383 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
1384 usage(popt_context, EXIT_FAILURE, buf,
1385 poptGetInvocationName(popt_context));
1388 /* FIXME: rewrite this from scratch */
1390 if (opt_shared && strcmp(aname, "create")) {
1391 usage(popt_context, EXIT_FAILURE,
1392 _("Option --shared is allowed only for create operation.\n"),
1393 poptGetInvocationName(popt_context));
1396 if (opt_allow_discards &&
1397 strcmp(aname, "luksOpen") &&
1398 strcmp(aname, "create") &&
1399 strcmp(aname, "loopaesOpen")) {
1400 usage(popt_context, EXIT_FAILURE,
1401 _("Option --allow-discards is allowed only for luksOpen, loopaesOpen and create operation.\n"),
1402 poptGetInvocationName(popt_context));
1406 strcmp(aname, "luksFormat") &&
1407 strcmp(aname, "create") &&
1408 strcmp(aname, "loopaesOpen")) {
1409 usage(popt_context, EXIT_FAILURE,
1410 _("Option --key-size is allowed only for luksFormat, create and loopaesOpen.\n"
1411 "To limit read from keyfile use --keyfile-size=(bytes)."),
1412 poptGetInvocationName(popt_context));
1415 if (opt_key_size % 8)
1416 usage(popt_context, EXIT_FAILURE,
1417 _("Key size must be a multiple of 8 bits"),
1418 poptGetInvocationName(popt_context));
1420 if (!strcmp(aname, "luksKillSlot") && action_argc > 1)
1421 opt_key_slot = atoi(action_argv[1]);
1422 if (opt_key_slot != CRYPT_ANY_SLOT &&
1423 (opt_key_slot < 0 || opt_key_slot >= crypt_keyslot_max(CRYPT_LUKS1)))
1424 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1425 poptGetInvocationName(popt_context));
1427 if ((!strcmp(aname, "luksRemoveKey") ||
1428 !strcmp(aname, "luksFormat")) &&
1431 log_err(_("Option --key-file takes precedence over specified key file argument.\n"));
1433 opt_key_file = action_argv[1];
1436 if (opt_keyfile_size < 0 || opt_new_keyfile_size < 0 || opt_key_size < 0 ||
1437 opt_keyfile_offset < 0 || opt_new_keyfile_offset < 0) {
1438 usage(popt_context, EXIT_FAILURE,
1439 _("Negative number for option not permitted."),
1440 poptGetInvocationName(popt_context));
1443 if (opt_random && opt_urandom)
1444 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1445 poptGetInvocationName(popt_context));
1447 if ((opt_random || opt_urandom) && strcmp(aname, "luksFormat"))
1448 usage(popt_context, EXIT_FAILURE, _("Option --use-[u]random is allowed only for luksFormat."),
1449 poptGetInvocationName(popt_context));
1451 if (opt_uuid && strcmp(aname, "luksFormat") && strcmp(aname, "luksUUID"))
1452 usage(popt_context, EXIT_FAILURE, _("Option --uuid is allowed only for luksFormat and luksUUID."),
1453 poptGetInvocationName(popt_context));
1455 if (opt_align_payload && strcmp(aname, "luksFormat"))
1456 usage(popt_context, EXIT_FAILURE, _("Option --align-payload is allowed only for luksFormat."),
1457 poptGetInvocationName(popt_context));
1459 if (opt_skip && strcmp(aname, "create") && strcmp(aname, "loopaesOpen"))
1460 usage(popt_context, EXIT_FAILURE,
1461 _("Option --skip is supported only for create and loopaesOpen commands.\n"),
1462 poptGetInvocationName(popt_context));
1464 if (opt_offset && strcmp(aname, "create") && strcmp(aname, "loopaesOpen"))
1465 usage(popt_context, EXIT_FAILURE,
1466 _("Option --offset is supported only for create and loopaesOpen commands.\n"),
1467 poptGetInvocationName(popt_context));
1471 crypt_set_debug_level(-1);
1472 _dbg_version_and_cmd(argc, argv);
1475 r = run_action(action);
1476 poptFreeContext(popt_context);