diff options
Diffstat (limited to '')
-rw-r--r-- | src/Makemodule.am | 118 | ||||
-rw-r--r-- | src/cryptsetup.c | 3603 | ||||
-rw-r--r-- | src/cryptsetup.h | 177 | ||||
-rw-r--r-- | src/cryptsetup_arg_list.h | 232 | ||||
-rw-r--r-- | src/cryptsetup_args.h | 113 | ||||
-rw-r--r-- | src/integritysetup.c | 767 | ||||
-rw-r--r-- | src/integritysetup_arg_list.h | 100 | ||||
-rw-r--r-- | src/integritysetup_args.h | 61 | ||||
-rw-r--r-- | src/utils_arg_macros.h | 103 | ||||
-rw-r--r-- | src/utils_arg_names.h | 173 | ||||
-rw-r--r-- | src/utils_args.c | 131 | ||||
-rw-r--r-- | src/utils_blockdev.c | 382 | ||||
-rw-r--r-- | src/utils_luks.c | 274 | ||||
-rw-r--r-- | src/utils_luks.h | 52 | ||||
-rw-r--r-- | src/utils_password.c | 331 | ||||
-rw-r--r-- | src/utils_progress.c | 301 | ||||
-rw-r--r-- | src/utils_reencrypt.c | 1560 | ||||
-rw-r--r-- | src/utils_reencrypt_luks1.c | 1354 | ||||
-rw-r--r-- | src/utils_tools.c | 468 | ||||
-rw-r--r-- | src/veritysetup.c | 680 | ||||
-rw-r--r-- | src/veritysetup_arg_list.h | 70 | ||||
-rw-r--r-- | src/veritysetup_args.h | 57 |
22 files changed, 11107 insertions, 0 deletions
diff --git a/src/Makemodule.am b/src/Makemodule.am new file mode 100644 index 0000000..57fff40 --- /dev/null +++ b/src/Makemodule.am @@ -0,0 +1,118 @@ +# cryptsetup +if CRYPTSETUP + +cryptsetup_SOURCES = \ + lib/utils_crypt.c \ + lib/utils_loop.c \ + lib/utils_io.c \ + lib/utils_blkid.c \ + src/utils_args.c \ + src/utils_tools.c \ + src/utils_password.c \ + src/utils_luks.c \ + src/utils_luks.h \ + src/utils_blockdev.c \ + src/utils_arg_names.h \ + src/utils_arg_macros.h \ + src/utils_reencrypt.c \ + src/utils_reencrypt_luks1.c \ + src/utils_progress.c \ + src/cryptsetup.c \ + src/cryptsetup.h \ + src/cryptsetup_args.h \ + src/cryptsetup_arg_list.h + +cryptsetup_LDADD = $(LDADD) \ + libcryptsetup.la \ + @POPT_LIBS@ \ + @PWQUALITY_LIBS@ \ + @PASSWDQC_LIBS@ \ + @UUID_LIBS@ \ + @BLKID_LIBS@ + +sbin_PROGRAMS += cryptsetup + +if STATIC_TOOLS +sbin_PROGRAMS += cryptsetup.static +cryptsetup_static_SOURCES = $(cryptsetup_SOURCES) +cryptsetup_static_LDFLAGS = $(AM_LDFLAGS) -all-static +cryptsetup_static_LDADD = \ + $(cryptsetup_LDADD) \ + @CRYPTO_STATIC_LIBS@ \ + @PWQUALITY_STATIC_LIBS@ \ + @DEVMAPPER_STATIC_LIBS@ +endif +endif + +# veritysetup +if VERITYSETUP + +veritysetup_SOURCES = \ + lib/utils_crypt.c \ + lib/utils_loop.c \ + lib/utils_io.c \ + lib/utils_blkid.c \ + src/utils_args.c \ + src/utils_arg_names.h \ + src/utils_arg_macros.h \ + src/utils_tools.c \ + src/veritysetup.c \ + src/veritysetup_args.h \ + src/veritysetup_arg_list.h \ + src/cryptsetup.h + +veritysetup_LDADD = $(LDADD) \ + libcryptsetup.la \ + @POPT_LIBS@ \ + @BLKID_LIBS@ + +sbin_PROGRAMS += veritysetup + +if STATIC_TOOLS +sbin_PROGRAMS += veritysetup.static +veritysetup_static_SOURCES = $(veritysetup_SOURCES) +veritysetup_static_LDFLAGS = $(AM_LDFLAGS) -all-static +veritysetup_static_LDADD = \ + $(veritysetup_LDADD) \ + @CRYPTO_STATIC_LIBS@ \ + @DEVMAPPER_STATIC_LIBS@ +endif +endif + +# integritysetup +if INTEGRITYSETUP + +integritysetup_SOURCES = \ + lib/utils_crypt.c \ + lib/utils_loop.c \ + lib/utils_io.c \ + lib/utils_blkid.c \ + src/utils_args.c \ + src/utils_arg_names.h \ + src/utils_arg_macros.h \ + src/utils_tools.c \ + src/utils_blockdev.c \ + src/utils_progress.c \ + src/integritysetup.c \ + src/integritysetup_args.h \ + src/integritysetup_arg_list.h \ + src/cryptsetup.h + +integritysetup_LDADD = $(LDADD) \ + libcryptsetup.la \ + @POPT_LIBS@ \ + @UUID_LIBS@ \ + @BLKID_LIBS@ + +sbin_PROGRAMS += integritysetup + +if STATIC_TOOLS +sbin_PROGRAMS += integritysetup.static +integritysetup_static_SOURCES = $(integritysetup_SOURCES) +integritysetup_static_LDFLAGS = $(AM_LDFLAGS) -all-static +integritysetup_static_LDADD = \ + $(integritysetup_LDADD) \ + @CRYPTO_STATIC_LIBS@ \ + @DEVMAPPER_STATIC_LIBS@ +endif +endif diff --git a/src/cryptsetup.c b/src/cryptsetup.c new file mode 100644 index 0000000..e387c1c --- /dev/null +++ b/src/cryptsetup.c @@ -0,0 +1,3603 @@ +/* + * cryptsetup - setup cryptographic volumes for dm-crypt + * + * Copyright (C) 2004 Jana Saout <jana@saout.de> + * Copyright (C) 2004-2007 Clemens Fruhwirth <clemens@endorphin.org> + * Copyright (C) 2009-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2009-2023 Milan Broz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <uuid/uuid.h> + +#include "cryptsetup.h" +#include "cryptsetup_args.h" +#include "utils_luks.h" + +static char *keyfiles[MAX_KEYFILES]; +static char *keyfile_stdin = NULL; + +static int keyfiles_count = 0; +int64_t data_shift = 0; + +const char *device_type = "luks"; +const char *set_pbkdf = NULL; + +static const char **action_argv; +static int action_argc; +static const char *null_action_argv[] = {NULL, NULL}; +static int total_keyfiles = 0; + +static struct tools_log_params log_parms; + +struct tools_arg tool_core_args[] = { { NULL, false, CRYPT_ARG_BOOL }, /* leave unused due to popt library */ +#define ARG(A, B, C, D, E, F, G, H) { A, false, F, G, H }, +#include "cryptsetup_arg_list.h" +#undef ARG +}; + +void tools_cleanup(void) +{ + tools_args_free(tool_core_args, ARRAY_SIZE(tool_core_args)); + + FREE_AND_NULL(keyfile_stdin); + + while (keyfiles_count) + free(keyfiles[--keyfiles_count]); + + total_keyfiles = 0; +} + +static const char *uuid_or_device_header(const char **data_device) +{ + if (data_device) + *data_device = ARG_SET(OPT_HEADER_ID) ? action_argv[0] : NULL; + + return uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]); +} + +static bool isLUKS(const char *type) +{ + return isLUKS2(type) || isLUKS1(type); +} + +static int _set_keyslot_encryption_params(struct crypt_device *cd) +{ + const char *type = crypt_get_type(cd); + + if (!ARG_SET(OPT_KEYSLOT_KEY_SIZE_ID) && !ARG_SET(OPT_KEYSLOT_CIPHER_ID)) + return 0; + + if (!isLUKS2(type)) { + log_err(_("Keyslot encryption parameters can be set only for LUKS2 device.")); + return -EINVAL; + } + + return crypt_keyslot_set_encryption(cd, ARG_STR(OPT_KEYSLOT_CIPHER_ID), ARG_UINT32(OPT_KEYSLOT_KEY_SIZE_ID) / 8); +} + +static int _try_token_pin_unlock(struct crypt_device *cd, + int token_id, + const char *activated_name, + const char *token_type, + uint32_t activate_flags, + int tries, + bool activation) +{ + size_t pin_len; + char msg[64], *pin = NULL; + int r; + + assert(tries >= 1); + assert(token_id >= 0 || token_id == CRYPT_ANY_TOKEN); + + if (token_id == CRYPT_ANY_TOKEN) + r = snprintf(msg, sizeof(msg), _("Enter token PIN: ")); + else + r = snprintf(msg, sizeof(msg), _("Enter token %d PIN: "), token_id); + if (r < 0 || (size_t)r >= sizeof(msg)) + return -EINVAL; + + do { + r = tools_get_key(msg, &pin, &pin_len, 0, 0, NULL, + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd); + if (r < 0) + break; + + if (activation) + r = crypt_activate_by_token_pin(cd, activated_name, token_type, + token_id, pin, pin_len, NULL, + activate_flags); + else + r = crypt_resume_by_token_pin(cd, activated_name, token_type, + token_id, pin, pin_len, NULL); + crypt_safe_free(pin); + pin = NULL; + tools_keyslot_msg(r, UNLOCKED); + tools_token_error_msg(r, ARG_STR(OPT_TOKEN_TYPE_ID), token_id, true); + check_signal(&r); + } while (r == -ENOANO && (--tries > 0)); + + return r; +} + +static int action_open_plain(void) +{ + struct crypt_device *cd = NULL, *cd1 = NULL; + const char *pcipher, *pmode; + char *msg, cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN]; + struct crypt_active_device cad; + struct crypt_params_plain params = { + .hash = ARG_SET(OPT_HASH_ID) ? ARG_STR(OPT_HASH_ID) : DEFAULT_PLAIN_HASH, + .skip = ARG_UINT64(OPT_SKIP_ID), + .offset = ARG_UINT64(OPT_OFFSET_ID), + .sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID) ?: SECTOR_SIZE + }; + char *password = NULL; + const char *activated_name = NULL; + size_t passwordLen, key_size_max, signatures = 0, + key_size = (ARG_UINT32(OPT_KEY_SIZE_ID) ?: DEFAULT_PLAIN_KEYBITS) / 8; + uint32_t activate_flags = 0; + int r; + + r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID) ?: DEFAULT_CIPHER(PLAIN), + cipher, NULL, cipher_mode); + if (r < 0) { + log_err(_("No known cipher specification pattern detected.")); + goto out; + } + + /* FIXME: temporary hack, no hashing for keyfiles in plain mode */ + if (ARG_SET(OPT_KEY_FILE_ID) && !tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID))) { + params.hash = NULL; + if (!ARG_SET(OPT_BATCH_MODE_ID) && ARG_SET(OPT_HASH_ID)) + log_std(_("WARNING: The --hash parameter is being ignored " + "in plain mode with keyfile specified.\n")); + } + + if (params.hash && !strcmp(params.hash, "plain")) + params.hash = NULL; + + if (!ARG_SET(OPT_BATCH_MODE_ID) && !params.hash && ARG_SET(OPT_KEY_FILE_ID) && !tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID)) && ARG_SET(OPT_KEYFILE_SIZE_ID)) + log_std(_("WARNING: The --keyfile-size option is being ignored, " + "the read size is the same as the encryption key size.\n")); + + if (ARG_SET(OPT_REFRESH_ID)) { + activated_name = action_argc > 1 ? action_argv[1] : action_argv[0]; + r = crypt_init_by_name_and_header(&cd1, activated_name, NULL); + if (r) + goto out; + r = crypt_get_active_device(cd1, activated_name, &cad); + if (r) + goto out; + + /* copy known parameters from existing device */ + params.skip = crypt_get_iv_offset(cd1); + params.offset = crypt_get_data_offset(cd1); + params.size = cad.size; + params.sector_size = crypt_get_sector_size(cd1); + key_size = crypt_get_volume_key_size(cd1); + + if ((r = crypt_init(&cd, crypt_get_device_name(cd1)))) + goto out; + + activate_flags |= CRYPT_ACTIVATE_REFRESH; + + pcipher = crypt_get_cipher(cd1); + pmode = crypt_get_cipher_mode(cd1); + } else { + activated_name = action_argv[1]; + if ((r = crypt_init(&cd, action_argv[0]))) + goto out; + + /* Skip blkid scan when activating plain device with offset */ + if (!ARG_UINT64(OPT_OFFSET_ID)) { + /* Print all present signatures in read-only mode */ + r = tools_detect_signatures(action_argv[0], PRB_FILTER_NONE, &signatures, ARG_SET(OPT_BATCH_MODE_ID)); + if (r < 0) + goto out; + } + + if (signatures && !ARG_SET(OPT_BATCH_MODE_ID)) { + r = asprintf(&msg, _("Detected device signature(s) on %s. Proceeding further may damage existing data."), action_argv[0]); + if (r == -1) { + r = -ENOMEM; + goto out; + } + + r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL; + free(msg); + if (r < 0) + goto out; + } + + pcipher = cipher; + pmode = cipher_mode; + } + + if (ARG_SET(OPT_DEVICE_SIZE_ID)) + params.size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE; + else if (ARG_SET(OPT_SIZE_ID)) + params.size = ARG_UINT64(OPT_SIZE_ID); + + r = crypt_format(cd, CRYPT_PLAIN, + pcipher, pmode, + NULL, NULL, + key_size, + ¶ms); + check_signal(&r); + if (r < 0) + goto out; + + if (ARG_SET(OPT_SHARED_ID)) + activate_flags |= CRYPT_ACTIVATE_SHARED; + + set_activation_flags(&activate_flags); + + if (!tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID))) { + /* If no hash, key is read directly, read size is always key_size + * (possible --keyfile_size is ignored. + * If hash is specified, --keyfile_size is applied. + * The --keyfile_offset is applied always. + */ + key_size_max = params.hash ? ARG_UINT32(OPT_KEYFILE_SIZE_ID) : key_size; + r = crypt_activate_by_keyfile_device_offset(cd, action_argv[1], + CRYPT_ANY_SLOT, ARG_STR(OPT_KEY_FILE_ID), key_size_max, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), activate_flags); + } else { + key_size_max = (ARG_SET(OPT_KEY_FILE_ID) && !params.hash) ? key_size : ARG_UINT32(OPT_KEYFILE_SIZE_ID); + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), key_size_max, + ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(0), 0, cd); + if (r < 0) + goto out; + + r = crypt_activate_by_passphrase(cd, activated_name, + CRYPT_ANY_SLOT, password, passwordLen, activate_flags); + } +out: + crypt_free(cd); + crypt_free(cd1); + crypt_safe_free(password); + + return r; +} + +static int action_open_loopaes(void) +{ + struct crypt_device *cd = NULL; + struct crypt_params_loopaes params = { + .hash = ARG_STR(OPT_HASH_ID), + .offset = ARG_UINT64(OPT_OFFSET_ID), + .skip = ARG_SET(OPT_SKIP_ID) ? ARG_UINT64(OPT_SKIP_ID) : ARG_UINT64(OPT_OFFSET_ID) + }; + unsigned int key_size = (ARG_UINT32(OPT_KEY_SIZE_ID) ?: DEFAULT_LOOPAES_KEYBITS) / 8; + uint32_t activate_flags = 0; + const char *activated_name = NULL; + int r; + + if (!ARG_SET(OPT_KEY_FILE_ID)) { + log_err(_("Option --key-file is required.")); + return -EINVAL; + } + + if (ARG_SET(OPT_REFRESH_ID)) { + activated_name = action_argc > 1 ? action_argv[1] : action_argv[0]; + if ((r = crypt_init_by_name(&cd, activated_name))) + goto out; + activate_flags |= CRYPT_ACTIVATE_REFRESH; + } else { + activated_name = action_argv[1]; + if ((r = crypt_init(&cd, action_argv[0]))) + goto out; + + r = crypt_format(cd, CRYPT_LOOPAES, ARG_STR(OPT_CIPHER_ID) ?: DEFAULT_LOOPAES_CIPHER, + NULL, NULL, NULL, key_size, ¶ms); + check_signal(&r); + if (r < 0) + goto out; + } + + set_activation_flags(&activate_flags); + + r = crypt_activate_by_keyfile_device_offset(cd, activated_name, CRYPT_ANY_SLOT, + tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID)) ? "/dev/stdin" : ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), activate_flags); +out: + crypt_free(cd); + + return r; +} + +static int tcrypt_load(struct crypt_device *cd, struct crypt_params_tcrypt *params) +{ + int r, tries, eperm = 0; + + tries = set_tries_tty(); + do { + /* TCRYPT header is encrypted, get passphrase now */ + r = tools_get_key(NULL, CONST_CAST(char**)¶ms->passphrase, + ¶ms->passphrase_size, 0, 0, keyfile_stdin, ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(0), 0, cd); + if (r < 0) + continue; + + if (ARG_SET(OPT_VERACRYPT_QUERY_PIM_ID)) { + char *tmp_pim_nptr = NULL; + char *tmp_pim_end = NULL; + size_t tmp_pim_size = 0; + unsigned long long tmp_pim_ull = 0; + + r = tools_get_key(_("Enter VeraCrypt PIM: "), + &tmp_pim_nptr, + &tmp_pim_size, 0, 0, keyfile_stdin, ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(0), 0, cd); + if (r < 0) + continue; + + tmp_pim_ull = strtoull(tmp_pim_nptr, &tmp_pim_end, 10); + if (*tmp_pim_nptr == '\0' || !tmp_pim_end || *tmp_pim_end != '\0') { + log_err(_("Invalid PIM value: parse error.")); + r = -EINVAL; + } else if (tmp_pim_ull == 0) { + log_err(_("Invalid PIM value: 0.")); + r = -EINVAL; + } else if (tmp_pim_ull > UINT32_MAX) { + log_err(_("Invalid PIM value: outside of range.")); + r = -ERANGE; + } + crypt_safe_free(tmp_pim_nptr); + if (r < 0) + continue; + + params->veracrypt_pim = (uint32_t)tmp_pim_ull; + crypt_safe_memzero(&tmp_pim_ull, sizeof(tmp_pim_ull)); + } + + if (ARG_SET(OPT_TCRYPT_HIDDEN_ID)) + params->flags |= CRYPT_TCRYPT_HIDDEN_HEADER; + + if (ARG_SET(OPT_TCRYPT_SYSTEM_ID)) + params->flags |= CRYPT_TCRYPT_SYSTEM_HEADER; + + if (ARG_SET(OPT_TCRYPT_BACKUP_ID)) + params->flags |= CRYPT_TCRYPT_BACKUP_HEADER; + + r = crypt_load(cd, CRYPT_TCRYPT, params); + + if (r == -EPERM) { + log_err(_("No device header detected with this passphrase.")); + eperm = 1; + } + + if (r < 0) { + crypt_safe_free(CONST_CAST(char*)params->passphrase); + params->passphrase = NULL; + params->passphrase_size = 0; + } + check_signal(&r); + } while ((r == -EPERM || r == -ERANGE) && (--tries > 0)); + + /* Report wrong passphrase if at least one try failed */ + if (eperm && r == -EPIPE) + r = -EPERM; + + return r; +} + +static int action_open_tcrypt(void) +{ + struct crypt_device *cd = NULL; + struct crypt_params_tcrypt params = { + .keyfiles = CONST_CAST(const char **)keyfiles, + .keyfiles_count = keyfiles_count, + .flags = CRYPT_TCRYPT_LEGACY_MODES | + (ARG_SET(OPT_DISABLE_VERACRYPT_ID) ? 0 : CRYPT_TCRYPT_VERA_MODES), + .veracrypt_pim = ARG_UINT32(OPT_VERACRYPT_PIM_ID), + .hash_name = ARG_STR(OPT_HASH_ID), + .cipher = ARG_STR(OPT_CIPHER_ID), + }; + const char *activated_name; + uint32_t activate_flags = 0; + int r; + + activated_name = ARG_SET(OPT_TEST_PASSPHRASE_ID) ? NULL : action_argv[1]; + + r = crypt_init_data_device(&cd, ARG_STR(OPT_HEADER_ID) ?: action_argv[0], action_argv[0]); + if (r < 0) + goto out; + + r = tcrypt_load(cd, ¶ms); + if (r < 0) + goto out; + + set_activation_flags(&activate_flags); + + if (activated_name) + r = crypt_activate_by_volume_key(cd, activated_name, NULL, 0, activate_flags); +out: + crypt_free(cd); + crypt_safe_free(CONST_CAST(char*)params.passphrase); + crypt_safe_memzero(¶ms.veracrypt_pim, sizeof(params.veracrypt_pim)); + return r; +} + +static int action_open_bitlk(void) +{ + struct crypt_device *cd = NULL; + const char *activated_name; + uint32_t activate_flags = 0; + int r, tries, keysize; + char *password = NULL; + char *key = NULL; + size_t passwordLen; + + activated_name = ARG_SET(OPT_TEST_PASSPHRASE_ID) ? NULL : action_argv[1]; + + if ((r = crypt_init(&cd, action_argv[0]))) + goto out; + + r = crypt_load(cd, CRYPT_BITLK, NULL); + if (r < 0) { + log_err(_("Device %s is not a valid BITLK device."), action_argv[0]); + goto out; + } + set_activation_flags(&activate_flags); + + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + keysize = crypt_get_volume_key_size(cd); + if (!keysize && !ARG_SET(OPT_KEY_SIZE_ID)) { + log_err(_("Cannot determine volume key size for BITLK, please use --key-size option.")); + r = -EINVAL; + goto out; + } else if (!keysize) + keysize = ARG_UINT32(OPT_KEY_SIZE_ID) / 8; + + r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &key, keysize); + if (r < 0) + goto out; + r = crypt_activate_by_volume_key(cd, activated_name, + key, keysize, activate_flags); + } else { + tries = set_tries_tty(); + do { + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd); + if (r < 0) + goto out; + + r = crypt_activate_by_passphrase(cd, activated_name, CRYPT_ANY_SLOT, + password, passwordLen, activate_flags); + tools_passphrase_msg(r); + check_signal(&r); + crypt_safe_free(password); + password = NULL; + } while ((r == -EPERM || r == -ERANGE) && (--tries > 0)); + } +out: + crypt_safe_free(password); + crypt_safe_free(key); + crypt_free(cd); + return r; +} + +static int tcryptDump_with_volume_key(struct crypt_device *cd) +{ + char *vk = NULL; + size_t vk_size; + int r; + + if (!ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog( + _("Header dump with volume key is sensitive information\n" + "which allows access to encrypted partition without passphrase.\n" + "This dump should be always stored encrypted on safe place."), + NULL)) + return -EPERM; + + vk_size = crypt_get_volume_key_size(cd); + vk = crypt_safe_alloc(vk_size); + if (!vk) + return -ENOMEM; + + r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size, NULL, 0); + if (r < 0) + goto out; + + log_std("TCRYPT header information for %s\n", crypt_get_device_name(cd)); + log_std("Cipher chain: \t%s\n", crypt_get_cipher(cd)); + log_std("Cipher mode: \t%s\n", crypt_get_cipher_mode(cd)); + log_std("Payload offset:\t%d\n", (int)crypt_get_data_offset(cd)); + log_std("MK bits: \t%d\n", (int)vk_size * 8); + log_std("MK dump:\t"); + crypt_log_hex(NULL, vk, vk_size, " ", 16, "\n\t\t"); + log_std("\n"); +out: + crypt_safe_free(vk); + return r; +} + +static int action_tcryptDump(void) +{ + struct crypt_device *cd = NULL; + struct crypt_params_tcrypt params = { + .keyfiles = CONST_CAST(const char **)keyfiles, + .keyfiles_count = keyfiles_count, + .flags = CRYPT_TCRYPT_LEGACY_MODES | + (ARG_SET(OPT_DISABLE_VERACRYPT_ID) ? 0: CRYPT_TCRYPT_VERA_MODES), + .veracrypt_pim = ARG_UINT32(OPT_VERACRYPT_PIM_ID), + .hash_name = ARG_STR(OPT_HASH_ID), + .cipher = ARG_STR(OPT_CIPHER_ID), + }; + int r; + r = crypt_init_data_device(&cd, ARG_STR(OPT_HEADER_ID) ?: action_argv[0], action_argv[0]); + if (r < 0) + goto out; + + r = tcrypt_load(cd, ¶ms); + if (r < 0) + goto out; + + if (ARG_SET(OPT_DUMP_VOLUME_KEY_ID)) + r = tcryptDump_with_volume_key(cd); + else + r = crypt_dump(cd); +out: + crypt_free(cd); + crypt_safe_free(CONST_CAST(char*)params.passphrase); + return r; +} + +static int bitlkDump_with_volume_key(struct crypt_device *cd) +{ + char *vk = NULL, *password = NULL; + size_t passwordLen = 0; + size_t vk_size; + int r; + + if (!ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog( + _("The header dump with volume key is sensitive information\n" + "that allows access to encrypted partition without a passphrase.\n" + "This dump should be stored encrypted in a safe place."), + NULL)) + return -EPERM; + + vk_size = crypt_get_volume_key_size(cd); + vk = crypt_safe_alloc(vk_size); + if (!vk) + return -ENOMEM; + + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), 0, 0, cd); + if (r < 0) + goto out; + + r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size, + password, passwordLen); + tools_passphrase_msg(r); + check_signal(&r); + if (r < 0) + goto out; + tools_keyslot_msg(r, UNLOCKED); + + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + r = tools_write_mk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), vk, vk_size); + if (r < 0) + goto out; + } + + log_std("BITLK header information for %s\n", crypt_get_device_name(cd)); + log_std("Cipher name: \t%s\n", crypt_get_cipher(cd)); + log_std("Cipher mode: \t%s\n", crypt_get_cipher_mode(cd)); + log_std("UUID: \t%s\n", crypt_get_uuid(cd)); + log_std("MK bits: \t%d\n", (int)vk_size * 8); + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + log_std("Key stored to file %s.\n", ARG_STR(OPT_VOLUME_KEY_FILE_ID)); + goto out; + } + log_std("MK dump:\t"); + crypt_log_hex(NULL, vk, vk_size, " ", 16, "\n\t\t"); + log_std("\n"); +out: + crypt_safe_free(password); + crypt_safe_free(vk); + return r; +} + +static int action_bitlkDump(void) +{ + struct crypt_device *cd = NULL; + int r; + + if ((r = crypt_init(&cd, action_argv[0]))) + goto out; + + r = crypt_load(cd, CRYPT_BITLK, NULL); + if (r < 0) { + log_err(_("Device %s is not a valid BITLK device."), action_argv[0]); + goto out; + } + + if (ARG_SET(OPT_DUMP_VOLUME_KEY_ID)) + r = bitlkDump_with_volume_key(cd); + else + r = crypt_dump(cd); +out: + crypt_free(cd); + return r; +} + +static int fvault2Dump_with_volume_key(struct crypt_device *cd) +{ + char *vk = NULL; + char *password = NULL; + size_t vk_size = 0; + size_t pass_len = 0; + int r = 0; + + if (!ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog( + _("The header dump with volume key is sensitive information\n" + "that allows access to encrypted partition without a passphrase.\n" + "This dump should be stored encrypted in a safe place."), + NULL)) + return -EPERM; + + vk_size = crypt_get_volume_key_size(cd); + vk = crypt_safe_alloc(vk_size); + if (vk == NULL) + return -ENOMEM; + + r = tools_get_key(NULL, &password, &pass_len, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), + ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID), 0, 0, cd); + if (r < 0) + goto out; + + r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size, password, pass_len); + tools_passphrase_msg(r); + check_signal(&r); + if (r < 0) + goto out; + + tools_keyslot_msg(r, UNLOCKED); + + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + r = tools_write_mk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), vk, vk_size); + if (r < 0) + goto out; + } + + r = crypt_dump(cd); + if (r < 0) + goto out; + + log_std("Volume key: \t"); + crypt_log_hex(cd, vk, vk_size, " ", 0, NULL); + log_std("\n"); +out: + crypt_safe_free(password); + crypt_safe_free(vk); + return r; +} + +static int action_fvault2Dump(void) +{ + struct crypt_device *cd = NULL; + int r = 0; + + r = crypt_init(&cd, action_argv[0]); + if (r < 0) + goto out; + + r = crypt_load(cd, CRYPT_FVAULT2, NULL); + if (r < 0) { + log_err(_("Device %s is not a valid FVAULT2 device."), action_argv[0]); + goto out; + } + + if (ARG_SET(OPT_DUMP_VOLUME_KEY_ID)) + r = fvault2Dump_with_volume_key(cd); + else + r = crypt_dump(cd); +out: + crypt_free(cd); + return r; +} + +static int action_open_fvault2(void) +{ + struct crypt_device *cd = NULL; + const char *activated_name; + uint32_t activate_flags = 0; + int r, tries, keysize; + char *password = NULL; + char *key = NULL; + size_t passwordLen; + + activated_name = ARG_SET(OPT_TEST_PASSPHRASE_ID) ? NULL : action_argv[1]; + + if ((r = crypt_init(&cd, action_argv[0]))) + goto out; + + r = crypt_load(cd, CRYPT_FVAULT2, NULL); + if (r < 0) { + log_err(_("Device %s is not a valid FVAULT2 device."), action_argv[0]); + goto out; + } + set_activation_flags(&activate_flags); + + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + keysize = crypt_get_volume_key_size(cd); + if (!keysize && !ARG_SET(OPT_KEY_SIZE_ID)) { + log_err(_("Cannot determine volume key size for FVAULT2, please use --key-size option.")); + r = -EINVAL; + goto out; + } else if (!keysize) + keysize = ARG_UINT32(OPT_KEY_SIZE_ID) / 8; + + r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &key, keysize); + if (r < 0) + goto out; + r = crypt_activate_by_volume_key(cd, activated_name, key, keysize, activate_flags); + } else { + tries = set_tries_tty(); + do { + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), + ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(0), 0, cd); + if (r < 0) + goto out; + + r = crypt_activate_by_passphrase(cd, activated_name, CRYPT_ANY_SLOT, + password, passwordLen, activate_flags); + tools_passphrase_msg(r); + check_signal(&r); + crypt_safe_free(password); + password = NULL; + } while ((r == -EPERM || r == -ERANGE) && (--tries > 0)); + } +out: + crypt_safe_free(password); + crypt_safe_free(key); + crypt_free(cd); + return r; +} + +static int action_close(void) +{ + struct crypt_device *cd = NULL; + crypt_status_info ci; + uint32_t flags = 0; + int r; + + if (ARG_SET(OPT_DEFERRED_ID)) + flags |= CRYPT_DEACTIVATE_DEFERRED; + if (ARG_SET(OPT_CANCEL_DEFERRED_ID)) + flags |= CRYPT_DEACTIVATE_DEFERRED_CANCEL; + + r = crypt_init_by_name_and_header(&cd, action_argv[0], ARG_STR(OPT_HEADER_ID)); + if (r == 0) + r = crypt_deactivate_by_name(cd, action_argv[0], flags); + + if (!r && ARG_SET(OPT_DEFERRED_ID)) { + ci = crypt_status(cd, action_argv[0]); + if (ci == CRYPT_ACTIVE || ci == CRYPT_BUSY) + log_std(_("Device %s is still active and scheduled for deferred removal.\n"), + action_argv[0]); + } + + crypt_free(cd); + return r; +} + +static int action_resize(void) +{ + int r; + size_t passwordLen; + struct crypt_active_device cad; + uint64_t dev_size = 0; + char *password = NULL; + struct crypt_device *cd = NULL; + + r = crypt_init_by_name_and_header(&cd, action_argv[0], ARG_STR(OPT_HEADER_ID)); + if (r) + goto out; + + /* FIXME: LUKS2 may enforce fixed size and it must not be changed */ + r = crypt_get_active_device(cd, action_argv[0], &cad); + if (r) + goto out; + + if (ARG_SET(OPT_DEVICE_SIZE_ID)) + dev_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE; + else if (ARG_SET(OPT_SIZE_ID)) + dev_size = ARG_UINT64(OPT_SIZE_ID); + + if (cad.flags & CRYPT_ACTIVATE_KEYRING_KEY) { + if (ARG_SET(OPT_DISABLE_KEYRING_ID)) { + r = -EINVAL; + log_err(_("Resize of active device requires volume key " + "in keyring but --disable-keyring option is set.")); + goto out; + } + + /* try load VK in kernel keyring using token */ + r = crypt_activate_by_token_pin(cd, NULL, ARG_STR(OPT_TOKEN_TYPE_ID), + ARG_INT32(OPT_TOKEN_ID_ID), NULL, 0, NULL, + CRYPT_ACTIVATE_KEYRING_KEY); + tools_keyslot_msg(r, UNLOCKED); + tools_token_error_msg(r, ARG_STR(OPT_TOKEN_TYPE_ID), ARG_INT32(OPT_TOKEN_ID_ID), false); + + /* Token requires PIN. Ask if there is evident preference for tokens */ + if (r == -ENOANO && (ARG_SET(OPT_TOKEN_ONLY_ID) || ARG_SET(OPT_TOKEN_TYPE_ID) || + ARG_SET(OPT_TOKEN_ID_ID))) + r = _try_token_pin_unlock(cd, ARG_INT32(OPT_TOKEN_ID_ID), NULL, ARG_STR(OPT_TOKEN_TYPE_ID), CRYPT_ACTIVATE_KEYRING_KEY, 1, true); + + if (r >= 0 || quit || ARG_SET(OPT_TOKEN_ONLY_ID)) + goto out; + + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd); + if (r < 0) + goto out; + + r = crypt_activate_by_passphrase(cd, NULL, ARG_INT32(OPT_KEY_SLOT_ID), + password, passwordLen, + CRYPT_ACTIVATE_KEYRING_KEY); + tools_passphrase_msg(r); + tools_keyslot_msg(r, UNLOCKED); + } + +out: + if (r >= 0) + r = crypt_resize(cd, action_argv[0], dev_size); + + crypt_safe_free(password); + crypt_free(cd); + return r; +} + +static int action_status(void) +{ + crypt_status_info ci; + crypt_reencrypt_info ri; + struct crypt_active_device cad; + struct crypt_params_integrity ip = {}; + struct crypt_device *cd = NULL; + char *backing_file; + const char *device; + int path = 0, r = 0; + + /* perhaps a path, not a dm device name */ + if (strchr(action_argv[0], '/')) + path = 1; + + ci = crypt_status(NULL, action_argv[0]); + switch (ci) { + case CRYPT_INVALID: + r = -EINVAL; + break; + case CRYPT_INACTIVE: + if (path) + log_std("%s is inactive.\n", action_argv[0]); + else + log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]); + r = -ENODEV; + break; + case CRYPT_ACTIVE: + case CRYPT_BUSY: + if (path) + log_std("%s is active%s.\n", action_argv[0], + ci == CRYPT_BUSY ? " and is in use" : ""); + else + log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0], + ci == CRYPT_BUSY ? " and is in use" : ""); + + r = crypt_init_by_name_and_header(&cd, action_argv[0], ARG_STR(OPT_HEADER_ID)); + if (r < 0) + goto out; + + log_std(" type: %s\n", crypt_get_type(cd) ?: "n/a"); + + /* Print only CRYPT type devices */ + if (!crypt_get_cipher(cd)) + goto out; + + ri = crypt_reencrypt_status(cd, NULL); + if (ri > CRYPT_REENCRYPT_NONE && ri < CRYPT_REENCRYPT_INVALID) + log_std(" reencryption: in-progress\n"); + + r = crypt_get_active_device(cd, action_argv[0], &cad); + if (r < 0) + goto out; + + r = crypt_get_integrity_info(cd, &ip); + if (r < 0 && r != -ENOTSUP) + goto out; + + log_std(" cipher: %s-%s\n", crypt_get_cipher(cd), crypt_get_cipher_mode(cd)); + log_std(" keysize: %d bits\n", crypt_get_volume_key_size(cd) * 8); + log_std(" key location: %s\n", (cad.flags & CRYPT_ACTIVATE_KEYRING_KEY) ? "keyring" : "dm-crypt"); + if (ip.integrity) + log_std(" integrity: %s\n", ip.integrity); + if (ip.integrity_key_size) + log_std(" integrity keysize: %d bits\n", ip.integrity_key_size * 8); + device = crypt_get_device_name(cd); + log_std(" device: %s\n", device); + if ((backing_file = crypt_loop_backing_file(device))) { + log_std(" loop: %s\n", backing_file); + free(backing_file); + } + log_std(" sector size: %d\n", crypt_get_sector_size(cd)); + log_std(" offset: %" PRIu64 " sectors\n", cad.offset); + log_std(" size: %" PRIu64 " sectors\n", cad.size); + if (cad.iv_offset) + log_std(" skipped: %" PRIu64 " sectors\n", cad.iv_offset); + log_std(" mode: %s%s\n", cad.flags & CRYPT_ACTIVATE_READONLY ? + "readonly" : "read/write", + (cad.flags & CRYPT_ACTIVATE_SUSPENDED) ? " (suspended)" : ""); + if (cad.flags & (CRYPT_ACTIVATE_ALLOW_DISCARDS| + CRYPT_ACTIVATE_SAME_CPU_CRYPT| + CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS| + CRYPT_ACTIVATE_NO_READ_WORKQUEUE| + CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE)) + log_std(" flags: %s%s%s%s%s\n", + (cad.flags & CRYPT_ACTIVATE_ALLOW_DISCARDS) ? "discards " : "", + (cad.flags & CRYPT_ACTIVATE_SAME_CPU_CRYPT) ? "same_cpu_crypt " : "", + (cad.flags & CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS) ? "submit_from_crypt_cpus " : "", + (cad.flags & CRYPT_ACTIVATE_NO_READ_WORKQUEUE) ? "no_read_workqueue " : "", + (cad.flags & CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE) ? "no_write_workqueue" : ""); + } +out: + crypt_free(cd); + if (r == -ENOTSUP) + r = 0; + return r; +} + +static int benchmark_callback(uint32_t time_ms, void *usrptr) +{ + struct crypt_pbkdf_type *pbkdf = usrptr; + int r = 0; + + check_signal(&r); + if (r) + log_err(_("Benchmark interrupted.")); + else + log_dbg("PBKDF benchmark: memory cost = %u, iterations = %u, " + "threads = %u (took %u ms)", pbkdf->max_memory_kb, + pbkdf->iterations, pbkdf->parallel_threads, time_ms); + return r; +} + +static int action_benchmark_kdf(const char *kdf, const char *hash, size_t key_size) +{ + int r; + if (!strcmp(kdf, CRYPT_KDF_PBKDF2)) { + struct crypt_pbkdf_type pbkdf = { + .type = CRYPT_KDF_PBKDF2, + .hash = hash, + .time_ms = 1000, + }; + + r = crypt_benchmark_pbkdf(NULL, &pbkdf, "foobarfo", 8, "0123456789abcdef", 16, key_size, + &benchmark_callback, &pbkdf); + if (r < 0) + log_std(_("PBKDF2-%-9s N/A\n"), hash); + else + log_std(_("PBKDF2-%-9s %7u iterations per second for %zu-bit key\n"), + hash, pbkdf.iterations, key_size * 8); + } else { + struct crypt_pbkdf_type pbkdf = { + .type = kdf, + .time_ms = ARG_UINT32(OPT_ITER_TIME_ID) ?: DEFAULT_LUKS2_ITER_TIME, + .max_memory_kb = ARG_UINT32(OPT_PBKDF_MEMORY_ID), + .parallel_threads = ARG_UINT32(OPT_PBKDF_PARALLEL_ID) + }; + + r = crypt_benchmark_pbkdf(NULL, &pbkdf, "foobarfo", 8, + "0123456789abcdef0123456789abcdef", 32, + key_size, &benchmark_callback, &pbkdf); + if (r < 0) + log_std(_("%-10s N/A\n"), kdf); + else + log_std(_("%-10s %4u iterations, %5u memory, " + "%1u parallel threads (CPUs) for " + "%zu-bit key (requested %u ms time)\n"), kdf, + pbkdf.iterations, pbkdf.max_memory_kb, pbkdf.parallel_threads, + key_size * 8, pbkdf.time_ms); + } + + return r; +} + +static int benchmark_cipher_loop(const char *cipher, const char *cipher_mode, + size_t volume_key_size, + double *encryption_mbs, double *decryption_mbs) +{ + int r, buffer_size = 1024 * 1024; + + do { + r = crypt_benchmark(NULL, cipher, cipher_mode, + volume_key_size, 0, buffer_size, + encryption_mbs, decryption_mbs); + if (r == -ERANGE) { + if (buffer_size < 1024 * 1024 * 65) + buffer_size *= 2; + else { + log_err(_("Result of benchmark is not reliable.")); + r = -ENOENT; + } + } + } while (r == -ERANGE); + + return r; +} + +static int action_benchmark(void) +{ + static struct { + const char *cipher; + const char *mode; + size_t key_size; + } bciphers[] = { + { "aes", "cbc", 16 }, + { "serpent", "cbc", 16 }, + { "twofish", "cbc", 16 }, + { "aes", "cbc", 32 }, + { "serpent", "cbc", 32 }, + { "twofish", "cbc", 32 }, + { "aes", "xts", 32 }, + { "serpent", "xts", 32 }, + { "twofish", "xts", 32 }, + { "aes", "xts", 64 }, + { "serpent", "xts", 64 }, + { "twofish", "xts", 64 }, + { NULL, NULL, 0 } + }; + static struct { + const char *type; + const char *hash; + } bkdfs[] = { + { CRYPT_KDF_PBKDF2, "sha1" }, + { CRYPT_KDF_PBKDF2, "sha256" }, + { CRYPT_KDF_PBKDF2, "sha512" }, + { CRYPT_KDF_PBKDF2, "ripemd160" }, + { CRYPT_KDF_PBKDF2, "whirlpool" }, + { CRYPT_KDF_ARGON2I, NULL }, + { CRYPT_KDF_ARGON2ID, NULL }, + { NULL, NULL } + }; + char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN]; + double enc_mbr = 0, dec_mbr = 0; + int key_size = (ARG_UINT32(OPT_KEY_SIZE_ID) ?: DEFAULT_PLAIN_KEYBITS) / 8; + int skipped = 0, width; + char *c; + int i, r; + + log_std(_("# Tests are approximate using memory only (no storage IO).\n")); + if (set_pbkdf || ARG_SET(OPT_HASH_ID)) { + if (!set_pbkdf && ARG_SET(OPT_HASH_ID)) + set_pbkdf = CRYPT_KDF_PBKDF2; + r = action_benchmark_kdf(set_pbkdf, ARG_STR(OPT_HASH_ID), key_size); + } else if (ARG_SET(OPT_CIPHER_ID)) { + r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID), cipher, NULL, cipher_mode); + if (r < 0) { + log_err(_("No known cipher specification pattern detected.")); + return r; + } + if ((c = strchr(cipher_mode, '-'))) + *c = '\0'; + + r = benchmark_cipher_loop(cipher, cipher_mode, key_size, &enc_mbr, &dec_mbr); + if (!r) { + width = strlen(cipher) + strlen(cipher_mode) + 1; + if (width < 11) + width = 11; + /* TRANSLATORS: The string is header of a table and must be exactly (right side) aligned. */ + log_std(_("#%*s Algorithm | Key | Encryption | Decryption\n"), width - 11, ""); + log_std("%*s-%s %9db %10.1f MiB/s %10.1f MiB/s\n", width - (int)strlen(cipher_mode) - 1, + cipher, cipher_mode, key_size*8, enc_mbr, dec_mbr); + } else if (r < 0) + log_err(_("Cipher %s (with %i bits key) is not available."), ARG_STR(OPT_CIPHER_ID), key_size * 8); + } else { + for (i = 0; bkdfs[i].type; i++) { + r = action_benchmark_kdf(bkdfs[i].type, bkdfs[i].hash, key_size); + check_signal(&r); + if (r == -EINTR) + break; + } + + for (i = 0; bciphers[i].cipher; i++) { + r = benchmark_cipher_loop(bciphers[i].cipher, bciphers[i].mode, + bciphers[i].key_size, &enc_mbr, &dec_mbr); + check_signal(&r); + if (r == -ENOTSUP || r == -EINTR) + break; + if (r == -ENOENT) + skipped++; + if (i == 0) + /* TRANSLATORS: The string is header of a table and must be exactly (right side) aligned. */ + log_std(_("# Algorithm | Key | Encryption | Decryption\n")); + + if (snprintf(cipher, MAX_CIPHER_LEN, "%s-%s", + bciphers[i].cipher, bciphers[i].mode) < 0) + r = -EINVAL; + + if (!r) + log_std("%15s %9zub %10.1f MiB/s %10.1f MiB/s\n", + cipher, bciphers[i].key_size*8, enc_mbr, dec_mbr); + else + log_std("%15s %9zub %17s %17s\n", cipher, + bciphers[i].key_size*8, _("N/A"), _("N/A")); + } + if (skipped && skipped == i) + r = -ENOTSUP; + } + + if (r == -ENOTSUP) { + log_err(_("Required kernel crypto interface not available.")); +#ifdef ENABLE_AF_ALG + log_err( _("Ensure you have algif_skcipher kernel module loaded.")); +#endif + } + return r; +} + +static int reencrypt_metadata_repair(struct crypt_device *cd) +{ + char *password; + size_t passwordLen; + int r; + struct crypt_params_reencrypt params = { + .flags = CRYPT_REENCRYPT_REPAIR_NEEDED + }; + + if (!ARG_SET(OPT_BATCH_MODE_ID) && + !yesDialog(_("Unprotected LUKS2 reencryption metadata detected. " + "Please verify the reencryption operation is desirable (see luksDump output)\n" + "and continue (upgrade metadata) only if you acknowledge the operation as genuine."), + _("Operation aborted.\n"))) + return -EINVAL; + + r = tools_get_key(_("Enter passphrase to protect and upgrade reencryption metadata: "), + &password, &passwordLen, ARG_UINT64(OPT_KEYFILE_OFFSET_ID), + ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(0), 0, cd); + if (r < 0) + return r; + + r = crypt_reencrypt_init_by_passphrase(cd, NULL, password, passwordLen, + ARG_INT32(OPT_KEY_SLOT_ID), ARG_INT32(OPT_KEY_SLOT_ID), NULL, NULL, ¶ms); + tools_passphrase_msg(r); + if (r < 0) + goto out; + + r = crypt_activate_by_passphrase(cd, NULL, ARG_INT32(OPT_KEY_SLOT_ID), + password, passwordLen, 0); + tools_passphrase_msg(r); + if (r >= 0) + r = 0; + +out: + crypt_safe_free(password); + return r; +} + +static int luks2_reencrypt_repair(struct crypt_device *cd) +{ + int r; + size_t passwordLen; + const char *msg; + char *password = NULL; + struct crypt_params_reencrypt params = {}; + + crypt_reencrypt_info ri = crypt_reencrypt_status(cd, ¶ms); + + if (params.flags & CRYPT_REENCRYPT_REPAIR_NEEDED) + return reencrypt_metadata_repair(cd); + + switch (ri) { + case CRYPT_REENCRYPT_NONE: + return 0; + case CRYPT_REENCRYPT_CLEAN: + break; + case CRYPT_REENCRYPT_CRASH: + if (!ARG_SET(OPT_BATCH_MODE_ID) && + !yesDialog(_("Really proceed with LUKS2 reencryption recovery?"), + _("Operation aborted.\n"))) + return -EINVAL; + break; + default: + return -EINVAL; + } + + if (ri == CRYPT_REENCRYPT_CLEAN) + msg = _("Enter passphrase to verify reencryption metadata digest: "); + else + msg = _("Enter passphrase for reencryption recovery: "); + + r = tools_get_key(msg, &password, &passwordLen, ARG_UINT64(OPT_KEYFILE_OFFSET_ID), + ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(0), 0, cd); + if (r < 0) + return r; + + r = crypt_activate_by_passphrase(cd, NULL, ARG_INT32(OPT_KEY_SLOT_ID), + password, passwordLen, 0); + if (r < 0) + goto out; + + if (ri == CRYPT_REENCRYPT_CLEAN) { + r = 0; + goto out; + } + + r = crypt_reencrypt_init_by_passphrase(cd, NULL, password, passwordLen, + ARG_INT32(OPT_KEY_SLOT_ID), ARG_INT32(OPT_KEY_SLOT_ID), NULL, NULL, + &(struct crypt_params_reencrypt){ .flags = CRYPT_REENCRYPT_RECOVERY }); + if (r > 0) + r = 0; +out: + crypt_safe_free(password); + + return r; +} + +static int action_luksRepair(void) +{ + struct crypt_device *cd = NULL; + int r; + + if ((r = crypt_init_data_device(&cd, ARG_STR(OPT_HEADER_ID) ?: action_argv[0], + action_argv[0]))) + goto out; + + crypt_set_log_callback(cd, quiet_log, &log_parms); + r = crypt_load(cd, luksType(device_type), NULL); + crypt_set_log_callback(cd, tool_log, &log_parms); + if (r == 0 && isLUKS2(crypt_get_type(cd))) { + /* + * LUKS2 triggers autorepair in crypt_load() above + * LUKS1 need to call crypt_repair() even if crypt_load() is ok + */ + log_verbose(_("No known problems detected for LUKS header.")); + goto out; + } + + r = tools_detect_signatures(action_argv[0], PRB_FILTER_LUKS, NULL, ARG_SET(OPT_BATCH_MODE_ID)); + if (r < 0) + goto out; + + if (!ARG_SET(OPT_BATCH_MODE_ID) && + !yesDialog(_("Really try to repair LUKS device header?"), + _("Operation aborted.\n"))) + r = -EINVAL; + else + r = crypt_repair(cd, luksType(device_type), NULL); +out: + /* Header is ok, check if reencryption metadata needs repair/recovery. */ + if (!r && isLUKS2(crypt_get_type(cd))) + r = luks2_reencrypt_repair(cd); + + crypt_free(cd); + return r; +} + +static int _wipe_data_device(struct crypt_device *cd) +{ + char tmp_name[64], tmp_path[128], tmp_uuid[40]; + uuid_t tmp_uuid_bin; + int r = -EINVAL; + char *backing_file = NULL; + struct tools_progress_params prog_parms = { + .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID), + .batch_mode = ARG_SET(OPT_BATCH_MODE_ID), + .json_output = ARG_SET(OPT_PROGRESS_JSON_ID), + .interrupt_message = _("\nWipe interrupted."), + .device = tools_get_device_name(crypt_get_device_name(cd), &backing_file) + }; + + if (!ARG_SET(OPT_BATCH_MODE_ID)) + log_std(_("Wiping device to initialize integrity checksum.\n" + "You can interrupt this by pressing CTRL+c " + "(rest of not wiped device will contain invalid checksum).\n")); + + /* Activate the device a temporary one */ + uuid_generate(tmp_uuid_bin); + uuid_unparse(tmp_uuid_bin, tmp_uuid); + if (snprintf(tmp_name, sizeof(tmp_name), "temporary-cryptsetup-%s", tmp_uuid) < 0) + goto out; + if (snprintf(tmp_path, sizeof(tmp_path), "%s/%s", crypt_get_dir(), tmp_name) < 0) + goto out; + + r = crypt_activate_by_volume_key(cd, tmp_name, NULL, 0, + CRYPT_ACTIVATE_PRIVATE | CRYPT_ACTIVATE_NO_JOURNAL); + if (r < 0) + goto out; + + /* Wipe the device */ + set_int_handler(0); + r = crypt_wipe(cd, tmp_path, CRYPT_WIPE_ZERO, 0, 0, DEFAULT_WIPE_BLOCK, + 0, &tools_progress, &prog_parms); + if (crypt_deactivate(cd, tmp_name)) + log_err(_("Cannot deactivate temporary device %s."), tmp_path); + set_int_block(0); + +out: + free(backing_file); + return r; +} + +static int strcmp_or_null(const char *str, const char *expected) +{ + return !str ? 0 : strcmp(str, expected); +} + +int luksFormat(struct crypt_device **r_cd, char **r_password, size_t *r_passwordLen) +{ + int r = -EINVAL, keysize, integrity_keysize = 0, fd, created = 0; + struct stat st; + const char *header_device, *type; + char *msg = NULL, *key = NULL, *password = NULL; + char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN], integrity[MAX_CIPHER_LEN]; + size_t passwordLen, signatures; + struct crypt_device *cd = NULL; + struct crypt_params_luks1 params1 = { + .hash = ARG_STR(OPT_HASH_ID) ?: DEFAULT_LUKS1_HASH, + .data_alignment = ARG_UINT32(OPT_ALIGN_PAYLOAD_ID), + .data_device = ARG_SET(OPT_HEADER_ID) ? action_argv[0] : NULL, + }; + struct crypt_params_luks2 params2 = { + .data_alignment = params1.data_alignment, + .data_device = params1.data_device, + .sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID), + .label = ARG_STR(OPT_LABEL_ID), + .subsystem = ARG_STR(OPT_SUBSYSTEM_ID) + }; + void *params; + + type = luksType(device_type); + if (!type) + type = crypt_get_default_type(); + + if (isLUKS2(type)) { + params = ¶ms2; + } else if (isLUKS1(type)) { + params = ¶ms1; + + if (ARG_UINT32(OPT_SECTOR_SIZE_ID) > SECTOR_SIZE) { + log_err(_("Unsupported encryption sector size.")); + return -EINVAL; + } + + if (ARG_SET(OPT_INTEGRITY_ID)) { + log_err(_("Integrity option can be used only for LUKS2 format.")); + return -EINVAL; + } + + if (ARG_SET(OPT_LUKS2_KEYSLOTS_SIZE_ID) || ARG_SET(OPT_LUKS2_METADATA_SIZE_ID)) { + log_err(_("Unsupported LUKS2 metadata size options.")); + return -EINVAL; + } + } else + return -EINVAL; + + /* Create header file (must contain at least one sector)? */ + if (ARG_SET(OPT_HEADER_ID) && stat(ARG_STR(OPT_HEADER_ID), &st) < 0 && errno == ENOENT) { + if (!ARG_SET(OPT_BATCH_MODE_ID) && + !yesDialog(_("Header file does not exist, do you want to create it?"), + _("Operation aborted.\n"))) + return -EPERM; + + log_dbg("Creating header file."); + /* coverity[toctou] */ + fd = open(ARG_STR(OPT_HEADER_ID), O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR); + if (fd == -1 || posix_fallocate(fd, 0, 4096)) + log_err(_("Cannot create header file %s."), ARG_STR(OPT_HEADER_ID)); + else { + r = 0; + created = 1; + } + if (fd != -1) + close(fd); + if (r < 0) + return r; + } + + header_device = ARG_STR(OPT_HEADER_ID) ?: action_argv[0]; + + r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID) ?: DEFAULT_CIPHER(LUKS1), + cipher, NULL, cipher_mode); + if (r < 0) { + log_err(_("No known cipher specification pattern detected.")); + goto out; + } + + if (ARG_SET(OPT_INTEGRITY_ID)) { + r = crypt_parse_integrity_mode(ARG_STR(OPT_INTEGRITY_ID), integrity, &integrity_keysize); + if (r < 0) { + log_err(_("No known integrity specification pattern detected.")); + goto out; + } + params2.integrity = integrity; + /* FIXME: we use default integrity_params (set to NULL) */ + } + + /* Never call pwquality if using null cipher */ + if (crypt_is_cipher_null(cipher)) + ARG_SET_TRUE(OPT_FORCE_PASSWORD_ID); + + if ((r = crypt_init(&cd, header_device))) { + if (ARG_SET(OPT_HEADER_ID)) + log_err(_("Cannot use %s as on-disk header."), header_device); + return r; + } + + if (ARG_SET(OPT_LUKS2_KEYSLOTS_SIZE_ID) || ARG_SET(OPT_LUKS2_METADATA_SIZE_ID)) { + r = crypt_set_metadata_size(cd, ARG_UINT64(OPT_LUKS2_METADATA_SIZE_ID), ARG_UINT64(OPT_LUKS2_KEYSLOTS_SIZE_ID)); + if (r < 0) { + log_err(_("Unsupported LUKS2 metadata size options.")); + goto out; + } + } + + if (ARG_SET(OPT_OFFSET_ID)) { + r = crypt_set_data_offset(cd, ARG_UINT64(OPT_OFFSET_ID)); + if (r < 0) + goto out; + } + + /* Print all present signatures in read-only mode */ + r = tools_detect_signatures(header_device, PRB_FILTER_NONE, &signatures, ARG_SET(OPT_BATCH_MODE_ID)); + if (r < 0) + goto out; + + if (!created && !ARG_SET(OPT_BATCH_MODE_ID)) { + r = asprintf(&msg, _("This will overwrite data on %s irrevocably."), header_device); + if (r == -1) { + r = -ENOMEM; + goto out; + } + + r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL; + free(msg); + if (r < 0) + goto out; + } + + keysize = get_adjusted_key_size(cipher_mode, DEFAULT_LUKS1_KEYBITS, integrity_keysize); + + if (ARG_SET(OPT_USE_RANDOM_ID)) + crypt_set_rng_type(cd, CRYPT_RNG_RANDOM); + else if (ARG_SET(OPT_USE_URANDOM_ID)) + crypt_set_rng_type(cd, CRYPT_RNG_URANDOM); + + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(1), !ARG_SET(OPT_FORCE_PASSWORD_ID), cd); + if (r < 0) + goto out; + + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &key, keysize); + if (r < 0) + goto out; + } + + r = set_pbkdf_params(cd, type); + if (r) { + log_err(_("Failed to set pbkdf parameters.")); + goto out; + } + + /* Signature candidates found */ + if (signatures && ((r = tools_wipe_all_signatures(header_device, true, false)) < 0)) + goto out; + + if (ARG_SET(OPT_INTEGRITY_LEGACY_PADDING_ID)) + crypt_set_compatibility(cd, CRYPT_COMPAT_LEGACY_INTEGRITY_PADDING); + + r = crypt_format(cd, type, cipher, cipher_mode, + ARG_STR(OPT_UUID_ID), key, keysize, params); + check_signal(&r); + if (r < 0) + goto out; + + r = _set_keyslot_encryption_params(cd); + if (r < 0) + goto out; + + r = crypt_keyslot_add_by_volume_key(cd, ARG_INT32(OPT_KEY_SLOT_ID), + key, keysize, + password, passwordLen); + if (r < 0) { + (void) tools_wipe_all_signatures(header_device, true, false); + goto out; + } + tools_keyslot_msg(r, CREATED); + + if (ARG_SET(OPT_INTEGRITY_ID) && !ARG_SET(OPT_INTEGRITY_NO_WIPE_ID) && + strcmp_or_null(params2.integrity, "none")) + r = _wipe_data_device(cd); +out: + if (r >= 0 && r_cd && r_password && r_passwordLen) { + *r_cd = cd; + *r_password = password; + *r_passwordLen = passwordLen; + } else { + crypt_free(cd); + crypt_safe_free(password); + } + + crypt_safe_free(key); + + return r; +} + +static int action_luksFormat(void) +{ + return luksFormat(NULL, NULL, NULL); +} + +static int action_open_luks(void) +{ + struct crypt_active_device cad; + struct crypt_device *cd = NULL; + const char *data_device, *header_device, *activated_name; + char *key = NULL; + uint32_t activate_flags = 0; + int r, keysize, tries; + char *password = NULL; + size_t passwordLen; + struct stat st; + + if (ARG_SET(OPT_REFRESH_ID)) { + activated_name = action_argc > 1 ? action_argv[1] : action_argv[0]; + r = crypt_init_by_name_and_header(&cd, activated_name, ARG_STR(OPT_HEADER_ID)); + if (r) + goto out; + activate_flags |= CRYPT_ACTIVATE_REFRESH; + } else { + header_device = uuid_or_device_header(&data_device); + + activated_name = ARG_SET(OPT_TEST_PASSPHRASE_ID) ? NULL : action_argv[1]; + + if ((r = crypt_init_data_device(&cd, header_device, data_device))) + goto out; + + if ((r = crypt_load(cd, luksType(device_type), NULL))) { + log_err(_("Device %s is not a valid LUKS device."), + header_device); + goto out; + } + + if (!data_device && (crypt_get_data_offset(cd) < 8) && !ARG_SET(OPT_TEST_PASSPHRASE_ID)) { + log_err(_("Reduced data offset is allowed only for detached LUKS header.")); + r = -EINVAL; + goto out; + } + + if (activated_name && !stat(crypt_get_device_name(cd), &st) && S_ISREG(st.st_mode) && + crypt_get_data_offset(cd) >= ((uint64_t)st.st_size / SECTOR_SIZE)) { + log_err(_("LUKS file container %s is too small for activation, there is no remaining space for data."), + crypt_get_device_name(cd)); + r = -EINVAL; + goto out; + } + } + + set_activation_flags(&activate_flags); + + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + keysize = crypt_get_volume_key_size(cd); + if (!keysize && !ARG_SET(OPT_KEY_SIZE_ID)) { + log_err(_("Cannot determine volume key size for LUKS without keyslots, please use --key-size option.")); + r = -EINVAL; + goto out; + } else if (!keysize) + keysize = ARG_UINT32(OPT_KEY_SIZE_ID) / 8; + + r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &key, keysize); + if (r < 0) + goto out; + r = crypt_activate_by_volume_key(cd, activated_name, + key, keysize, activate_flags); + } else { + r = crypt_activate_by_token_pin(cd, activated_name, ARG_STR(OPT_TOKEN_TYPE_ID), + ARG_INT32(OPT_TOKEN_ID_ID), NULL, 0, NULL, activate_flags); + tools_keyslot_msg(r, UNLOCKED); + tools_token_error_msg(r, ARG_STR(OPT_TOKEN_TYPE_ID), ARG_INT32(OPT_TOKEN_ID_ID), false); + + /* Token requires PIN. Ask if there is evident preference for tokens */ + if (r == -ENOANO && (ARG_SET(OPT_TOKEN_ONLY_ID) || ARG_SET(OPT_TOKEN_TYPE_ID) || + ARG_SET(OPT_TOKEN_ID_ID))) + r = _try_token_pin_unlock(cd, ARG_INT32(OPT_TOKEN_ID_ID), activated_name, ARG_STR(OPT_TOKEN_TYPE_ID), activate_flags, set_tries_tty(), true); + + if (r >= 0 || r == -EEXIST || quit || ARG_SET(OPT_TOKEN_ONLY_ID)) + goto out; + + tries = set_tries_tty(); + do { + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd); + if (r < 0) + goto out; + + r = crypt_activate_by_passphrase(cd, activated_name, + ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen, activate_flags); + tools_keyslot_msg(r, UNLOCKED); + tools_passphrase_msg(r); + check_signal(&r); + crypt_safe_free(password); + password = NULL; + } while ((r == -EPERM || r == -ERANGE) && (--tries > 0)); + } +out: + if (r >= 0 && ARG_SET(OPT_PERSISTENT_ID) && + (crypt_get_active_device(cd, activated_name, &cad) || + crypt_persistent_flags_set(cd, CRYPT_FLAGS_ACTIVATION, cad.flags & activate_flags))) + log_err(_("Device activated but cannot make flags persistent.")); + + crypt_safe_free(key); + crypt_safe_free(password); + crypt_free(cd); + return r; +} + +static int verify_keyslot(struct crypt_device *cd, int key_slot, crypt_keyslot_info ki, + char *msg_last, char *msg_pass, char *msg_fail, + const char *key_file, uint64_t keyfile_offset, + int keyfile_size) +{ + char *password = NULL; + size_t passwordLen; + int i, max, r; + + if (ki == CRYPT_SLOT_ACTIVE_LAST && !ARG_SET(OPT_BATCH_MODE_ID) && !key_file && + msg_last && !ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog(msg_last, msg_fail)) + return -EPERM; + + r = tools_get_key(msg_pass, &password, &passwordLen, + keyfile_offset, keyfile_size, key_file, ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(0), 0, cd); + if (r < 0) + goto out; + + if (ki == CRYPT_SLOT_ACTIVE_LAST) { + /* check the last keyslot */ + r = crypt_activate_by_passphrase(cd, NULL, key_slot, + password, passwordLen, 0); + } else { + /* try all other keyslots */ + r = crypt_keyslot_max(crypt_get_type(cd)); + if (r < 0) + goto out; + max = r; + + for (i = 0; i < max ; i++) { + if (i == key_slot) + continue; + ki = crypt_keyslot_status(cd, i); + if (ki == CRYPT_SLOT_ACTIVE || ki == CRYPT_SLOT_ACTIVE_LAST) + r = crypt_activate_by_passphrase(cd, NULL, i, + password, passwordLen, 0); + if (r == i) + break; + } + } + + /* Handle inactive keyslots the same as bad password here */ + if (r == -ENOENT) + r = -EPERM; + tools_passphrase_msg(r); +out: + crypt_safe_free(password); + return r; +} + +static int action_luksKillSlot(void) +{ + struct crypt_device *cd = NULL; + crypt_keyslot_info ki; + int r; + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + if ((r = crypt_load(cd, luksType(device_type), NULL))) { + log_err(_("Device %s is not a valid LUKS device."), + uuid_or_device_header(NULL)); + goto out; + } + + ki = crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)); + switch (ki) { + case CRYPT_SLOT_ACTIVE_LAST: + case CRYPT_SLOT_ACTIVE: + case CRYPT_SLOT_UNBOUND: + log_verbose(_("Keyslot %d is selected for deletion."), ARG_INT32(OPT_KEY_SLOT_ID)); + break; + case CRYPT_SLOT_INACTIVE: + log_err(_("Keyslot %d is not active."), ARG_INT32(OPT_KEY_SLOT_ID)); + /* fall through */ + case CRYPT_SLOT_INVALID: + r = -EINVAL; + goto out; + } + + if (!ARG_SET(OPT_BATCH_MODE_ID) || ARG_SET(OPT_KEY_FILE_ID) || !isatty(STDIN_FILENO)) { + r = verify_keyslot(cd, ARG_INT32(OPT_KEY_SLOT_ID), ki, + _("This is the last keyslot. Device will become unusable after purging this key."), + _("Enter any remaining passphrase: "), + _("Operation aborted, the keyslot was NOT wiped.\n"), + ARG_STR(OPT_KEY_FILE_ID), ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID)); + tools_keyslot_msg(r, UNLOCKED); + + if (r == -EPIPE && (!ARG_SET(OPT_KEY_FILE_ID) || tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID)))) { + log_dbg("Failed read from input, ignoring passphrase."); + r = 0; + } + + if (r < 0) + goto out; + } + + r = crypt_keyslot_destroy(cd, ARG_INT32(OPT_KEY_SLOT_ID)); + tools_keyslot_msg(ARG_INT32(OPT_KEY_SLOT_ID), REMOVED); +out: + crypt_free(cd); + return r; +} + +static int action_luksRemoveKey(void) +{ + struct crypt_device *cd = NULL; + char *password = NULL; + size_t passwordLen; + int r; + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + if ((r = crypt_load(cd, luksType(device_type), NULL))) { + log_err(_("Device %s is not a valid LUKS device."), + uuid_or_device_header(NULL)); + goto out; + } + + r = tools_get_key(_("Enter passphrase to be deleted: "), + &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(0), 0, + cd); + if(r < 0) + goto out; + + r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT, + password, passwordLen, 0); + tools_passphrase_msg(r); + check_signal(&r); + if (r < 0) + goto out; + tools_keyslot_msg(r, UNLOCKED); + + ARG_SET_INT32(OPT_KEY_SLOT_ID, r); + log_verbose(_("Keyslot %d is selected for deletion."), ARG_INT32(OPT_KEY_SLOT_ID)); + + if (crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)) == CRYPT_SLOT_ACTIVE_LAST && + !ARG_SET(OPT_BATCH_MODE_ID) && + !yesDialog(_("This is the last keyslot. " + "Device will become unusable after purging this key."), + _("Operation aborted, the keyslot was NOT wiped.\n"))) { + r = -EPERM; + goto out; + } + + r = crypt_keyslot_destroy(cd, ARG_INT32(OPT_KEY_SLOT_ID)); + tools_keyslot_msg(ARG_INT32(OPT_KEY_SLOT_ID), REMOVED); +out: + crypt_safe_free(password); + crypt_free(cd); + return r; +} + +static int luksAddUnboundKey(void) +{ + int r = -EINVAL, keysize = 0; + char *key = NULL; + const char *new_key_file = (action_argc > 1 ? action_argv[1] : NULL); + char *password_new = NULL; + size_t password_new_size = 0; + struct crypt_device *cd = NULL; + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + if ((r = crypt_load(cd, CRYPT_LUKS2, NULL))) { + log_err(_("Device %s is not a valid LUKS2 device."), + uuid_or_device_header(NULL)); + goto out; + } + + r = _set_keyslot_encryption_params(cd); + if (r < 0) + goto out; + + /* Never call pwquality if using null cipher */ + if (crypt_is_cipher_null(crypt_get_cipher(cd))) + ARG_SET_TRUE(OPT_FORCE_PASSWORD_ID); + + keysize = ARG_UINT32(OPT_KEY_SIZE_ID) / 8; + r = set_pbkdf_params(cd, crypt_get_type(cd)); + if (r) { + log_err(_("Failed to set pbkdf parameters.")); + goto out; + } + + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &key, keysize); + if (r < 0) + goto out; + + check_signal(&r); + if (r < 0) + goto out; + } + + r = tools_get_key(_("Enter new passphrase for key slot: "), + &password_new, &password_new_size, + ARG_UINT64(OPT_NEW_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_NEW_KEYFILE_SIZE_ID), + new_key_file, ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(1), !ARG_SET(OPT_FORCE_PASSWORD_ID), cd); + if (r < 0) + goto out; + + r = crypt_keyslot_add_by_key(cd, ARG_INT32(OPT_KEY_SLOT_ID), key, keysize, + password_new, password_new_size, CRYPT_VOLUME_KEY_NO_SEGMENT); + tools_keyslot_msg(r, CREATED); +out: + crypt_safe_free(password_new); + crypt_safe_free(key); + crypt_free(cd); + return r; +} + +static int _ask_for_pin(struct crypt_device *cd, + int token_id, char **r_pin, size_t *r_pin_size, + struct crypt_keyslot_context *kc) +{ + int r; + char msg[64]; + + assert(r_pin); + assert(r_pin_size); + assert(kc); + assert(token_id >= 0 || token_id == CRYPT_ANY_TOKEN); + + if (crypt_keyslot_context_get_type(kc) != CRYPT_KC_TYPE_TOKEN) + return -EINVAL; + + if (token_id == CRYPT_ANY_TOKEN) + r = snprintf(msg, sizeof(msg), _("Enter token PIN: ")); + else + r = snprintf(msg, sizeof(msg), _("Enter token %d PIN: "), token_id); + if (r < 0 || (size_t)r >= sizeof(msg)) + return -EINVAL; + + r = tools_get_key(msg, r_pin, r_pin_size, 0, 0, NULL, + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd); + if (r < 0) + return r; + + r = crypt_keyslot_context_set_pin(cd, *r_pin, *r_pin_size, kc); + if (r < 0) { + crypt_safe_free(*r_pin); + *r_pin = NULL; + *r_pin_size = 0; + } + + return r; +} + +static int try_keyslot_add(struct crypt_device *cd, + int keyslot_existing, + int keyslot_new, + struct crypt_keyslot_context *kc, + struct crypt_keyslot_context *kc_new, + bool pin_provided, + bool new_pin_provided) +{ + int r; + + r = crypt_keyslot_add_by_keyslot_context(cd, keyslot_existing, kc, keyslot_new, kc_new, 0); + if (crypt_keyslot_context_get_type(kc) == CRYPT_KC_TYPE_TOKEN) + tools_token_error_msg(crypt_keyslot_context_get_error(kc), ARG_STR(OPT_TOKEN_TYPE_ID), + ARG_INT32(OPT_TOKEN_ID_ID), pin_provided); + if (crypt_keyslot_context_get_type(kc_new) == CRYPT_KC_TYPE_TOKEN) + tools_token_error_msg(crypt_keyslot_context_get_error(kc_new), NULL, + ARG_INT32(OPT_NEW_TOKEN_ID_ID), new_pin_provided); + return r; +} + +static int action_luksAddKey(void) +{ + int keyslot_old, keyslot_new, keysize = 0, r = -EINVAL; + const char *new_key_file = (action_argc > 1 ? action_argv[1] : NULL); + char *key = NULL, *password = NULL, *password_new = NULL, *pin = NULL, *pin_new = NULL; + size_t pin_size, pin_size_new, password_size = 0, password_new_size = 0; + struct crypt_device *cd = NULL; + struct crypt_keyslot_context *p_kc_new = NULL, *kc = NULL, *kc_new = NULL; + + /* Unbound keyslot (no assigned data segment) is special case */ + if (ARG_SET(OPT_UNBOUND_ID)) + return luksAddUnboundKey(); + + /* maintain backward compatibility of luksAddKey action positional parameter */ + if (!new_key_file) + new_key_file = ARG_STR(OPT_NEW_KEYFILE_ID); + + keyslot_old = ARG_INT32(OPT_KEY_SLOT_ID); + keyslot_new = ARG_INT32(OPT_NEW_KEY_SLOT_ID); + + /* + * maintain backward compatibility of --key-slot/-S as 'new keyslot number' + * unless --new-key-slot is used. + */ + if (!ARG_SET(OPT_NEW_KEY_SLOT_ID) && ARG_SET(OPT_KEY_SLOT_ID)) { + if (!ARG_SET(OPT_BATCH_MODE_ID)) + log_std(_("WARNING: The --key-slot parameter is used for new keyslot number.\n")); + keyslot_old = CRYPT_ANY_SLOT; + keyslot_new = ARG_INT32(OPT_KEY_SLOT_ID); + } + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + if ((r = crypt_load(cd, luksType(device_type), NULL))) { + log_err(_("Device %s is not a valid LUKS device."), + uuid_or_device_header(NULL)); + goto out; + } + + r = _set_keyslot_encryption_params(cd); + if (r < 0) + goto out; + + /* Never call pwquality if using null cipher */ + if (crypt_is_cipher_null(crypt_get_cipher(cd))) + ARG_SET_TRUE(OPT_FORCE_PASSWORD_ID); + + keysize = crypt_get_volume_key_size(cd); + r = set_pbkdf_params(cd, crypt_get_type(cd)); + if (r) { + log_err(_("Failed to set pbkdf parameters.")); + goto out; + } + + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + if (!keysize && !ARG_SET(OPT_KEY_SIZE_ID)) { + log_err(_("Cannot determine volume key size for LUKS without keyslots, please use --key-size option.")); + r = -EINVAL; + goto out; + } else if (!keysize) + keysize = ARG_UINT32(OPT_KEY_SIZE_ID) / 8; + + r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &key, keysize); + if (r < 0) + goto out; + + r = crypt_volume_key_verify(cd, key, keysize); + if (r == -EPERM) + log_err(_("Volume key does not match the volume.")); + check_signal(&r); + if (r < 0) + goto out; + r = crypt_keyslot_context_init_by_volume_key(cd, key, keysize, &kc); + } else if (ARG_SET(OPT_KEY_FILE_ID) && !tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID))) + r = crypt_keyslot_context_init_by_keyfile(cd, + ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_KEYFILE_SIZE_ID), + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), + &kc); + else if (ARG_SET(OPT_TOKEN_ID_ID) || ARG_SET(OPT_TOKEN_TYPE_ID) || ARG_SET(OPT_TOKEN_ONLY_ID)) { + r = crypt_keyslot_context_init_by_token(cd, + ARG_INT32(OPT_TOKEN_ID_ID), + ARG_STR(OPT_TOKEN_TYPE_ID), + NULL, 0, NULL, &kc); + } else { + r = tools_get_key(_("Enter any existing passphrase: "), + &password, &password_size, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd); + + if (r < 0) + goto out; + + /* Check password before asking for new one */ + r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT, + password, password_size, 0); + check_signal(&r); + tools_passphrase_msg(r); + if (r < 0) + goto out; + tools_keyslot_msg(r, UNLOCKED); + + r = crypt_keyslot_context_init_by_passphrase(cd, password, password_size, &kc); + } + + if (r < 0) + goto out; + + if (new_key_file && !tools_is_stdin(new_key_file)) { + if (ARG_SET(OPT_KEY_FILE_ID) && !strcmp(ARG_STR(OPT_KEY_FILE_ID), new_key_file)) + p_kc_new = kc; + else { + r = crypt_keyslot_context_init_by_keyfile(cd, + new_key_file, + ARG_UINT32(OPT_NEW_KEYFILE_SIZE_ID), + ARG_UINT64(OPT_NEW_KEYFILE_OFFSET_ID), + &kc_new); + p_kc_new = kc_new; + } + } else if (ARG_SET(OPT_NEW_TOKEN_ID_ID)) { + if (ARG_INT32(OPT_NEW_TOKEN_ID_ID) == ARG_INT32(OPT_TOKEN_ID_ID)) + p_kc_new = kc; + else { + r = crypt_keyslot_context_init_by_token(cd, + ARG_INT32(OPT_NEW_TOKEN_ID_ID), + NULL, NULL, 0, NULL, &kc_new); + p_kc_new = kc_new; + } + } else { + r = tools_get_key(_("Enter new passphrase for key slot: "), + &password_new, &password_new_size, + ARG_UINT64(OPT_NEW_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_NEW_KEYFILE_SIZE_ID), new_key_file, + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(1), !ARG_SET(OPT_FORCE_PASSWORD_ID), cd); + + if (r < 0) + goto out; + r = crypt_keyslot_context_init_by_passphrase(cd, password_new, password_new_size, &kc_new); + } + + if (r < 0) + goto out; + + if (!p_kc_new) + p_kc_new = kc_new; + + r = try_keyslot_add(cd, keyslot_old, keyslot_new, kc, p_kc_new, pin, pin_new); + if (r >= 0 || r != -ENOANO) + goto out; + + if (crypt_keyslot_context_get_error(kc) == -ENOANO) { + r = _ask_for_pin(cd, ARG_INT32(OPT_TOKEN_ID_ID), &pin, &pin_size, kc); + if (r < 0) + goto out; + + r = try_keyslot_add(cd, keyslot_old, keyslot_new, kc, p_kc_new, pin, pin_new); + if (r >= 0 || r != -ENOANO) + goto out; + } + + if (crypt_keyslot_context_get_error(p_kc_new) == -ENOANO) { + r = _ask_for_pin(cd, ARG_INT32(OPT_NEW_TOKEN_ID_ID), &pin_new, &pin_size_new, p_kc_new); + if (r < 0) + goto out; + r = try_keyslot_add(cd, keyslot_old, keyslot_new, kc, p_kc_new, pin, pin_new); + } +out: + tools_keyslot_msg(r, CREATED); + crypt_keyslot_context_free(kc); + crypt_keyslot_context_free(kc_new); + crypt_safe_free(password); + crypt_safe_free(password_new); + crypt_safe_free(pin); + crypt_safe_free(pin_new); + crypt_safe_free(key); + crypt_free(cd); + return r; +} + +static int action_luksChangeKey(void) +{ + const char *new_key_file = (action_argc > 1 ? action_argv[1] : NULL); + struct crypt_device *cd = NULL; + char *password = NULL, *password_new = NULL; + size_t password_size = 0, password_new_size = 0; + int r; + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + if ((r = crypt_load(cd, luksType(device_type), NULL))) { + log_err(_("Device %s is not a valid LUKS device."), + uuid_or_device_header(NULL)); + goto out; + } + + r = _set_keyslot_encryption_params(cd); + if (r < 0) + goto out; + + /* Never call pwquality if using null cipher */ + if (crypt_is_cipher_null(crypt_get_cipher(cd))) + ARG_SET_TRUE(OPT_FORCE_PASSWORD_ID); + + r = set_pbkdf_params(cd, crypt_get_type(cd)); + if (r) { + log_err(_("Failed to set pbkdf parameters.")); + goto out; + } + + r = tools_get_key(_("Enter passphrase to be changed: "), + &password, &password_size, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd); + if (r < 0) + goto out; + + /* Check password before asking for new one */ + r = crypt_activate_by_passphrase(cd, NULL, ARG_INT32(OPT_KEY_SLOT_ID), + password, password_size, CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY); + tools_passphrase_msg(r); + check_signal(&r); + if (r < 0) + goto out; + tools_keyslot_msg(r, UNLOCKED); + + r = tools_get_key(_("Enter new passphrase: "), + &password_new, &password_new_size, + ARG_UINT64(OPT_NEW_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_NEW_KEYFILE_SIZE_ID), + new_key_file, + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(1), !ARG_SET(OPT_FORCE_PASSWORD_ID), cd); + if (r < 0) + goto out; + + r = crypt_keyslot_change_by_passphrase(cd, ARG_INT32(OPT_KEY_SLOT_ID), ARG_INT32(OPT_KEY_SLOT_ID), + password, password_size, password_new, password_new_size); + tools_keyslot_msg(r, CREATED); +out: + crypt_safe_free(password); + crypt_safe_free(password_new); + crypt_free(cd); + return r; +} + +static int action_luksConvertKey(void) +{ + struct crypt_device *cd = NULL; + char *password = NULL; + size_t password_size = 0; + int r; + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + if ((r = crypt_load(cd, CRYPT_LUKS2, NULL))) { + log_err(_("Device %s is not a valid LUKS2 device."), + uuid_or_device_header(NULL)); + goto out; + } + + r = _set_keyslot_encryption_params(cd); + if (r < 0) + goto out; + + if (crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)) == CRYPT_SLOT_INACTIVE) { + r = -EINVAL; + log_err(_("Keyslot %d is not active."), ARG_INT32(OPT_KEY_SLOT_ID)); + goto out; + } + + r = set_pbkdf_params(cd, crypt_get_type(cd)); + if (r) { + log_err(_("Failed to set pbkdf parameters.")); + goto out; + } + + r = tools_get_key(_("Enter passphrase for keyslot to be converted: "), + &password, &password_size, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd); + if (r < 0) + goto out; + + r = crypt_keyslot_change_by_passphrase(cd, ARG_INT32(OPT_KEY_SLOT_ID), ARG_INT32(OPT_KEY_SLOT_ID), + password, password_size, password, password_size); + tools_passphrase_msg(r); + tools_keyslot_msg(r, CREATED); +out: + crypt_safe_free(password); + crypt_free(cd); + return r; +} + +static int action_isLuks(void) +{ + struct crypt_device *cd = NULL; + int r; + + /* FIXME: argc > max should be checked for other operations as well */ + if (action_argc > 1) { + log_err(_("Only one device argument for isLuks operation is supported.")); + return -ENODEV; + } + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + crypt_set_log_callback(cd, quiet_log, &log_parms); + r = crypt_load(cd, luksType(device_type), NULL); +out: + crypt_free(cd); + return r; +} + +static int action_luksUUID(void) +{ + struct crypt_device *cd = NULL; + const char *existing_uuid = NULL; + int r; + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + if (!ARG_SET(OPT_BATCH_MODE_ID)) + crypt_set_confirm_callback(cd, yesDialog, _("Operation aborted.\n")); + + if ((r = crypt_load(cd, luksType(device_type), NULL))) + goto out; + + if (ARG_SET(OPT_UUID_ID)) + r = crypt_set_uuid(cd, ARG_STR(OPT_UUID_ID)); + else { + existing_uuid = crypt_get_uuid(cd); + log_std("%s\n", existing_uuid ?: ""); + r = existing_uuid ? 0 : 1; + } +out: + crypt_free(cd); + return r; +} + +static int luksDump_with_volume_key(struct crypt_device *cd) +{ + char *vk = NULL, *password = NULL; + size_t passwordLen = 0; + size_t vk_size; + int r; + + if (!ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog( + _("The header dump with volume key is sensitive information\n" + "that allows access to encrypted partition without a passphrase.\n" + "This dump should be stored encrypted in a safe place."), + NULL)) + return -EPERM; + + vk_size = crypt_get_volume_key_size(cd); + vk = crypt_safe_alloc(vk_size); + if (!vk) + return -ENOMEM; + + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), 0, 0, cd); + if (r < 0) + goto out; + + r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size, + password, passwordLen); + tools_passphrase_msg(r); + check_signal(&r); + if (r < 0) + goto out; + tools_keyslot_msg(r, UNLOCKED); + + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + r = tools_write_mk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), vk, vk_size); + if (r < 0) + goto out; + } + + log_std("LUKS header information for %s\n", crypt_get_device_name(cd)); + log_std("Cipher name: \t%s\n", crypt_get_cipher(cd)); + log_std("Cipher mode: \t%s\n", crypt_get_cipher_mode(cd)); + log_std("Payload offset:\t%d\n", (int)crypt_get_data_offset(cd)); + log_std("UUID: \t%s\n", crypt_get_uuid(cd)); + log_std("MK bits: \t%d\n", (int)vk_size * 8); + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + log_std("Key stored to file %s.\n", ARG_STR(OPT_VOLUME_KEY_FILE_ID)); + goto out; + } + log_std("MK dump:\t"); + crypt_log_hex(NULL, vk, vk_size, " ", 16, "\n\t\t"); + log_std("\n"); +out: + crypt_safe_free(password); + crypt_safe_free(vk); + return r; +} + +static int luksDump_with_unbound_key(struct crypt_device *cd) +{ + crypt_keyslot_info ki; + char *uk = NULL, *password = NULL; + size_t uk_size, passwordLen = 0; + int r; + + ki = crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)); + if (ki != CRYPT_SLOT_UNBOUND) { + log_err(_("Keyslot %d does not contain unbound key."), ARG_INT32(OPT_KEY_SLOT_ID)); + return -EINVAL; + } + + if (!ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog( + _("The header dump with unbound key is sensitive information.\n" + "This dump should be stored encrypted in a safe place."), + NULL)) + return -EPERM; + + r = crypt_keyslot_get_key_size(cd, ARG_INT32(OPT_KEY_SLOT_ID)); + if (r < 0) + return -EINVAL; + uk_size = r; + uk = crypt_safe_alloc(uk_size); + if (!uk) + return -ENOMEM; + + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), 0, 0, cd); + if (r < 0) + goto out; + + r = crypt_volume_key_get(cd, ARG_INT32(OPT_KEY_SLOT_ID), uk, &uk_size, + password, passwordLen); + tools_passphrase_msg(r); + check_signal(&r); + if (r < 0) + goto out; + tools_keyslot_msg(r, UNLOCKED); + + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + r = tools_write_mk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), uk, uk_size); + if (r < 0) + goto out; + } + + log_std("LUKS header information for %s\n", crypt_get_device_name(cd)); + log_std("UUID: \t%s\n", crypt_get_uuid(cd)); + log_std("Keyslot: \t%d\n", ARG_INT32(OPT_KEY_SLOT_ID)); + log_std("Key bits:\t%d\n", (int)uk_size * 8); + if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + log_std("Key stored to file %s.\n", ARG_STR(OPT_VOLUME_KEY_FILE_ID)); + goto out; + } + log_std("Unbound Key:\t"); + crypt_log_hex(NULL, uk, uk_size, " ", 16, "\n\t\t"); + log_std("\n"); +out: + crypt_safe_free(password); + crypt_safe_free(uk); + return r; +} + +static int action_luksDump(void) +{ + struct crypt_device *cd = NULL; + int r; + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + if ((r = crypt_load(cd, luksType(device_type), NULL))) { + log_err(_("Device %s is not a valid LUKS device."), + uuid_or_device_header(NULL)); + goto out; + } + + if (ARG_SET(OPT_DUMP_VOLUME_KEY_ID)) + r = luksDump_with_volume_key(cd); + else if (ARG_SET(OPT_UNBOUND_ID)) + r = luksDump_with_unbound_key(cd); + else if (ARG_SET(OPT_DUMP_JSON_ID)) + r = crypt_dump_json(cd, NULL, 0); + else + r = crypt_dump(cd); +out: + crypt_free(cd); + return r; +} + +static int action_luksSuspend(void) +{ + struct crypt_device *cd = NULL; + int r; + + r = crypt_init_by_name_and_header(&cd, action_argv[0], uuid_or_device(ARG_STR(OPT_HEADER_ID))); + if (!r) { + r = crypt_suspend(cd, action_argv[0]); + if (r == -ENODEV) + log_err(_("%s is not active %s device name."), action_argv[0], "LUKS"); + } + + crypt_free(cd); + return r; +} + +static int action_luksResume(void) +{ + struct crypt_device *cd = NULL; + char *password = NULL; + size_t passwordLen; + int r, tries; + struct crypt_active_device cad; + const char *req_type = luksType(device_type); + + if (req_type && !isLUKS(req_type)) + return -EINVAL; + + if ((r = crypt_init_by_name_and_header(&cd, action_argv[0], uuid_or_device(ARG_STR(OPT_HEADER_ID))))) + return r; + + r = -EINVAL; + if (!isLUKS(crypt_get_type(cd))) { + log_err(_("%s is not active LUKS device name or header is missing."), action_argv[0]); + goto out; + } + + if (req_type && strcmp(req_type, crypt_get_type(cd))) { + log_err(_("%s is not active %s device name."), action_argv[0], req_type); + goto out; + } + + r = crypt_get_active_device(cd, action_argv[0], &cad); + if (r < 0) + goto out; + + if (!(cad.flags & CRYPT_ACTIVATE_SUSPENDED)) { + log_err(_("Volume %s is not suspended."), action_argv[0]); + r = -EINVAL; + goto out; + } + + /* try to resume LUKS2 device by token first */ + r = crypt_resume_by_token_pin(cd, action_argv[0], ARG_STR(OPT_TOKEN_TYPE_ID), + ARG_INT32(OPT_TOKEN_ID_ID), NULL, 0, NULL); + tools_keyslot_msg(r, UNLOCKED); + tools_token_error_msg(r, ARG_STR(OPT_TOKEN_TYPE_ID), ARG_INT32(OPT_TOKEN_ID_ID), false); + + /* Token requires PIN. Ask if there is evident preference for tokens */ + if (r == -ENOANO && (ARG_SET(OPT_TOKEN_ONLY_ID) || ARG_SET(OPT_TOKEN_TYPE_ID) || + ARG_SET(OPT_TOKEN_ID_ID))) + r = _try_token_pin_unlock(cd, ARG_INT32(OPT_TOKEN_ID_ID), action_argv[0], ARG_STR(OPT_TOKEN_TYPE_ID), 0, set_tries_tty(), false); + + if (r >= 0 || quit || ARG_SET(OPT_TOKEN_ONLY_ID)) + goto out; + + tries = set_tries_tty(); + do { + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd); + if (r < 0) + goto out; + + r = crypt_resume_by_passphrase(cd, action_argv[0], ARG_INT32(OPT_KEY_SLOT_ID), + password, passwordLen); + tools_passphrase_msg(r); + check_signal(&r); + tools_keyslot_msg(r, UNLOCKED); + + crypt_safe_free(password); + password = NULL; + } while ((r == -EPERM || r == -ERANGE) && (--tries > 0)); +out: + crypt_safe_free(password); + crypt_free(cd); + return r; +} + +static int action_luksBackup(void) +{ + struct crypt_device *cd = NULL; + int r; + + if (!ARG_SET(OPT_HEADER_BACKUP_FILE_ID)) { + log_err(_("Option --header-backup-file is required.")); + return -EINVAL; + } + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + r = crypt_header_backup(cd, NULL, ARG_STR(OPT_HEADER_BACKUP_FILE_ID)); +out: + crypt_free(cd); + return r; +} + +static int action_luksRestore(void) +{ + struct crypt_device *cd = NULL; + int r = 0; + + if (!ARG_SET(OPT_HEADER_BACKUP_FILE_ID)) { + log_err(_("Option --header-backup-file is required.")); + return -EINVAL; + } + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + if (!ARG_SET(OPT_BATCH_MODE_ID)) + crypt_set_confirm_callback(cd, yesDialog, NULL); + r = crypt_header_restore(cd, NULL, ARG_STR(OPT_HEADER_BACKUP_FILE_ID)); +out: + crypt_free(cd); + return r; +} + +static const char *_get_device_type(void) +{ + const char *type, *name = NULL; + struct crypt_device *cd = NULL; + + if (action_argc > 1) + name = action_argv[1]; + else if (action_argc == 1) + name = action_argv[0]; + + if (crypt_init_by_name_and_header(&cd, name, ARG_STR(OPT_HEADER_ID))) + return NULL; + + type = crypt_get_type(cd); + if (!type) { + crypt_free(cd); + log_err(_("%s is not cryptsetup managed device."), name); + return NULL; + } + + if (!strncmp(type, "LUKS", 4)) + type = "luks"; + else if (!strcmp(type, CRYPT_PLAIN)) + type = "plain"; + else if (!strcmp(type, CRYPT_LOOPAES)) + type = "loopaes"; + else { + log_err(_("Refresh is not supported for device type %s"), type); + type = NULL; + } + + crypt_free(cd); + + return type; +} + +static int action_open(void) +{ + int r = -EINVAL; + + if (ARG_SET(OPT_REFRESH_ID) && !device_type) + /* read device type from active mapping */ + device_type = _get_device_type(); + + if (!device_type) + return -EINVAL; + + if (!strcmp(device_type, "luks") || + !strcmp(device_type, "luks1") || + !strcmp(device_type, "luks2")) { + if (action_argc < 2 && (!ARG_SET(OPT_TEST_PASSPHRASE_ID) && !ARG_SET(OPT_REFRESH_ID))) + goto out; + return action_open_luks(); + } else if (!strcmp(device_type, "plain")) { + if (action_argc < 2 && !ARG_SET(OPT_REFRESH_ID)) + goto out; + return action_open_plain(); + } else if (!strcmp(device_type, "loopaes")) { + if (action_argc < 2 && !ARG_SET(OPT_REFRESH_ID)) + goto out; + return action_open_loopaes(); + } else if (!strcmp(device_type, "tcrypt")) { + if (action_argc < 2 && !ARG_SET(OPT_TEST_PASSPHRASE_ID)) + goto out; + return action_open_tcrypt(); + } else if (!strcmp(device_type, "bitlk")) { + if (action_argc < 2 && !ARG_SET(OPT_TEST_PASSPHRASE_ID)) + goto out; + return action_open_bitlk(); + } else if (!strcmp(device_type, "fvault2")) { + if (action_argc < 2 && !ARG_SET(OPT_TEST_PASSPHRASE_ID)) + goto out; + return action_open_fvault2(); + } else + r = -ENOENT; +out: + if (r == -ENOENT) + log_err(_("Unrecognized metadata device type %s."), device_type); + else + log_err(_("Command requires device and mapped name as arguments.")); + + return r; +} + +static int action_luksErase(void) +{ + struct crypt_device *cd = NULL; + crypt_keyslot_info ki; + char *msg = NULL; + int i, max, r; + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + goto out; + + if ((r = crypt_load(cd, luksType(device_type), NULL))) { + log_err(_("Device %s is not a valid LUKS device."), + uuid_or_device_header(NULL)); + goto out; + } + + if(asprintf(&msg, _("This operation will erase all keyslots on device %s.\n" + "Device will become unusable after this operation."), + uuid_or_device_header(NULL)) == -1) { + r = -ENOMEM; + goto out; + } + + if (!ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog(msg, _("Operation aborted, keyslots were NOT wiped.\n"))) { + r = -EPERM; + goto out; + } + + /* Safety check */ + max = crypt_keyslot_max(crypt_get_type(cd)); + if (max <= 0) { + r = -EINVAL; + goto out; + } + + for (i = 0; i < max; i++) { + ki = crypt_keyslot_status(cd, i); + if (ki == CRYPT_SLOT_ACTIVE || ki == CRYPT_SLOT_ACTIVE_LAST) { + r = crypt_keyslot_destroy(cd, i); + if (r < 0) + goto out; + tools_keyslot_msg(i, REMOVED); + } + } +out: + free(msg); + crypt_free(cd); + return r; +} + +static int action_luksConvert(void) +{ + struct crypt_device *cd = NULL; + char *msg = NULL; + const char *to_type, *from_type; + int r; + + if (!strcmp(device_type, "luks2")) { + to_type = CRYPT_LUKS2; + } else if (!strcmp(device_type, "luks1")) { + to_type = CRYPT_LUKS1; + } else { + log_err(_("Invalid LUKS type, only luks1 and luks2 are supported.")); + return -EINVAL; + } + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + return r; + + if ((r = crypt_load(cd, CRYPT_LUKS, NULL)) || + !(from_type = crypt_get_type(cd))) { + log_err(_("Device %s is not a valid LUKS device."), + uuid_or_device_header(NULL)); + crypt_free(cd); + return r; + } + + if (!strcmp(from_type, to_type)) { + log_err(_("Device is already %s type."), to_type); + crypt_free(cd); + return -EINVAL; + } + + r = 0; + if (!ARG_SET(OPT_BATCH_MODE_ID)) { + if (asprintf(&msg, _("This operation will convert %s to %s format.\n"), + uuid_or_device_header(NULL), to_type) == -1) + r = -ENOMEM; + else if (!yesDialog(msg, _("Operation aborted, device was NOT converted.\n"))) + r = -EPERM; + } + + r = r ?: crypt_convert(cd, to_type, NULL); + + free(msg); + crypt_free(cd); + return r; +} + +static int _config_priority(struct crypt_device *cd) +{ + crypt_keyslot_info cs; + crypt_keyslot_priority priority = CRYPT_SLOT_PRIORITY_INVALID; + + if (!strcmp("normal", ARG_STR(OPT_PRIORITY_ID))) + priority = CRYPT_SLOT_PRIORITY_NORMAL; + else if (!strcmp("prefer", ARG_STR(OPT_PRIORITY_ID))) + priority = CRYPT_SLOT_PRIORITY_PREFER; + else if (!strcmp("ignore", ARG_STR(OPT_PRIORITY_ID))) + priority = CRYPT_SLOT_PRIORITY_IGNORE; + + cs = crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)); + if (cs != CRYPT_SLOT_INVALID) + return crypt_keyslot_set_priority(cd, ARG_INT32(OPT_KEY_SLOT_ID), priority); + return -EINVAL; +} + +static int _config_labels(struct crypt_device *cd) +{ + return crypt_set_label(cd, ARG_STR(OPT_LABEL_ID), ARG_STR(OPT_SUBSYSTEM_ID)); +} + +static int action_luksConfig(void) +{ + struct crypt_device *cd = NULL; + int r; + + if (!ARG_SET(OPT_PRIORITY_ID) && !ARG_SET(OPT_LABEL_ID) && !ARG_SET(OPT_SUBSYSTEM_ID)) { + log_err(_("Option --priority, --label or --subsystem is missing.")); + return -EINVAL; + } + + if ((r = crypt_init(&cd, uuid_or_device_header(NULL)))) + return r; + + if ((r = crypt_load(cd, CRYPT_LUKS2, NULL))) { + log_err(_("Device %s is not a valid LUKS2 device."), + uuid_or_device_header(NULL)); + goto out; + } + + if (ARG_SET(OPT_PRIORITY_ID) && (r = _config_priority(cd))) + goto out; + + if ((ARG_SET(OPT_LABEL_ID) || ARG_SET(OPT_SUBSYSTEM_ID)) && (r = _config_labels(cd))) + goto out; +out: + crypt_free(cd); + return r; +} + +static int _token_add(struct crypt_device *cd) +{ + int r, token; + crypt_token_info token_info; + const struct crypt_token_params_luks2_keyring params = { + .key_description = ARG_STR(OPT_KEY_DESCRIPTION_ID) + }; + + if (ARG_INT32(OPT_TOKEN_ID_ID) != CRYPT_ANY_TOKEN) { + token_info = crypt_token_status(cd, ARG_INT32(OPT_TOKEN_ID_ID), NULL); + if (token_info < CRYPT_TOKEN_INACTIVE) { + log_err(_("Token %d is invalid."), ARG_INT32(OPT_TOKEN_ID_ID)); + return -EINVAL; + } else if (token_info > CRYPT_TOKEN_INACTIVE && !ARG_SET(OPT_TOKEN_REPLACE_ID)) { + log_err(_("Token %d in use."), ARG_INT32(OPT_TOKEN_ID_ID)); + return -EINVAL; + } + } + + if (crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)) == CRYPT_SLOT_INACTIVE) { + log_err(_("Keyslot %d is not active."), ARG_INT32(OPT_KEY_SLOT_ID)); + return -EINVAL; + } + + r = crypt_token_luks2_keyring_set(cd, ARG_INT32(OPT_TOKEN_ID_ID), ¶ms); + if (r < 0) { + log_err(_("Failed to add luks2-keyring token %d."), ARG_INT32(OPT_TOKEN_ID_ID)); + return r; + } + + token = r; + + if (ARG_SET(OPT_UNBOUND_ID)) + return token; + + r = crypt_token_assign_keyslot(cd, token, ARG_INT32(OPT_KEY_SLOT_ID)); + if (r < 0) { + log_err(_("Failed to assign token %d to keyslot %d."), token, ARG_INT32(OPT_KEY_SLOT_ID)); + (void) crypt_token_json_set(cd, token, NULL); + return r; + } + + return token; +} + +static int _token_remove(struct crypt_device *cd) +{ + crypt_token_info token_info; + + token_info = crypt_token_status(cd, ARG_INT32(OPT_TOKEN_ID_ID), NULL); + if (token_info < CRYPT_TOKEN_INACTIVE) { + log_err(_("Token %d is invalid."), ARG_INT32(OPT_TOKEN_ID_ID)); + return -EINVAL; + } else if (token_info == CRYPT_TOKEN_INACTIVE) { + log_err(_("Token %d is not in use."), ARG_INT32(OPT_TOKEN_ID_ID)); + return -EINVAL; + } + + return crypt_token_json_set(cd, ARG_INT32(OPT_TOKEN_ID_ID), NULL); +} + +static int _token_import(struct crypt_device *cd) +{ + char *json; + size_t json_length; + crypt_token_info token_info; + int r, token; + + if (ARG_INT32(OPT_TOKEN_ID_ID) != CRYPT_ANY_TOKEN) { + token_info = crypt_token_status(cd, ARG_INT32(OPT_TOKEN_ID_ID), NULL); + if (token_info < CRYPT_TOKEN_INACTIVE) { + log_err(_("Token %d is invalid."), ARG_INT32(OPT_TOKEN_ID_ID)); + return -EINVAL; + } else if (token_info > CRYPT_TOKEN_INACTIVE && !ARG_SET(OPT_TOKEN_REPLACE_ID)) { + log_err(_("Token %d in use."), ARG_INT32(OPT_TOKEN_ID_ID)); + return -EINVAL; + } + } + + if (crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)) == CRYPT_SLOT_INACTIVE) { + log_err(_("Keyslot %d is not active."), ARG_INT32(OPT_KEY_SLOT_ID)); + return -EINVAL; + } + + r = tools_read_json_file(ARG_STR(OPT_JSON_FILE_ID), &json, &json_length, ARG_SET(OPT_BATCH_MODE_ID)); + if (r) + return r; + + r = crypt_token_json_set(cd, ARG_INT32(OPT_TOKEN_ID_ID), json); + free(json); + if (r < 0) { + log_err(_("Failed to import token from file.")); + return r; + } + + token = r; + + if (ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT) { + r = crypt_token_assign_keyslot(cd, token, ARG_INT32(OPT_KEY_SLOT_ID)); + if (r < 0) { + log_err(_("Failed to assign token %d to keyslot %d."), token, ARG_INT32(OPT_KEY_SLOT_ID)); + (void) crypt_token_json_set(cd, token, NULL); + return r; + } + } + + return token; +} + +static int _token_export(struct crypt_device *cd) +{ + const char *json; + int r; + + r = crypt_token_json_get(cd, ARG_INT32(OPT_TOKEN_ID_ID), &json); + if (r < 0) { + log_err(_("Failed to get token %d for export."), ARG_INT32(OPT_TOKEN_ID_ID)); + return r; + } + + return tools_write_json_file(ARG_STR(OPT_JSON_FILE_ID), json); +} + +static int _token_unassign(struct crypt_device *cd) +{ + int r = crypt_token_is_assigned(cd, ARG_INT32(OPT_TOKEN_ID_ID), ARG_INT32(OPT_KEY_SLOT_ID)); + + if (r < 0) { + if (r == -ENOENT) + log_err(_("Token %d is not assigned to keyslot %d."), ARG_INT32(OPT_TOKEN_ID_ID), ARG_INT32(OPT_KEY_SLOT_ID)); + else + log_err(_("Failed to unassign token %d from keyslot %d."), ARG_INT32(OPT_TOKEN_ID_ID), ARG_INT32(OPT_KEY_SLOT_ID)); + + return r; + } + + r = crypt_token_unassign_keyslot(cd, ARG_INT32(OPT_TOKEN_ID_ID), ARG_INT32(OPT_KEY_SLOT_ID)); + if (r < 0) + log_err(_("Failed to unassign token %d from keyslot %d."), ARG_INT32(OPT_TOKEN_ID_ID), ARG_INT32(OPT_KEY_SLOT_ID)); + + return r; +} + +static int action_token(void) +{ + int r; + struct crypt_device *cd = NULL; + + if ((r = crypt_init(&cd, uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[1])))) + return r; + + if ((r = crypt_load(cd, CRYPT_LUKS2, NULL))) { + log_err(_("Device %s is not a valid LUKS2 device."), + uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[1])); + crypt_free(cd); + return r; + } + + r = -EINVAL; + + if (!strcmp(action_argv[0], "add")) { + r = _token_add(cd); /* adds only luks2-keyring type */ + tools_token_msg(r, CREATED); + } else if (!strcmp(action_argv[0], "remove")) { + r = _token_remove(cd); + tools_token_msg(r, REMOVED); + } else if (!strcmp(action_argv[0], "import")) { + r = _token_import(cd); + tools_token_msg(r, CREATED); + } else if (!strcmp(action_argv[0], "export")) + r = _token_export(cd); + else if (!strcmp(action_argv[0], "unassign")) + r = _token_unassign(cd); + + crypt_free(cd); + + return r; +} + +static int action_reencrypt(void) +{ + return reencrypt(action_argc, action_argv); +} + +static const char *verify_tcryptdump(void) +{ + if ((ARG_SET(OPT_TCRYPT_HIDDEN_ID) || ARG_SET(OPT_TCRYPT_SYSTEM_ID) || ARG_SET(OPT_TCRYPT_BACKUP_ID)) && (!device_type || strcmp(device_type, "tcrypt"))) + return _("Option --tcrypt-hidden, --tcrypt-system or --tcrypt-backup is supported only for TCRYPT device."); + + if ((ARG_SET(OPT_VERACRYPT_ID) || ARG_SET(OPT_DISABLE_VERACRYPT_ID)) && (!device_type || strcmp(device_type, "tcrypt"))) + return _("Option --veracrypt or --disable-veracrypt is supported only for TCRYPT device type."); + + if (ARG_SET(OPT_VERACRYPT_PIM_ID) && ARG_SET(OPT_DISABLE_VERACRYPT_ID)) + return _("Option --veracrypt-pim is supported only for VeraCrypt compatible devices."); + + if (ARG_SET(OPT_VERACRYPT_QUERY_PIM_ID)) { + if (ARG_SET(OPT_DISABLE_VERACRYPT_ID)) + return _("Option --veracrypt-query-pim is supported only for VeraCrypt compatible devices."); + else if (ARG_SET(OPT_VERACRYPT_PIM_ID)) + return _("The options --veracrypt-pim and --veracrypt-query-pim are mutually exclusive."); + } + + return NULL; +} + +static const char * verify_open(void) +{ + if (ARG_SET(OPT_PERSISTENT_ID) && ARG_SET(OPT_TEST_PASSPHRASE_ID)) + return _("Option --persistent is not allowed with --test-passphrase."); + + if (ARG_SET(OPT_REFRESH_ID) && ARG_SET(OPT_TEST_PASSPHRASE_ID)) + return _("Options --refresh and --test-passphrase are mutually exclusive."); + + if (ARG_SET(OPT_SHARED_ID) && strcmp_or_null(device_type, "plain")) + return _("Option --shared is allowed only for open of plain device."); + + if (ARG_SET(OPT_SKIP_ID) && strcmp_or_null(device_type, "plain") && strcmp(device_type, "loopaes")) + return _("Option --skip is supported only for open of plain and loopaes devices."); + + if (ARG_SET(OPT_OFFSET_ID) && strcmp_or_null(device_type, "plain") && strcmp(device_type, "loopaes")) + return _("Option --offset with open action is only supported for plain and loopaes devices."); + + if (ARG_SET(OPT_TCRYPT_HIDDEN_ID) && ARG_SET(OPT_ALLOW_DISCARDS_ID)) + return _("Option --tcrypt-hidden cannot be combined with --allow-discards."); + + if (ARG_SET(OPT_SECTOR_SIZE_ID) && + (!device_type || strcmp(device_type, "plain"))) + return _("Sector size option with open action is supported only for plain devices."); + + if (ARG_SET(OPT_IV_LARGE_SECTORS_ID) && (!device_type || strcmp(device_type, "plain") || + ARG_UINT32(OPT_SECTOR_SIZE_ID) <= SECTOR_SIZE)) + return _("Large IV sectors option is supported only for opening plain type device with sector size larger than 512 bytes."); + + if (ARG_SET(OPT_TEST_PASSPHRASE_ID) && (!device_type || + (strncmp(device_type, "luks", 4) && strcmp(device_type, "tcrypt") && + strcmp(device_type, "bitlk") && strcmp(device_type, "fvault2")))) + return _("Option --test-passphrase is allowed only for open of LUKS, TCRYPT, BITLK and FVAULT2 devices."); + + if (ARG_SET(OPT_DEVICE_SIZE_ID) && ARG_SET(OPT_SIZE_ID)) + return _("Options --device-size and --size cannot be combined."); + + if (ARG_SET(OPT_UNBOUND_ID) && device_type && strncmp(device_type, "luks", 4)) + return _("Option --unbound is allowed only for open of luks device."); + + if (ARG_SET(OPT_UNBOUND_ID) && !ARG_SET(OPT_TEST_PASSPHRASE_ID)) + return _("Option --unbound cannot be used without --test-passphrase."); + + /* "open --type tcrypt" and "tcryptDump" checks are identical */ + return verify_tcryptdump(); +} + +static const char *verify_close(void) +{ + if (ARG_SET(OPT_CANCEL_DEFERRED_ID) && ARG_SET(OPT_DEFERRED_ID)) + return _("Options --cancel-deferred and --deferred cannot be used at the same time."); + + return NULL; +} + +static const char *verify_resize(void) +{ + if (ARG_SET(OPT_DEVICE_SIZE_ID) && ARG_SET(OPT_SIZE_ID)) + return _("Options --device-size and --size cannot be combined."); + + return NULL; +} + +static const char *verify_reencrypt(void) +{ + if (ARG_SET(OPT_REDUCE_DEVICE_SIZE_ID) && ARG_SET(OPT_DEVICE_SIZE_ID)) + return _("Options --reduce-device-size and --data-size cannot be combined."); + + if (isLUKS1(luksType(device_type)) && ARG_SET(OPT_ACTIVE_NAME_ID)) + return _("Option --active-name can be set only for LUKS2 device."); + + if (ARG_SET(OPT_ACTIVE_NAME_ID) && ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID)) + return _("Options --active-name and --force-offline-reencrypt cannot be combined."); + + return NULL; +} + +static const char *verify_config(void) +{ + if (ARG_SET(OPT_PRIORITY_ID) && ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT) + return _("Keyslot specification is required."); + + return NULL; +} + +static const char *verify_format(void) +{ + if (ARG_SET(OPT_ALIGN_PAYLOAD_ID) && ARG_SET(OPT_OFFSET_ID)) + return _("Options --align-payload and --offset cannot be combined."); + + if (ARG_SET(OPT_INTEGRITY_NO_WIPE_ID) && !ARG_SET(OPT_INTEGRITY_ID)) + return _("Option --integrity-no-wipe can be used only for format action with integrity extension."); + + if (ARG_SET(OPT_USE_RANDOM_ID) && ARG_SET(OPT_USE_URANDOM_ID)) + return _("Only one of --use-[u]random options is allowed."); + + return NULL; +} + +static const char *verify_addkey(void) +{ + if (ARG_SET(OPT_UNBOUND_ID) && !ARG_UINT32(OPT_KEY_SIZE_ID)) + return _("Key size is required with --unbound option."); + + return NULL; +} + +static const char *verify_luksDump(void) +{ + if (ARG_SET(OPT_UNBOUND_ID) && ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT) + return _("Keyslot specification is required."); + + return NULL; +} + +static const char *verify_token(void) +{ + if (strcmp(action_argv[0], "add") && + strcmp(action_argv[0], "remove") && + strcmp(action_argv[0], "import") && + strcmp(action_argv[0], "export") && + strcmp(action_argv[0], "unassign")) + return _("Invalid token action."); + + if (!ARG_SET(OPT_KEY_DESCRIPTION_ID) && !strcmp(action_argv[0], "add")) + return _("--key-description parameter is mandatory for token add action."); + + if (ARG_INT32(OPT_TOKEN_ID_ID) == CRYPT_ANY_TOKEN && + (!strcmp(action_argv[0], "remove") || !strcmp(action_argv[0], "export"))) + return _("Action requires specific token. Use --token-id parameter."); + + if (ARG_SET(OPT_UNBOUND_ID)) { + if (strcmp(action_argv[0], "add")) + return _("Option --unbound is valid only with token add action."); + if (ARG_SET(OPT_KEY_SLOT_ID)) + return _("Options --key-slot and --unbound cannot be combined."); + } + + if (!strcmp(action_argv[0], "unassign")) { + if (!ARG_SET(OPT_KEY_SLOT_ID)) + return _("Action requires specific keyslot. Use --key-slot parameter."); + if (!ARG_SET(OPT_TOKEN_ID_ID)) + return _("Action requires specific token. Use --token-id parameter."); + } + + return NULL; +} + +static struct action_type { + const char *type; + int (*handler)(void); + const char *(*verify)(void); + int required_action_argc; + const char *arg_desc; + const char *desc; +} action_types[] = { + { OPEN_ACTION, action_open, verify_open, 1, N_("<device> [--type <type>] [<name>]"),N_("open device as <name>") }, + { CLOSE_ACTION, action_close, verify_close, 1, N_("<name>"), N_("close device (remove mapping)") }, + { RESIZE_ACTION, action_resize, verify_resize, 1, N_("<name>"), N_("resize active device") }, + { STATUS_ACTION, action_status, NULL, 1, N_("<name>"), N_("show device status") }, + { BENCHMARK_ACTION, action_benchmark, NULL, 0, N_("[--cipher <cipher>]"), N_("benchmark cipher") }, + { REPAIR_ACTION, action_luksRepair, NULL, 1, N_("<device>"), N_("try to repair on-disk metadata") }, + { REENCRYPT_ACTION, action_reencrypt, verify_reencrypt, 0, N_("<device>"), N_("reencrypt LUKS2 device") }, + { ERASE_ACTION, action_luksErase, NULL, 1, N_("<device>"), N_("erase all keyslots (remove encryption key)") }, + { CONVERT_ACTION, action_luksConvert, NULL, 1, N_("<device>"), N_("convert LUKS from/to LUKS2 format") }, + { CONFIG_ACTION, action_luksConfig, verify_config, 1, N_("<device>"), N_("set permanent configuration options for LUKS2") }, + { FORMAT_ACTION, action_luksFormat, verify_format, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") }, + { ADDKEY_ACTION, action_luksAddKey, verify_addkey, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") }, + { REMOVEKEY_ACTION, action_luksRemoveKey, NULL, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") }, + { CHANGEKEY_ACTION, action_luksChangeKey, NULL, 1, N_("<device> [<key file>]"), N_("changes supplied key or key file of LUKS device") }, + { CONVERTKEY_ACTION, action_luksConvertKey, NULL, 1, N_("<device> [<key file>]"), N_("converts a key to new pbkdf parameters") }, + { KILLKEY_ACTION, action_luksKillSlot, NULL, 2, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") }, + { UUID_ACTION, action_luksUUID, NULL, 1, N_("<device>"), N_("print UUID of LUKS device") }, + { ISLUKS_ACTION, action_isLuks, NULL, 1, N_("<device>"), N_("tests <device> for LUKS partition header") }, + { LUKSDUMP_ACTION, action_luksDump, verify_luksDump, 1, N_("<device>"), N_("dump LUKS partition information") }, + { TCRYPTDUMP_ACTION, action_tcryptDump, verify_tcryptdump, 1, N_("<device>"), N_("dump TCRYPT device information") }, + { BITLKDUMP_ACTION, action_bitlkDump, NULL, 1, N_("<device>"), N_("dump BITLK device information") }, + { FVAULT2DUMP_ACTION, action_fvault2Dump, NULL, 1, N_("<device>"), N_("dump FVAULT2 device information") }, + { SUSPEND_ACTION, action_luksSuspend, NULL, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen)") }, + { RESUME_ACTION, action_luksResume, NULL, 1, N_("<device>"), N_("Resume suspended LUKS device") }, + { HEADERBACKUP_ACTION, action_luksBackup, NULL, 1, N_("<device>"), N_("Backup LUKS device header and keyslots") }, + { HEADERRESTORE_ACTION, action_luksRestore, NULL, 1, N_("<device>"), N_("Restore LUKS device header and keyslots") }, + { TOKEN_ACTION, action_token, verify_token, 2, N_("<add|remove|import|export> <device>"), N_("Manipulate LUKS2 tokens") }, + {} +}; + +static void help(poptContext popt_context, + enum poptCallbackReason reason __attribute__((unused)), + struct poptOption *key, + const char *arg __attribute__((unused)), + void *data __attribute__((unused))) +{ + const char *path; + + if (key->shortName == '?') { + struct action_type *action; + const struct crypt_pbkdf_type *pbkdf_luks1, *pbkdf_luks2; + + tools_package_version(PACKAGE_NAME, true); + poptPrintHelp(popt_context, stdout, 0); + + log_std(_("\n" + "<action> is one of:\n")); + + for(action = action_types; action->type; action++) + log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc)); + + log_std(_("\n" + "You can also use old <action> syntax aliases:\n" + "\topen: create (plainOpen), luksOpen, loopaesOpen, tcryptOpen, bitlkOpen, fvault2Open\n" + "\tclose: remove (plainClose), luksClose, loopaesClose, tcryptClose, bitlkClose, fvault2Close\n")); + log_std(_("\n" + "<name> is the device to create under %s\n" + "<device> is the encrypted device\n" + "<key slot> is the LUKS key slot number to modify\n" + "<key file> optional key file for the new key for luksAddKey action\n"), + crypt_get_dir()); + + log_std(_("\nDefault compiled-in metadata format is %s (for luksFormat action).\n"), + crypt_get_default_type()); + + path = crypt_token_external_path(); + if (path) { + log_std(_("\nLUKS2 external token plugin support is %s.\n"), _("compiled-in")); + log_std(_("LUKS2 external token plugin path: %s.\n"), path); + } else + log_std(_("\nLUKS2 external token plugin support is %s.\n"), _("disabled")); + + pbkdf_luks1 = crypt_get_pbkdf_default(CRYPT_LUKS1); + pbkdf_luks2 = crypt_get_pbkdf_default(CRYPT_LUKS2); + log_std(_("\nDefault compiled-in key and passphrase parameters:\n" + "\tMaximum keyfile size: %dkB, " + "Maximum interactive passphrase length %d (characters)\n" + "Default PBKDF for LUKS1: %s, iteration time: %d (ms)\n" + "Default PBKDF for LUKS2: %s\n" + "\tIteration time: %d, Memory required: %dkB, Parallel threads: %d\n"), + DEFAULT_KEYFILE_SIZE_MAXKB, DEFAULT_PASSPHRASE_SIZE_MAX, + pbkdf_luks1->type, pbkdf_luks1->time_ms, + pbkdf_luks2->type, pbkdf_luks2->time_ms, pbkdf_luks2->max_memory_kb, + pbkdf_luks2->parallel_threads); + + log_std(_("\nDefault compiled-in device cipher parameters:\n" + "\tloop-AES: %s, Key %d bits\n" + "\tplain: %s, Key: %d bits, Password hashing: %s\n" + "\tLUKS: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"), + DEFAULT_LOOPAES_CIPHER, DEFAULT_LOOPAES_KEYBITS, + DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH, + DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH, + DEFAULT_RNG); +#if defined(ENABLE_LUKS_ADJUST_XTS_KEYSIZE) && DEFAULT_LUKS1_KEYBITS != 512 + log_std(_("\tLUKS: Default keysize with XTS mode (two internal keys) will be doubled.\n")); +#endif + tools_cleanup(); + poptFreeContext(popt_context); + exit(EXIT_SUCCESS); + } else if (key->shortName == 'V') { + tools_package_version(PACKAGE_NAME, true); + tools_cleanup(); + poptFreeContext(popt_context); + exit(EXIT_SUCCESS); + } else + usage(popt_context, EXIT_SUCCESS, NULL, NULL); +} + +static void help_args(struct action_type *action, poptContext popt_context) +{ + char buf[128]; + + if (snprintf(buf, sizeof(buf), _("%s: requires %s as arguments"), action->type, action->arg_desc) < 0) + buf[0] = '\0'; + usage(popt_context, EXIT_FAILURE, buf, poptGetInvocationName(popt_context)); +} + +static int run_action(struct action_type *action) +{ + int r; + + log_dbg("Running command %s.", action->type); + + set_int_handler(0); + r = action->handler(); + + /* Some functions returns keyslot # */ + if (r > 0) + r = 0; + check_signal(&r); + + show_status(r); + return translate_errno(r); +} + +static const char *verify_action(struct action_type *action) +{ + log_dbg("Verifying parameters for command %s.", action->type); + + return action->verify ? action->verify() : NULL; +} + +static bool needs_size_conversion(unsigned arg_id) +{ + return (arg_id == OPT_DEVICE_SIZE_ID || arg_id == OPT_HOTZONE_SIZE_ID || + arg_id == OPT_LUKS2_KEYSLOTS_SIZE_ID || arg_id == OPT_LUKS2_METADATA_SIZE_ID || + arg_id == OPT_REDUCE_DEVICE_SIZE_ID); +} + +static void check_key_slot_value(poptContext popt_context) +{ + if (ARG_INT32(OPT_KEY_SLOT_ID) < 0) + usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."), + poptGetInvocationName(popt_context)); +} + +static void basic_options_cb(poptContext popt_context, + enum poptCallbackReason reason __attribute__((unused)), + struct poptOption *key, + const char *arg, + void *data __attribute__((unused))) +{ + tools_parse_arg_value(popt_context, tool_core_args[key->val].type, tool_core_args + key->val, arg, key->val, needs_size_conversion); + + /* special cases additional handling */ + switch (key->val) { + case OPT_DEBUG_JSON_ID: + /* fall through */ + case OPT_DEBUG_ID: + log_parms.debug = true; + /* fall through */ + case OPT_VERBOSE_ID: + log_parms.verbose = true; + break; + case OPT_DEVICE_SIZE_ID: + if (ARG_UINT64(OPT_DEVICE_SIZE_ID) == 0) + usage(popt_context, EXIT_FAILURE, poptStrerror(POPT_ERROR_BADNUMBER), + poptGetInvocationName(popt_context)); + if (ARG_UINT64(OPT_DEVICE_SIZE_ID) % SECTOR_SIZE) + usage(popt_context, EXIT_FAILURE, _("Device size must be multiple of 512 bytes sector."), + poptGetInvocationName(popt_context)); + break; + case OPT_HOTZONE_SIZE_ID: + if (ARG_UINT64(OPT_HOTZONE_SIZE_ID) == 0) + usage(popt_context, EXIT_FAILURE, _("Invalid max reencryption hotzone size specification."), + poptGetInvocationName(popt_context)); + break; + case OPT_KEY_FILE_ID: + if (tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID))) { + free(keyfile_stdin); + keyfile_stdin = strdup(ARG_STR(OPT_KEY_FILE_ID)); + } else if (keyfiles_count < MAX_KEYFILES) + keyfiles[keyfiles_count++] = strdup(ARG_STR(OPT_KEY_FILE_ID)); + total_keyfiles++; + break; + case OPT_KEY_SIZE_ID: + if (ARG_UINT32(OPT_KEY_SIZE_ID) % 8) + usage(popt_context, EXIT_FAILURE, + _("Key size must be a multiple of 8 bits"), + poptGetInvocationName(popt_context)); + break; + case OPT_KEY_SLOT_ID: + check_key_slot_value(popt_context); + break; + case OPT_KEYSLOT_KEY_SIZE_ID: + if (ARG_UINT32(OPT_KEYSLOT_KEY_SIZE_ID) == 0) + usage(popt_context, EXIT_FAILURE, poptStrerror(POPT_ERROR_BADNUMBER), + poptGetInvocationName(popt_context)); + if (ARG_UINT32(OPT_KEYSLOT_KEY_SIZE_ID) % 8) + usage(popt_context, EXIT_FAILURE, + _("Key size must be a multiple of 8 bits"), + poptGetInvocationName(popt_context)); + break; + case OPT_REDUCE_DEVICE_SIZE_ID: + if (ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID) > 1024 * 1024 * 1024) + usage(popt_context, EXIT_FAILURE, _("Maximum device reduce size is 1 GiB."), + poptGetInvocationName(popt_context)); + if (ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID) % SECTOR_SIZE) + usage(popt_context, EXIT_FAILURE, _("Reduce size must be multiple of 512 bytes sector."), + poptGetInvocationName(popt_context)); + data_shift = -(int64_t)ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID); + break; + case OPT_SECTOR_SIZE_ID: + if (ARG_UINT32(OPT_SECTOR_SIZE_ID) < SECTOR_SIZE || + ARG_UINT32(OPT_SECTOR_SIZE_ID) > MAX_SECTOR_SIZE || + (ARG_UINT32(OPT_SECTOR_SIZE_ID) & (ARG_UINT32(OPT_SECTOR_SIZE_ID) - 1))) + usage(popt_context, EXIT_FAILURE, + _("Unsupported encryption sector size."), + poptGetInvocationName(popt_context)); + break; + case OPT_PRIORITY_ID: + if (strcmp(ARG_STR(OPT_PRIORITY_ID), "normal") && + strcmp(ARG_STR(OPT_PRIORITY_ID), "prefer") && + strcmp(ARG_STR(OPT_PRIORITY_ID), "ignore")) + usage(popt_context, EXIT_FAILURE, + _("Option --priority can be only ignore/normal/prefer."), + poptGetInvocationName(popt_context)); + break; + } +} + +static void cryptsetup_init_arg_aliases(void) +{ + unsigned i; + + for (i = 1; i < ARRAY_SIZE(tool_core_args); i++) + if (tool_core_args[i].type == CRYPT_ARG_ALIAS) + ARG_INIT_ALIAS(i); +} + +int main(int argc, const char **argv) +{ + static struct poptOption popt_help_options[] = { + { NULL, '\0', POPT_ARG_CALLBACK, help, 0, NULL, NULL }, + { "help", '?', POPT_ARG_NONE, NULL, 0, N_("Show this help message"), NULL }, + { "usage", '\0', POPT_ARG_NONE, NULL, 0, N_("Display brief usage"), NULL }, + { "version",'V', POPT_ARG_NONE, NULL, 0, N_("Print package version"), NULL }, + POPT_TABLEEND + }; + static struct poptOption popt_basic_options[] = { + { NULL, '\0', POPT_ARG_CALLBACK, basic_options_cb, 0, NULL, NULL }, +#define ARG(A, B, C, D, E, F, G, H) { A, B, C, NULL, A ## _ID, D, E }, +#include "cryptsetup_arg_list.h" +#undef ARG + POPT_TABLEEND + }; + static struct poptOption popt_options[] = { + { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL }, + { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_basic_options, 0, NULL, NULL }, + POPT_TABLEEND + }; + poptContext popt_context; + struct action_type *action; + const char *aname, *error_message; + int r; + + /* initialize aliases */ + cryptsetup_init_arg_aliases(); + + crypt_set_log_callback(NULL, tool_log, &log_parms); + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0); + poptSetOtherOptionHelp(popt_context, + _("[OPTION...] <action> <action-specific>")); + + while ((r = poptGetNextOpt(popt_context)) > 0) {} + + if (r < -1) + usage(popt_context, EXIT_FAILURE, poptStrerror(r), + poptBadOption(popt_context, POPT_BADOPTION_NOALIAS)); + + if (!(aname = poptGetArg(popt_context))) + usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."), + poptGetInvocationName(popt_context)); + + action_argc = 0; + action_argv = poptGetArgs(popt_context); + /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */ + if(!action_argv) + action_argv = null_action_argv; + + /* Count args, somewhat unnice, change? */ + while(action_argv[action_argc] != NULL) + action_argc++; + + /* Handle aliases */ + if (!strcmp(aname, "create")) { + /* create command had historically switched arguments */ + if (action_argv[0] && action_argv[1]) { + const char *tmp = action_argv[0]; + action_argv[0] = action_argv[1]; + action_argv[1] = tmp; + } + aname = OPEN_ACTION; + device_type = "plain"; + } else if (!strcmp(aname, "plainOpen")) { + aname = OPEN_ACTION; + device_type = "plain"; + } else if (!strcmp(aname, "luksOpen")) { + aname = OPEN_ACTION; + device_type = "luks"; + } else if (!strcmp(aname, "loopaesOpen")) { + aname = OPEN_ACTION; + device_type = "loopaes"; + } else if (!strcmp(aname, "tcryptOpen")) { + aname = OPEN_ACTION; + device_type = "tcrypt"; + } else if (!strcmp(aname, "bitlkOpen")) { + aname = OPEN_ACTION; + device_type = "bitlk"; + } else if (!strcmp(aname, "fvault2Open")) { + aname = OPEN_ACTION; + device_type = "fvault2"; + } else if (!strcmp(aname, "tcryptDump")) { + device_type = "tcrypt"; + } else if (!strcmp(aname, "bitlkDump")) { + device_type = "bitlk"; + } else if (!strcmp(aname, "fvault2Dump")) { + device_type = "fvault2"; + } else if (!strcmp(aname, "remove") || + !strcmp(aname, "plainClose") || + !strcmp(aname, "luksClose") || + !strcmp(aname, "loopaesClose") || + !strcmp(aname, "tcryptClose") || + !strcmp(aname, "bitlkClose") || + !strcmp(aname, "fvault2Close")) { + aname = CLOSE_ACTION; + } else if (!strcmp(aname, "luksErase")) { + aname = ERASE_ACTION; + device_type = "luks"; + } else if (!strcmp(aname, "luksConfig")) { + aname = CONFIG_ACTION; + device_type = "luks2"; + } else if (!strcmp(aname, "refresh")) { + aname = OPEN_ACTION; + ARG_SET_TRUE(OPT_REFRESH_ID); + } else if (ARG_SET(OPT_TYPE_ID)) + device_type = ARG_STR(OPT_TYPE_ID); + + /* ignore user supplied type and query device type instead */ + if (ARG_SET(OPT_REFRESH_ID)) + device_type = NULL; + + for(action = action_types; action->type; action++) + if (strcmp(action->type, aname) == 0) + break; + + if (!action->type) + usage(popt_context, EXIT_FAILURE, _("Unknown action."), + poptGetInvocationName(popt_context)); + + if (action_argc < action->required_action_argc) + help_args(action, popt_context); + + /* this routine short circuits to exit() on error */ + tools_check_args(action->type, tool_core_args, ARRAY_SIZE(tool_core_args), popt_context); + + if (!strcmp(aname, KILLKEY_ACTION) && action_argc > 1) { + ARG_SET_INT32(OPT_KEY_SLOT_ID, atoi(action_argv[1])); + check_key_slot_value(popt_context); + } + + if ((!strcmp(aname, REMOVEKEY_ACTION) || + !strcmp(aname, FORMAT_ACTION)) && + action_argc > 1) { + if (ARG_SET(OPT_KEY_FILE_ID)) + log_err(_("Option --key-file takes precedence over specified key file argument.")); + else + ARG_SET_STR(OPT_KEY_FILE_ID, strdup(action_argv[1])); + } + + if (total_keyfiles > 1 && (strcmp_or_null(device_type, "tcrypt"))) + usage(popt_context, EXIT_FAILURE, _("Only one --key-file argument is allowed."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_PBKDF_ID) && crypt_parse_pbkdf(ARG_STR(OPT_PBKDF_ID), &set_pbkdf)) + usage(popt_context, EXIT_FAILURE, + _("Password-based key derivation function (PBKDF) can be only pbkdf2 or argon2i/argon2id."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_PBKDF_FORCE_ITERATIONS_ID) && ARG_SET(OPT_ITER_TIME_ID)) + usage(popt_context, EXIT_FAILURE, + _("PBKDF forced iterations cannot be combined with iteration time option."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_DEBUG_ID) || ARG_SET(OPT_DEBUG_JSON_ID)) { + crypt_set_debug_level(ARG_SET(OPT_DEBUG_JSON_ID)? CRYPT_DEBUG_JSON : CRYPT_DEBUG_ALL); + dbg_version_and_cmd(argc, argv); + } + + /* reencrypt action specific check */ + + if (ARG_SET(OPT_KEYSLOT_CIPHER_ID) != ARG_SET(OPT_KEYSLOT_KEY_SIZE_ID)) + usage(popt_context, EXIT_FAILURE, _("Options --keyslot-cipher and --keyslot-key-size must be used together."), + poptGetInvocationName(popt_context)); + + error_message = verify_action(action); + if (error_message) + usage(popt_context, EXIT_FAILURE, error_message, poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_TEST_ARGS_ID)) { + log_std(_("No action taken. Invoked with --test-args option.\n")); + tools_cleanup(); + poptFreeContext(popt_context); + return 0; + } + + if (ARG_SET(OPT_DISABLE_KEYRING_ID)) + (void) crypt_volume_key_keyring(NULL, 0); + + if (ARG_SET(OPT_DISABLE_EXTERNAL_TOKENS_ID)) + (void) crypt_token_external_disable(); + + if (ARG_SET(OPT_DISABLE_LOCKS_ID) && crypt_metadata_locking(NULL, 0)) { + log_std(_("Cannot disable metadata locking.")); + r = EXIT_FAILURE; + } else { + r = run_action(action); + } + + tools_cleanup(); + poptFreeContext(popt_context); + return r; +} diff --git a/src/cryptsetup.h b/src/cryptsetup.h new file mode 100644 index 0000000..011a669 --- /dev/null +++ b/src/cryptsetup.h @@ -0,0 +1,177 @@ +/* + * cryptsetup - setup cryptographic volumes for dm-crypt + * + * Copyright (C) 2004 Jana Saout <jana@saout.de> + * Copyright (C) 2004-2007 Clemens Fruhwirth <clemens@endorphin.org> + * Copyright (C) 2009-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2009-2023 Milan Broz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef CRYPTSETUP_H +#define CRYPTSETUP_H + +#include <stdbool.h> +#include <string.h> +#include <stdlib.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdint.h> +#include <errno.h> +#include <unistd.h> +#include <inttypes.h> +#include <limits.h> +#include <ctype.h> +#include <fcntl.h> +#include <popt.h> +#include <sys/stat.h> +#include <sys/time.h> + +#include "lib/nls.h" +#include "lib/bitops.h" +#include "lib/utils_crypt.h" +#include "lib/utils_loop.h" +#include "lib/utils_io.h" +#include "lib/utils_blkid.h" +#include "lib/libcryptsetup_macros.h" + +#include "libcryptsetup.h" + +#define DEFAULT_CIPHER(type) (DEFAULT_##type##_CIPHER "-" DEFAULT_##type##_MODE) + +#define DEFAULT_WIPE_BLOCK 1048576 /* 1 MiB */ +#define MAX_ACTIONS 16 + +/* Common tools */ +void tool_log(int level, const char *msg, void *usrptr __attribute__((unused))); +void quiet_log(int level, const char *msg, void *usrptr); + +int yesDialog(const char *msg, void *usrptr); +int noDialog(const char *msg, void *usrptr); +void show_status(int errcode); +const char *uuid_or_device(const char *spec); +__attribute__ ((noreturn)) \ +void usage(poptContext popt_context, int exitcode, const char *error, const char *more); +void dbg_version_and_cmd(int argc, const char **argv); +int translate_errno(int r); + +typedef enum { CREATED, UNLOCKED, REMOVED } crypt_object_op; +void tools_keyslot_msg(int keyslot, crypt_object_op op); +void tools_token_msg(int token, crypt_object_op op); +void tools_token_error_msg(int error, const char *type, int token, bool pin_provided); +void tools_package_version(const char *name, bool use_pwlibs); + +extern volatile int quit; +void set_int_block(int block); +void set_int_handler(int block); +void check_signal(int *r); +int tools_signals_blocked(void); + +int tools_get_key(const char *prompt, + char **key, size_t *key_size, + uint64_t keyfile_offset, size_t keyfile_size_max, + const char *key_file, + int timeout, int verify, int pwquality, + struct crypt_device *cd); +void tools_passphrase_msg(int r); +int tools_is_stdin(const char *key_file); +int tools_string_to_size(const char *s, uint64_t *size); + +struct tools_progress_params { + uint32_t frequency; + struct timeval start_time; + struct timeval end_time; + uint64_t start_offset; + bool batch_mode; + bool json_output; + const char *interrupt_message; + const char *device; +}; + +int tools_progress(uint64_t size, uint64_t offset, void *usrptr); +const char *tools_get_device_name(const char *device, char **r_backing_file); + +int tools_read_vk(const char *file, char **key, int keysize); +int tools_write_mk(const char *file, const char *key, int keysize); + +int tools_read_json_file(const char *file, char **json, size_t *json_size, bool batch_mode); +int tools_write_json_file(const char *file, const char *json); + +typedef enum { + PRB_FILTER_NONE = 0, + PRB_FILTER_LUKS, + PRB_ONLY_LUKS +} tools_probe_filter_info; + +int tools_detect_signatures(const char *device, tools_probe_filter_info filter, size_t *count, bool batch_mode); +int tools_wipe_all_signatures(const char *path, bool exclusive, bool only_luks); +int tools_superblock_block_size(const char *device, char *sb_name, + size_t sb_name_len, unsigned *r_block_size); +bool tools_blkid_supported(void); + +int tools_lookup_crypt_device(struct crypt_device *cd, const char *type, + const char *data_device_path, char **r_name); + + +/* each utility is required to implement it */ +void tools_cleanup(void); + +/* Log */ +#define log_dbg(x...) crypt_logf(NULL, CRYPT_LOG_DEBUG, x) +#define log_std(x...) crypt_logf(NULL, CRYPT_LOG_NORMAL, x) +#define log_verbose(x...) crypt_logf(NULL, CRYPT_LOG_VERBOSE, x) +#define log_err(x...) crypt_logf(NULL, CRYPT_LOG_ERROR, x) + +typedef enum { + CRYPT_ARG_BOOL = 0, + CRYPT_ARG_STRING, + CRYPT_ARG_INT32, + CRYPT_ARG_UINT32, + CRYPT_ARG_INT64, + CRYPT_ARG_UINT64, + CRYPT_ARG_ALIAS +} crypt_arg_type_info; + +struct tools_arg { + const char *name; + bool set; + crypt_arg_type_info type; + union { + char *str_value; + uint64_t u64_value; + uint32_t u32_value; + int32_t i32_value; + int64_t i64_value; + union { + unsigned id; + struct tools_arg *ptr; + } o; + } u; + const char *actions_array[MAX_ACTIONS]; +}; + +void tools_parse_arg_value(poptContext popt_context, crypt_arg_type_info type, struct tools_arg *arg, const char *popt_arg, int popt_val, bool(*needs_size_conv_fn)(unsigned arg_id)); + +void tools_args_free(struct tools_arg *args, size_t args_count); + +void tools_check_args(const char *action, const struct tools_arg *args, size_t args_size, poptContext popt_context); + +struct tools_log_params { + bool verbose; + bool debug; +}; + +#endif /* CRYPTSETUP_H */ diff --git a/src/cryptsetup_arg_list.h b/src/cryptsetup_arg_list.h new file mode 100644 index 0000000..a7e5bb0 --- /dev/null +++ b/src/cryptsetup_arg_list.h @@ -0,0 +1,232 @@ +/* + * Cryptsetup command line arguments list + * + * Copyright (C) 2020-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2020-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/* long name, short name, popt type, help description, units, internal argument type, default value, allowed actions (empty=global) */ + +ARG(OPT_ACTIVE_NAME, '\0', POPT_ARG_STRING, N_("Override device autodetection of dm device to be reencrypted"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_ALIGN_PAYLOAD, '\0', POPT_ARG_STRING, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS"), CRYPT_ARG_UINT32, {}, OPT_ALIGN_PAYLOAD_ACTIONS) + +ARG(OPT_ALLOW_DISCARDS, '\0', POPT_ARG_NONE, N_("Allow discards (aka TRIM) requests for device"), NULL, CRYPT_ARG_BOOL, {}, OPT_ALLOW_DISCARDS_ACTIONS) + +ARG(OPT_BATCH_MODE, 'q', POPT_ARG_NONE, N_("Do not ask for confirmation"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_CANCEL_DEFERRED, '\0', POPT_ARG_NONE, N_("Cancel a previously set deferred device removal"), NULL, CRYPT_ARG_BOOL, {}, OPT_DEFERRED_ACTIONS) + +ARG(OPT_CIPHER, 'c', POPT_ARG_STRING, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_DEBUG, '\0', POPT_ARG_NONE, N_("Show debug messages"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DEBUG_JSON, '\0', POPT_ARG_NONE, N_("Show debug messages including JSON metadata"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DEFERRED, '\0', POPT_ARG_NONE, N_("Device removal is deferred until the last user closes it"), NULL, CRYPT_ARG_BOOL, {}, OPT_DEFERRED_ACTIONS) + +ARG(OPT_DEVICE_SIZE, '\0', POPT_ARG_STRING, N_("Use only specified device size (ignore rest of device). DANGEROUS!"), N_("bytes"), CRYPT_ARG_UINT64, {}, OPT_DEVICE_SIZE_ACTIONS) + +ARG(OPT_DECRYPT, '\0', POPT_ARG_NONE, N_("Decrypt LUKS2 device (remove encryption)."), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DISABLE_EXTERNAL_TOKENS, '\0', POPT_ARG_NONE, N_("Disable loading of external LUKS2 token plugins"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DISABLE_KEYRING, '\0', POPT_ARG_NONE, N_("Disable loading volume keys via kernel keyring"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DISABLE_LOCKS, '\0', POPT_ARG_NONE, N_("Disable locking of on-disk metadata"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DISABLE_VERACRYPT, '\0', POPT_ARG_NONE, N_("Do not scan for VeraCrypt compatible device"), NULL, CRYPT_ARG_BOOL, {}, OPT_DISABLE_VERACRYPT_ACTIONS) + +ARG(OPT_DUMP_JSON, '\0', POPT_ARG_NONE, N_("Dump info in JSON format (LUKS2 only)"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DUMP_VOLUME_KEY, '\0', POPT_ARG_NONE, N_("Dump volume key instead of keyslots info"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_ENCRYPT, '\0', POPT_ARG_NONE, N_("Encrypt LUKS2 device (in-place encryption)."), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_FORCE_PASSWORD, '\0', POPT_ARG_NONE, N_("Disable password quality check (if enabled)"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_FORCE_OFFLINE_REENCRYPT, '\0', POPT_ARG_NONE, N_("Force offline LUKS2 reencryption and bypass active device detection."), NULL, CRYPT_ARG_BOOL, {}, OPT_FORCE_OFFLINE_REENCRYPT_ACTIONS) + +ARG(OPT_HASH, 'h', POPT_ARG_STRING, N_("The hash used to create the encryption key from the passphrase"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_HEADER, '\0', POPT_ARG_STRING, N_("Device or file with separated LUKS header"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_HEADER_BACKUP_FILE, '\0', POPT_ARG_STRING, N_("File with LUKS header and keyslots backup"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_HOTZONE_SIZE, '\0', POPT_ARG_STRING, N_("Maximal reencryption hotzone size."), N_("bytes"), CRYPT_ARG_UINT64, {}, OPT_HOTZONE_SIZE_ACTIONS) + +ARG(OPT_INIT_ONLY, '\0', POPT_ARG_NONE, N_("Initialize LUKS2 reencryption in metadata only."), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_INTEGRITY, 'I', POPT_ARG_STRING, N_("Data integrity algorithm (LUKS2 only)"), NULL, CRYPT_ARG_STRING, {}, OPT_INTEGRITY_ACTIONS) + +ARG(OPT_INTEGRITY_LEGACY_PADDING,'\0', POPT_ARG_NONE, N_("Use inefficient legacy padding (old kernels)"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_INTEGRITY_NO_JOURNAL, '\0', POPT_ARG_NONE, N_("Disable journal for integrity device"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_INTEGRITY_NO_WIPE, '\0', POPT_ARG_NONE, N_("Do not wipe device after format"), NULL, CRYPT_ARG_BOOL, {}, OPT_INTEGRITY_NO_WIPE_ACTIONS) + +ARG(OPT_ITER_TIME, 'i', POPT_ARG_STRING, N_("PBKDF iteration time for LUKS (in ms)"), N_("msecs"), CRYPT_ARG_UINT32, {}, OPT_ITER_TIME_ACTIONS) + +ARG(OPT_IV_LARGE_SECTORS, '\0', POPT_ARG_NONE, N_("Use IV counted in sector size (not in 512 bytes)"), NULL , CRYPT_ARG_BOOL, {}, OPT_IV_LARGE_SECTORS_ACTIONS) + +ARG(OPT_JSON_FILE, '\0', POPT_ARG_STRING, N_("Read or write the json from or to a file"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_KEEP_KEY, '\0', POPT_ARG_NONE, N_("Do not change volume key."), NULL, CRYPT_ARG_BOOL, {}, OPT_KEEP_KEY_ACTIONS) + +ARG(OPT_KEY_DESCRIPTION, '\0', POPT_ARG_STRING, N_("Key description"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_KEY_FILE, 'd', POPT_ARG_STRING, N_("Read the key from a file"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_KEY_SIZE, 's', POPT_ARG_STRING, N_("The size of the encryption key"), N_("BITS"), CRYPT_ARG_UINT32, {}, OPT_KEY_SIZE_ACTIONS) + +ARG(OPT_KEY_SLOT, 'S', POPT_ARG_STRING, N_("Slot number for new key (default is first free)"), "INT", CRYPT_ARG_INT32, { .i32_value = CRYPT_ANY_SLOT }, OPT_KEY_SLOT_ACTIONS) + +ARG(OPT_KEYFILE_OFFSET, '\0', POPT_ARG_STRING, N_("Number of bytes to skip in keyfile"), N_("bytes"), CRYPT_ARG_UINT64, {}, {}) + +ARG(OPT_KEYFILE_SIZE, 'l', POPT_ARG_STRING, N_("Limits the read from keyfile"), N_("bytes"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_KEYSLOT_CIPHER, '\0', POPT_ARG_STRING, N_("LUKS2 keyslot: The cipher used for keyslot encryption"), NULL, CRYPT_ARG_STRING, {}, OPT_KEYSLOT_CIPHER_ACTIONS) + +ARG(OPT_KEYSLOT_KEY_SIZE, '\0', POPT_ARG_STRING, N_("LUKS2 keyslot: The size of the encryption key"), N_("BITS"), CRYPT_ARG_UINT32, {}, OPT_KEYSLOT_KEY_SIZE_ACTIONS) + +ARG(OPT_LABEL, '\0', POPT_ARG_STRING, N_("Set label for the LUKS2 device"), NULL, CRYPT_ARG_STRING, {}, OPT_LABEL_ACTIONS) + +ARG(OPT_LUKS2_KEYSLOTS_SIZE, '\0', POPT_ARG_STRING, N_("LUKS2 header keyslots area size"), N_("bytes"), CRYPT_ARG_UINT64, {}, OPT_LUKS2_KEYSLOTS_SIZE_ACTIONS) + +ARG(OPT_LUKS2_METADATA_SIZE, '\0', POPT_ARG_STRING, N_("LUKS2 header metadata area size"), N_("bytes"), CRYPT_ARG_UINT64, {}, OPT_LUKS2_METADATA_SIZE_ACTIONS) + +ARG(OPT_VOLUME_KEY_FILE, '\0', POPT_ARG_STRING, N_("Use the volume key from file."), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_NEW_KEYFILE, '\0', POPT_ARG_STRING, N_("Read the key for a new slot from a file"), NULL, CRYPT_ARG_STRING, {}, OPT_NEW_KEYFILE_ACTIONS) + +ARG(OPT_NEW_KEY_SLOT, '\0', POPT_ARG_STRING, N_("Slot number for new key (default is first free)"), "INT", CRYPT_ARG_INT32, { .i32_value = CRYPT_ANY_SLOT }, OPT_NEW_KEY_SLOT_ACTIONS) + +ARG(OPT_NEW_KEYFILE_OFFSET , '\0', POPT_ARG_STRING, N_("Number of bytes to skip in newly added keyfile"), N_("bytes"), CRYPT_ARG_UINT64, {}, {}) + +ARG(OPT_NEW_KEYFILE_SIZE, '\0', POPT_ARG_STRING, N_("Limits the read from newly added keyfile"), N_("bytes"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_NEW_TOKEN_ID, '\0', POPT_ARG_STRING, N_("Token number (default: any)"), "INT", CRYPT_ARG_INT32, { .i32_value = CRYPT_ANY_TOKEN }, OPT_NEW_TOKEN_ID_ACTIONS) + +ARG(OPT_OFFSET, 'o', POPT_ARG_STRING, N_("The start offset in the backend device"), N_("SECTORS"), CRYPT_ARG_UINT64, {}, OPT_OFFSET_ACTIONS) + +ARG(OPT_PBKDF, '\0', POPT_ARG_STRING, N_("PBKDF algorithm (for LUKS2): argon2i, argon2id, pbkdf2"), NULL, CRYPT_ARG_STRING, {}, OPT_PBKDF_ACTIONS) + +ARG(OPT_PBKDF_FORCE_ITERATIONS, '\0', POPT_ARG_STRING, N_("PBKDF iterations cost (forced, disables benchmark)"), "LONG", CRYPT_ARG_UINT32, {}, OPT_PBKDF_FORCE_ITERATIONS_ACTIONS) + +ARG(OPT_PBKDF_MEMORY, '\0', POPT_ARG_STRING, N_("PBKDF memory cost limit"), N_("kilobytes"), CRYPT_ARG_UINT32, { .u32_value = DEFAULT_LUKS2_MEMORY_KB }, {}) + +ARG(OPT_PBKDF_PARALLEL, '\0', POPT_ARG_STRING, N_("PBKDF parallel cost"), N_("threads"), CRYPT_ARG_UINT32, { .u32_value = DEFAULT_LUKS2_PARALLEL_THREADS }, {}) + +ARG(OPT_PERF_NO_READ_WORKQUEUE, '\0', POPT_ARG_NONE, N_("Bypass dm-crypt workqueue and process read requests synchronously"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_PERF_NO_WRITE_WORKQUEUE, '\0', POPT_ARG_NONE, N_("Bypass dm-crypt workqueue and process write requests synchronously"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_PERF_SAME_CPU_CRYPT, '\0', POPT_ARG_NONE, N_("Use dm-crypt same_cpu_crypt performance compatibility option"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_PERF_SUBMIT_FROM_CRYPT_CPUS, '\0', POPT_ARG_NONE, N_("Use dm-crypt submit_from_crypt_cpus performance compatibility option"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_PERSISTENT, '\0', POPT_ARG_NONE, N_("Set activation flags persistent for device"), NULL, CRYPT_ARG_BOOL, {}, OPT_PERSISTENT_ACTIONS) + +ARG(OPT_PRIORITY, '\0', POPT_ARG_STRING, N_("Keyslot priority: ignore, normal, prefer"), NULL, CRYPT_ARG_STRING, {}, OPT_PRIORITY_ACTIONS) + +ARG(OPT_PROGRESS_JSON, '\0', POPT_ARG_NONE, N_("Print progress data in json format (suitable for machine processing)"), NULL, CRYPT_ARG_BOOL, {}, OPT_PROGRESS_JSON_ACTIONS) + +ARG(OPT_PROGRESS_FREQUENCY, '\0', POPT_ARG_STRING, N_("Progress line update (in seconds)"), N_("secs"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_READONLY, 'r', POPT_ARG_NONE, N_("Create a readonly mapping"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_REDUCE_DEVICE_SIZE, '\0', POPT_ARG_STRING, N_("Reduce data device size (move data offset). DANGEROUS!"), N_("bytes"), CRYPT_ARG_UINT64, {}, {}) + +ARG(OPT_REFRESH, '\0', POPT_ARG_NONE, N_("Refresh (reactivate) device with new parameters"), NULL, CRYPT_ARG_BOOL, {}, OPT_REFRESH_ACTIONS) + +ARG(OPT_RESILIENCE, '\0', POPT_ARG_STRING, N_("Reencryption hotzone resilience type (checksum,journal,none)"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_RESILIENCE_HASH, '\0', POPT_ARG_STRING, N_("Reencryption hotzone checksums hash"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_RESUME_ONLY, '\0', POPT_ARG_NONE, N_("Resume initialized LUKS2 reencryption only."), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_SECTOR_SIZE, '\0', POPT_ARG_STRING, N_("Encryption sector size (default: 512 bytes)"), "INT", CRYPT_ARG_UINT32, {}, OPT_SECTOR_SIZE_ACTIONS) + +ARG(OPT_SERIALIZE_MEMORY_HARD_PBKDF, '\0', POPT_ARG_NONE, N_("Use global lock to serialize memory hard PBKDF (OOM workaround)"), NULL, CRYPT_ARG_BOOL, {}, OPT_SERIALIZE_MEMORY_HARD_PBKDF_ACTIONS) + +ARG(OPT_SHARED, '\0', POPT_ARG_NONE, N_("Share device with another non-overlapping crypt segment"), NULL, CRYPT_ARG_BOOL, {}, OPT_SHARED_ACTIONS ) + +ARG(OPT_SIZE, 'b', POPT_ARG_STRING, N_("The size of the device"), N_("SECTORS"), CRYPT_ARG_UINT64, {}, OPT_SIZE_ACTIONS) + +ARG(OPT_SKIP, 'p', POPT_ARG_STRING, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS"), CRYPT_ARG_UINT64, {}, OPT_SKIP_ACTIONS) + +ARG(OPT_SUBSYSTEM, '\0', POPT_ARG_STRING, N_("Set subsystem label for the LUKS2 device"), NULL, CRYPT_ARG_STRING, {}, OPT_SUBSYSTEM_ACTIONS) + +ARG(OPT_TCRYPT_BACKUP, '\0', POPT_ARG_NONE, N_("Use backup (secondary) TCRYPT header"), NULL, CRYPT_ARG_BOOL, {}, OPT_TCRYPT_BACKUP_ACTIONS) + +ARG(OPT_TCRYPT_HIDDEN, '\0', POPT_ARG_NONE, N_("Use hidden header (hidden TCRYPT device)"), NULL, CRYPT_ARG_BOOL, {}, OPT_TCRYPT_HIDDEN_ACTIONS) + +ARG(OPT_TCRYPT_SYSTEM, '\0', POPT_ARG_NONE, N_("Device is system TCRYPT drive (with bootloader)"), NULL, CRYPT_ARG_BOOL, {}, OPT_TCRYPT_SYSTEM_ACTIONS) + +ARG(OPT_TEST_ARGS, '\0', POPT_ARG_NONE, N_("Do not run action, just validate all command line parameters"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_TEST_PASSPHRASE, '\0', POPT_ARG_NONE, N_("Do not activate device, just check passphrase"), NULL, CRYPT_ARG_BOOL, {}, OPT_TEST_PASSPHRASE_ACTIONS) + +ARG(OPT_TIMEOUT, 't', POPT_ARG_STRING, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_TOKEN_ID, '\0', POPT_ARG_STRING, N_("Token number (default: any)"), "INT", CRYPT_ARG_INT32, { .i32_value = CRYPT_ANY_TOKEN }, {}) + +ARG(OPT_TOKEN_ONLY, '\0', POPT_ARG_NONE, N_("Do not ask for passphrase if activation by token fails"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_TOKEN_REPLACE, '\0', POPT_ARG_NONE, N_("Replace the current token"), NULL, CRYPT_ARG_BOOL, {}, OPT_TOKEN_REPLACE_ACTIONS) + +ARG(OPT_TOKEN_TYPE, '\0', POPT_ARG_STRING, N_("Restrict allowed token types used to retrieve LUKS2 key"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_TRIES, 'T', POPT_ARG_STRING, N_("How often the input of the passphrase can be retried"), "INT", CRYPT_ARG_UINT32, { .u32_value = 3 }, {}) + +ARG(OPT_TYPE, 'M', POPT_ARG_STRING, N_("Type of device metadata: luks, luks1, luks2, plain, loopaes, tcrypt, bitlk"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_UNBOUND, '\0', POPT_ARG_NONE, N_("Create or dump unbound LUKS2 keyslot (unassigned to data segment) or LUKS2 token (unassigned to keyslot)"), NULL, CRYPT_ARG_BOOL, {}, OPT_UNBOUND_ACTIONS) + +ARG(OPT_USE_RANDOM, '\0', POPT_ARG_NONE, N_("Use /dev/random for generating volume key"), NULL, CRYPT_ARG_BOOL, {}, OPT_USE_RANDOM_ACTIONS) + +ARG(OPT_USE_URANDOM, '\0', POPT_ARG_NONE, N_("Use /dev/urandom for generating volume key"), NULL, CRYPT_ARG_BOOL, {}, OPT_USE_URANDOM_ACTIONS) + +ARG(OPT_UUID, '\0', POPT_ARG_STRING, N_("UUID for device to use"), NULL, CRYPT_ARG_STRING, {}, OPT_UUID_ACTIONS) + +ARG(OPT_VERACRYPT, '\0', POPT_ARG_NONE, N_("Scan also for VeraCrypt compatible device"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_VERACRYPT_PIM, '\0', POPT_ARG_STRING, N_("Personal Iteration Multiplier for VeraCrypt compatible device"), "INT", CRYPT_ARG_UINT32, {}, OPT_VERACRYPT_PIM_ACTIONS) + +ARG(OPT_VERACRYPT_QUERY_PIM, '\0', POPT_ARG_NONE, N_("Query Personal Iteration Multiplier for VeraCrypt compatible device"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_VERBOSE, 'v', POPT_ARG_NONE, N_("Shows more detailed error messages"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_VERIFY_PASSPHRASE, 'y', POPT_ARG_NONE, N_("Verifies the passphrase by asking for it twice"), NULL, CRYPT_ARG_BOOL, {}, {}) + +/* added for reencryption */ + +ARG(OPT_BLOCK_SIZE, 'B', POPT_ARG_STRING, N_("Reencryption block size"), N_("MiB"), CRYPT_ARG_UINT32, { .u32_value = 4 }, {}) + +ARG(OPT_NEW, 'N', POPT_ARG_NONE, N_("Create new header on not encrypted device"), NULL, CRYPT_ARG_ALIAS, { .o.id = OPT_ENCRYPT_ID }, {}) + +ARG(OPT_USE_DIRECTIO, '\0', POPT_ARG_NONE, N_("Use direct-io when accessing devices"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_USE_FSYNC, '\0', POPT_ARG_NONE, N_("Use fsync after each block"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_WRITE_LOG, '\0', POPT_ARG_NONE, N_("Update log file after every block"), NULL, CRYPT_ARG_BOOL, {}, {}) + +/* aliases */ + +ARG(OPT_DUMP_MASTER_KEY, '\0', POPT_ARG_NONE, N_("Alias for --dump-volume-key"), NULL, CRYPT_ARG_ALIAS, { .o.id = OPT_DUMP_VOLUME_KEY_ID}, {}) + +ARG(OPT_MASTER_KEY_FILE, '\0', POPT_ARG_STRING, N_("Alias for --dump-volume-key-file"), NULL, CRYPT_ARG_ALIAS, { .o.id = OPT_VOLUME_KEY_FILE_ID}, {}) diff --git a/src/cryptsetup_args.h b/src/cryptsetup_args.h new file mode 100644 index 0000000..63604a3 --- /dev/null +++ b/src/cryptsetup_args.h @@ -0,0 +1,113 @@ +/* + * Command line arguments helpers + * + * Copyright (C) 2020-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2020-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef CRYPTSETUP_ARGS_H +#define CRYPTSETUP_ARGS_H + +#include "utils_arg_names.h" +#include "utils_arg_macros.h" + +#define BITLKDUMP_ACTION "bitlkDump" +#define BENCHMARK_ACTION "benchmark" +#define CLOSE_ACTION "close" +#define CONFIG_ACTION "config" +#define CONVERT_ACTION "convert" +#define ERASE_ACTION "erase" +#define FVAULT2DUMP_ACTION "fvault2Dump" +#define ISLUKS_ACTION "isLuks" +#define ADDKEY_ACTION "luksAddKey" +#define CHANGEKEY_ACTION "luksChangeKey" +#define CONVERTKEY_ACTION "luksConvertKey" +#define LUKSDUMP_ACTION "luksDump" +#define FORMAT_ACTION "luksFormat" +#define HEADERBACKUP_ACTION "luksHeaderBackup" +#define HEADERRESTORE_ACTION "luksHeaderRestore" +#define KILLKEY_ACTION "luksKillSlot" +#define REMOVEKEY_ACTION "luksRemoveKey" +#define RESUME_ACTION "luksResume" +#define SUSPEND_ACTION "luksSuspend" +#define UUID_ACTION "luksUUID" +#define OPEN_ACTION "open" +#define REENCRYPT_ACTION "reencrypt" +#define REPAIR_ACTION "repair" +#define RESIZE_ACTION "resize" +#define STATUS_ACTION "status" +#define TCRYPTDUMP_ACTION "tcryptDump" +#define TOKEN_ACTION "token" + +/* avoid unshielded commas in ARG() macros later */ +#define OPT_ALIGN_PAYLOAD_ACTIONS { FORMAT_ACTION, REENCRYPT_ACTION } +#define OPT_ALLOW_DISCARDS_ACTIONS { OPEN_ACTION } +#define OPT_DEFERRED_ACTIONS { CLOSE_ACTION } +#define OPT_DEVICE_SIZE_ACTIONS { OPEN_ACTION, RESIZE_ACTION, REENCRYPT_ACTION } +#define OPT_DISABLE_VERACRYPT_ACTIONS { OPEN_ACTION, TCRYPTDUMP_ACTION } +#define OPT_HOTZONE_SIZE_ACTIONS { REENCRYPT_ACTION } +#define OPT_FORCE_OFFLINE_REENCRYPT_ACTIONS { REENCRYPT_ACTION } +#define OPT_INTEGRITY_ACTIONS { FORMAT_ACTION, REENCRYPT_ACTION } +#define OPT_INTEGRITY_NO_WIPE_ACTIONS { FORMAT_ACTION, REENCRYPT_ACTION } +#define OPT_ITER_TIME_ACTIONS { BENCHMARK_ACTION, FORMAT_ACTION, ADDKEY_ACTION, CHANGEKEY_ACTION, CONVERTKEY_ACTION, REENCRYPT_ACTION } +#define OPT_IV_LARGE_SECTORS_ACTIONS { OPEN_ACTION } +#define OPT_KEEP_KEY_ACTIONS { REENCRYPT_ACTION } +#define OPT_KEY_SIZE_ACTIONS { OPEN_ACTION, BENCHMARK_ACTION, FORMAT_ACTION, REENCRYPT_ACTION, ADDKEY_ACTION } +#define OPT_KEY_SLOT_ACTIONS { OPEN_ACTION, REENCRYPT_ACTION, CONFIG_ACTION, FORMAT_ACTION, ADDKEY_ACTION, CHANGEKEY_ACTION, CONVERTKEY_ACTION, LUKSDUMP_ACTION, TOKEN_ACTION, RESUME_ACTION } +#define OPT_KEYSLOT_CIPHER_ACTIONS { FORMAT_ACTION, REENCRYPT_ACTION, ADDKEY_ACTION, CHANGEKEY_ACTION, CONVERTKEY_ACTION } +#define OPT_KEYSLOT_KEY_SIZE_ACTIONS OPT_KEYSLOT_CIPHER_ACTIONS +#define OPT_NEW_KEYFILE_ACTIONS { ADDKEY_ACTION } +#define OPT_NEW_KEY_SLOT_ACTIONS { ADDKEY_ACTION } +#define OPT_NEW_TOKEN_ID_ACTIONS { ADDKEY_ACTION } +#define OPT_LABEL_ACTIONS { CONFIG_ACTION, FORMAT_ACTION, REENCRYPT_ACTION } +#define OPT_LUKS2_KEYSLOTS_SIZE_ACTIONS { REENCRYPT_ACTION, FORMAT_ACTION } +#define OPT_LUKS2_METADATA_SIZE_ACTIONS { REENCRYPT_ACTION, FORMAT_ACTION } +#define OPT_OFFSET_ACTIONS { OPEN_ACTION, REENCRYPT_ACTION, FORMAT_ACTION } +#define OPT_PBKDF_ACTIONS { BENCHMARK_ACTION, FORMAT_ACTION, ADDKEY_ACTION, CHANGEKEY_ACTION, CONVERTKEY_ACTION, REENCRYPT_ACTION } +#define OPT_PBKDF_FORCE_ITERATIONS_ACTIONS { FORMAT_ACTION, ADDKEY_ACTION, CHANGEKEY_ACTION, CONVERTKEY_ACTION, REENCRYPT_ACTION } +#define OPT_PERSISTENT_ACTIONS { OPEN_ACTION } +#define OPT_PRIORITY_ACTIONS { CONFIG_ACTION } +#define OPT_PROGRESS_JSON_ACTIONS { FORMAT_ACTION, REENCRYPT_ACTION } +#define OPT_REFRESH_ACTIONS { OPEN_ACTION } +#define OPT_SECTOR_SIZE_ACTIONS { OPEN_ACTION, REENCRYPT_ACTION, FORMAT_ACTION } +#define OPT_SERIALIZE_MEMORY_HARD_PBKDF_ACTIONS { OPEN_ACTION } +#define OPT_SHARED_ACTIONS { OPEN_ACTION } +#define OPT_SIZE_ACTIONS { OPEN_ACTION, RESIZE_ACTION } +#define OPT_SKIP_ACTIONS { OPEN_ACTION } +#define OPT_SUBSYSTEM_ACTIONS { CONFIG_ACTION, FORMAT_ACTION, REENCRYPT_ACTION } +#define OPT_TCRYPT_BACKUP_ACTIONS { OPEN_ACTION, TCRYPTDUMP_ACTION } +#define OPT_TCRYPT_HIDDEN_ACTIONS { OPEN_ACTION, TCRYPTDUMP_ACTION } +#define OPT_TCRYPT_SYSTEM_ACTIONS { OPEN_ACTION, TCRYPTDUMP_ACTION } +#define OPT_TEST_PASSPHRASE_ACTIONS { OPEN_ACTION } +#define OPT_TOKEN_REPLACE_ACTIONS { TOKEN_ACTION } +#define OPT_UNBOUND_ACTIONS { ADDKEY_ACTION, LUKSDUMP_ACTION, OPEN_ACTION, TOKEN_ACTION } +#define OPT_USE_RANDOM_ACTIONS { FORMAT_ACTION, REENCRYPT_ACTION } +#define OPT_USE_URANDOM_ACTIONS { FORMAT_ACTION, REENCRYPT_ACTION } +#define OPT_UUID_ACTIONS { FORMAT_ACTION, UUID_ACTION, REENCRYPT_ACTION } +#define OPT_VERACRYPT_PIM_ACTIONS { OPEN_ACTION, TCRYPTDUMP_ACTION } +#define OPT_VERACRYPT_QUERY_PIM_ACTIONS { OPEN_ACTION, TCRYPTDUMP_ACTION } + +enum { +OPT_UNUSED_ID = 0, /* leave unused due to popt library */ +#define ARG(A, B, C, D, E, F, G, H) A ## _ID, +#include "cryptsetup_arg_list.h" +#undef ARG +}; + +extern struct tools_arg tool_core_args[]; + +#endif diff --git a/src/integritysetup.c b/src/integritysetup.c new file mode 100644 index 0000000..eee6171 --- /dev/null +++ b/src/integritysetup.c @@ -0,0 +1,767 @@ +/* + * integritysetup - setup integrity protected volumes for dm-integrity + * + * Copyright (C) 2017-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2017-2023 Milan Broz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <uuid/uuid.h> + +#define DEFAULT_ALG_NAME "crc32c" + +#include "cryptsetup.h" +#include "integritysetup_args.h" + +#define PACKAGE_INTEGRITY "integritysetup" + +static const char **action_argv; +static int action_argc; +static struct tools_log_params log_parms; + +void tools_cleanup(void) +{ + tools_args_free(tool_core_args, ARRAY_SIZE(tool_core_args)); +} + +static int _read_keys(char **integrity_key, struct crypt_params_integrity *params) +{ + char *int_key = NULL, *journal_integrity_key = NULL, *journal_crypt_key = NULL; + int r; + + if (integrity_key && ARG_SET(OPT_INTEGRITY_KEY_FILE_ID)) { + r = tools_read_vk(ARG_STR(OPT_INTEGRITY_KEY_FILE_ID), &int_key, ARG_UINT32(OPT_INTEGRITY_KEY_SIZE_ID)); + if (r < 0) + return r; + params->integrity_key_size = ARG_UINT32(OPT_INTEGRITY_KEY_SIZE_ID); + } + + if (ARG_SET(OPT_JOURNAL_INTEGRITY_KEY_FILE_ID)) { + r = tools_read_vk(ARG_STR(OPT_JOURNAL_INTEGRITY_KEY_FILE_ID), &journal_integrity_key, ARG_UINT32(OPT_JOURNAL_INTEGRITY_KEY_SIZE_ID)); + if (r < 0) { + crypt_safe_free(int_key); + return r; + } + params->journal_integrity_key = journal_integrity_key; + params->journal_integrity_key_size = ARG_UINT32(OPT_JOURNAL_INTEGRITY_KEY_SIZE_ID); + } + + if (ARG_SET(OPT_JOURNAL_CRYPT_KEY_FILE_ID)) { + r = tools_read_vk(ARG_STR(OPT_JOURNAL_CRYPT_KEY_FILE_ID), &journal_crypt_key, ARG_UINT32(OPT_JOURNAL_CRYPT_KEY_SIZE_ID)); + if (r < 0) { + crypt_safe_free(int_key); + crypt_safe_free(journal_integrity_key); + return r; + } + params->journal_crypt_key = journal_crypt_key; + params->journal_crypt_key_size = ARG_UINT32(OPT_JOURNAL_CRYPT_KEY_SIZE_ID); + } + + if (integrity_key) + *integrity_key = int_key; + + return 0; +} + +static int _wipe_data_device(struct crypt_device *cd, const char *integrity_key) +{ + char tmp_name[64], tmp_path[128], tmp_uuid[40]; + uuid_t tmp_uuid_bin; + int r = -EINVAL; + char *backing_file = NULL; + struct tools_progress_params prog_parms = { + .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID), + .batch_mode = ARG_SET(OPT_BATCH_MODE_ID), + .json_output = ARG_SET(OPT_PROGRESS_JSON_ID), + .interrupt_message = _("\nWipe interrupted."), + .device = tools_get_device_name(crypt_get_device_name(cd), &backing_file) + }; + + if (!ARG_SET(OPT_BATCH_MODE_ID)) + log_std(_("Wiping device to initialize integrity checksum.\n" + "You can interrupt this by pressing CTRL+c " + "(rest of not wiped device will contain invalid checksum).\n")); + + /* Activate the device a temporary one */ + uuid_generate(tmp_uuid_bin); + uuid_unparse(tmp_uuid_bin, tmp_uuid); + if (snprintf(tmp_name, sizeof(tmp_name), "temporary-cryptsetup-%s", tmp_uuid) < 0) + goto out; + if (snprintf(tmp_path, sizeof(tmp_path), "%s/%s", crypt_get_dir(), tmp_name) < 0) + goto out; + + r = crypt_activate_by_volume_key(cd, tmp_name, integrity_key, + ARG_UINT32(OPT_INTEGRITY_KEY_SIZE_ID), CRYPT_ACTIVATE_PRIVATE | CRYPT_ACTIVATE_NO_JOURNAL); + if (r < 0) + goto out; + + /* Wipe the device */ + set_int_handler(0); + r = crypt_wipe(cd, tmp_path, CRYPT_WIPE_ZERO, 0, 0, DEFAULT_WIPE_BLOCK, + 0, &tools_progress, &prog_parms); + if (crypt_deactivate(cd, tmp_name)) + log_err(_("Cannot deactivate temporary device %s."), tmp_path); + set_int_block(0); + +out: + free(backing_file); + return r; +} + +static int action_format(void) +{ + struct crypt_device *cd = NULL; + struct crypt_params_integrity params = { + .journal_size = ARG_UINT64(OPT_JOURNAL_SIZE_ID), + .interleave_sectors = ARG_UINT32(OPT_INTERLEAVE_SECTORS_ID), + /* in bitmap mode we have to overload these values... */ + .journal_watermark = ARG_SET(OPT_INTEGRITY_BITMAP_MODE_ID) ? ARG_UINT32(OPT_BITMAP_SECTORS_PER_BIT_ID) : ARG_UINT32(OPT_JOURNAL_WATERMARK_ID), + .journal_commit_time = ARG_SET(OPT_INTEGRITY_BITMAP_MODE_ID) ? ARG_UINT32(OPT_BITMAP_FLUSH_TIME_ID) : ARG_UINT32(OPT_JOURNAL_COMMIT_TIME_ID), + .buffer_sectors = ARG_UINT32(OPT_BUFFER_SECTORS_ID), + .tag_size = ARG_UINT32(OPT_TAG_SIZE_ID), + .sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID), + }, params2; + char integrity[MAX_CIPHER_LEN], journal_integrity[MAX_CIPHER_LEN], journal_crypt[MAX_CIPHER_LEN]; + char *integrity_key = NULL, *msg = NULL; + int r; + size_t signatures; + + r = crypt_parse_hash_integrity_mode(ARG_STR(OPT_INTEGRITY_ID), integrity); + if (r < 0) { + log_err(_("No known integrity specification pattern detected.")); + return r; + } + params.integrity = integrity; + + if (ARG_SET(OPT_JOURNAL_INTEGRITY_ID)) { + r = crypt_parse_hash_integrity_mode(ARG_STR(OPT_JOURNAL_INTEGRITY_ID), journal_integrity); + if (r < 0) { + log_err(_("No known integrity specification pattern detected.")); + return r; + } + params.journal_integrity = journal_integrity; + } + + if (ARG_SET(OPT_JOURNAL_CRYPT_ID)) { + r = crypt_parse_hash_integrity_mode(ARG_STR(OPT_JOURNAL_CRYPT_ID), journal_crypt); + if (r < 0) { + log_err(_("No known integrity specification pattern detected.")); + return r; + } + params.journal_crypt = journal_crypt; + } + + r = _read_keys(&integrity_key, ¶ms); + if (r) + goto out; + + r = crypt_init_data_device(&cd, action_argv[0], ARG_STR(OPT_DATA_DEVICE_ID)); + if (r < 0) + goto out; + + if (!ARG_SET(OPT_BATCH_MODE_ID)) { + if (ARG_SET(OPT_DATA_DEVICE_ID) && !ARG_SET(OPT_NO_WIPE_ID)) + r = asprintf(&msg, _("This will overwrite data on %s and %s irrevocably.\n" + "To preserve data device use --no-wipe option (and then activate with --integrity-recalculate)."), + action_argv[0], ARG_STR(OPT_DATA_DEVICE_ID)); + else + r = asprintf(&msg, _("This will overwrite data on %s irrevocably."), action_argv[0]); + if (r == -1) { + r = -ENOMEM; + goto out; + } + + r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL; + free(msg); + if (r < 0) + goto out; + } + + r = tools_detect_signatures(action_argv[0], PRB_FILTER_NONE, &signatures, ARG_SET(OPT_BATCH_MODE_ID)); + if (r < 0) + goto out; + + /* Signature candidates found */ + if (signatures && ((r = tools_wipe_all_signatures(action_argv[0], true, false)) < 0)) + goto out; + + if (ARG_SET(OPT_INTEGRITY_LEGACY_PADDING_ID)) + crypt_set_compatibility(cd, CRYPT_COMPAT_LEGACY_INTEGRITY_PADDING); + + if (ARG_SET(OPT_INTEGRITY_LEGACY_HMAC_ID)) + crypt_set_compatibility(cd, CRYPT_COMPAT_LEGACY_INTEGRITY_HMAC); + + r = crypt_format(cd, CRYPT_INTEGRITY, NULL, NULL, NULL, NULL, 0, ¶ms); + if (r < 0) /* FIXME: call wipe signatures again */ + goto out; + + if (!ARG_SET(OPT_BATCH_MODE_ID) && !crypt_get_integrity_info(cd, ¶ms2)) + log_std(_("Formatted with tag size %u, internal integrity %s.\n"), + params2.tag_size, params2.integrity); + + if (!ARG_SET(OPT_NO_WIPE_ID)) + r = _wipe_data_device(cd, integrity_key); +out: + crypt_safe_free(integrity_key); + crypt_safe_free(CONST_CAST(void*)params.journal_integrity_key); + crypt_safe_free(CONST_CAST(void*)params.journal_crypt_key); + crypt_free(cd); + return r; +} + +static int action_resize(void) +{ + int r; + struct crypt_device *cd = NULL; + struct crypt_active_device cad; + uint64_t new_dev_size = 0; + uint64_t old_dev_size; + char path[PATH_MAX]; + char *backing_file = NULL; + struct tools_progress_params prog_parms = { + .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID), + .batch_mode = ARG_SET(OPT_BATCH_MODE_ID), + .json_output = ARG_SET(OPT_PROGRESS_JSON_ID), + .interrupt_message = _("\nWipe interrupted."), + .device = tools_get_device_name(crypt_get_device_name(cd), &backing_file) + }; + + if (ARG_SET(OPT_DEVICE_SIZE_ID)) + new_dev_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE; + else if (ARG_SET(OPT_SIZE_ID)) + new_dev_size = ARG_UINT64(OPT_SIZE_ID); + + r = crypt_init_by_name_and_header(&cd, action_argv[0], NULL); + if (r) + goto out; + + r = crypt_get_active_device(cd, action_argv[0], &cad); + if (r) + goto out; + old_dev_size = cad.size; + + r = snprintf(path, sizeof(path), "%s/%s", crypt_get_dir(), action_argv[0]); + if (r < 0) + goto out; + r = crypt_resize(cd, action_argv[0], new_dev_size); + if (r) + goto out; + + if (!new_dev_size) { + r = crypt_get_active_device(cd, action_argv[0], &cad); + if (r) + goto out; + new_dev_size = cad.size; + } + + if (new_dev_size > old_dev_size) { + if (ARG_SET(OPT_WIPE_ID)) { + if (ARG_SET(OPT_BATCH_MODE_ID)) + log_dbg("Wiping the end of the resized device"); + else + log_std(_("Wiping device to initialize integrity checksum.\n" + "You can interrupt this by pressing CTRL+c " + "(rest of not wiped device will contain invalid checksum).\n")); + + set_int_handler(0); + r = crypt_wipe(cd, path, CRYPT_WIPE_ZERO, old_dev_size * SECTOR_SIZE, + (new_dev_size - old_dev_size) * SECTOR_SIZE, DEFAULT_WIPE_BLOCK, + 0, &tools_progress, &prog_parms); + set_int_block(0); + } else { + log_dbg("Setting recalculate flag"); + r = crypt_activate_by_volume_key(cd, action_argv[0], NULL, 0, CRYPT_ACTIVATE_REFRESH | CRYPT_ACTIVATE_RECALCULATE); + + if (r == -ENOTSUP) + log_err(_("Setting recalculate flag is not supported, you may consider using --wipe instead.")); + } + } +out: + if (backing_file) + free(backing_file); + crypt_free(cd); + return r; +} + +static int action_open(void) +{ + struct crypt_device *cd = NULL; + struct crypt_params_integrity params = { + /* in bitmap mode we have to overload these values... */ + .journal_watermark = ARG_SET(OPT_INTEGRITY_BITMAP_MODE_ID) ? ARG_UINT32(OPT_BITMAP_SECTORS_PER_BIT_ID) : ARG_UINT32(OPT_JOURNAL_WATERMARK_ID), + .journal_commit_time = ARG_SET(OPT_INTEGRITY_BITMAP_MODE_ID) ? ARG_UINT32(OPT_BITMAP_FLUSH_TIME_ID) : ARG_UINT32(OPT_JOURNAL_COMMIT_TIME_ID), + .buffer_sectors = ARG_UINT32(OPT_BUFFER_SECTORS_ID), + }; + uint32_t activate_flags = 0; + char integrity[MAX_CIPHER_LEN], journal_integrity[MAX_CIPHER_LEN], journal_crypt[MAX_CIPHER_LEN]; + char *integrity_key = NULL; + int r; + + r = crypt_parse_hash_integrity_mode(ARG_STR(OPT_INTEGRITY_ID), integrity); + if (r < 0) { + log_err(_("No known integrity specification pattern detected.")); + return r; + } + params.integrity = integrity; + + if (ARG_SET(OPT_JOURNAL_INTEGRITY_ID)) { + r = crypt_parse_hash_integrity_mode(ARG_STR(OPT_JOURNAL_INTEGRITY_ID), journal_integrity); + if (r < 0) { + log_err(_("No known integrity specification pattern detected.")); + return r; + + } + params.journal_integrity = journal_integrity; + } + + if (ARG_SET(OPT_JOURNAL_CRYPT_ID)) { + r = crypt_parse_hash_integrity_mode(ARG_STR(OPT_JOURNAL_CRYPT_ID), journal_crypt); + if (r < 0) { + log_err(_("No known integrity specification pattern detected.")); + return r; + } + params.journal_crypt = journal_crypt; + } + + if (ARG_SET(OPT_INTEGRITY_NO_JOURNAL_ID) || ARG_SET(OPT_INTEGRITY_BITMAP_MODE_ID)) + activate_flags |= CRYPT_ACTIVATE_NO_JOURNAL; + if (ARG_SET(OPT_INTEGRITY_RECOVERY_MODE_ID)) + activate_flags |= CRYPT_ACTIVATE_RECOVERY; + if (ARG_SET(OPT_INTEGRITY_BITMAP_MODE_ID)) + activate_flags |= CRYPT_ACTIVATE_NO_JOURNAL_BITMAP; + + if (ARG_SET(OPT_INTEGRITY_RECALCULATE_ID) || ARG_SET(OPT_INTEGRITY_LEGACY_RECALC_ID)) + activate_flags |= CRYPT_ACTIVATE_RECALCULATE; + + if (ARG_SET(OPT_INTEGRITY_RECALCULATE_RESET_ID)) + activate_flags |= CRYPT_ACTIVATE_RECALCULATE_RESET; + + if (ARG_SET(OPT_ALLOW_DISCARDS_ID)) + activate_flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS; + + r = _read_keys(&integrity_key, ¶ms); + if (r) + goto out; + + if ((r = crypt_init_data_device(&cd, action_argv[0], ARG_STR(OPT_DATA_DEVICE_ID)))) + goto out; + + r = crypt_load(cd, CRYPT_INTEGRITY, ¶ms); + if (r) { + log_err(_("Device %s is not a valid INTEGRITY device."), action_argv[0]); + goto out; + } + + if (ARG_SET(OPT_INTEGRITY_LEGACY_RECALC_ID)) + crypt_set_compatibility(cd, CRYPT_COMPAT_LEGACY_INTEGRITY_RECALC); + + r = crypt_activate_by_volume_key(cd, action_argv[1], integrity_key, + ARG_UINT32(OPT_INTEGRITY_KEY_SIZE_ID), activate_flags); +out: + crypt_safe_free(integrity_key); + crypt_safe_free(CONST_CAST(void*)params.journal_integrity_key); + crypt_safe_free(CONST_CAST(void*)params.journal_crypt_key); + crypt_free(cd); + return r; +} + +static int action_close(void) +{ + struct crypt_device *cd = NULL; + crypt_status_info ci; + uint32_t flags = 0; + int r; + + if (ARG_SET(OPT_DEFERRED_ID)) + flags |= CRYPT_DEACTIVATE_DEFERRED; + if (ARG_SET(OPT_CANCEL_DEFERRED_ID)) + flags |= CRYPT_DEACTIVATE_DEFERRED_CANCEL; + + r = crypt_init_by_name(&cd, action_argv[0]); + if (r == 0) + r = crypt_deactivate_by_name(cd, action_argv[0], flags); + + if (!r && ARG_SET(OPT_DEFERRED_ID)) { + ci = crypt_status(cd, action_argv[0]); + if (ci == CRYPT_ACTIVE || ci == CRYPT_BUSY) + log_std(_("Device %s is still active and scheduled for deferred removal.\n"), + action_argv[0]); + } + + crypt_free(cd); + return r; +} + +static int action_status(void) +{ + crypt_status_info ci; + struct crypt_active_device cad; + struct crypt_params_integrity ip = {}; + struct crypt_device *cd = NULL; + char *backing_file; + const char *device, *metadata_device; + int path = 0, r = 0; + + /* perhaps a path, not a dm device name */ + if (strchr(action_argv[0], '/')) + path = 1; + + ci = crypt_status(NULL, action_argv[0]); + switch (ci) { + case CRYPT_INVALID: + r = -EINVAL; + break; + case CRYPT_INACTIVE: + if (path) + log_std("%s is inactive.\n", action_argv[0]); + else + log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]); + r = -ENODEV; + break; + case CRYPT_ACTIVE: + case CRYPT_BUSY: + if (path) + log_std("%s is active%s.\n", action_argv[0], + ci == CRYPT_BUSY ? " and is in use" : ""); + else + log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0], + ci == CRYPT_BUSY ? " and is in use" : ""); + + r = crypt_init_by_name_and_header(&cd, action_argv[0], NULL); + if (r < 0) + goto out; + + log_std(" type: %s\n", crypt_get_type(cd) ?: "n/a"); + + r = crypt_get_active_device(cd, action_argv[0], &cad); + if (r < 0) + goto out; + + /* Print only INTEGRITY (and LUKS2 with integrity) info */ + r = crypt_get_integrity_info(cd, &ip); + if (r < 0) + goto out; + + log_std(" tag size: %u\n", ip.tag_size); + log_std(" integrity: %s\n", ip.integrity ?: "(none)"); + device = crypt_get_device_name(cd); + metadata_device = crypt_get_metadata_device_name(cd); + log_std(" device: %s%s\n", device, metadata_device ? " (detached)" : ""); + if ((backing_file = crypt_loop_backing_file(device))) { + log_std(" loop: %s\n", backing_file); + free(backing_file); + } + if (metadata_device) { + log_std(" metadata device: %s\n", metadata_device); + if ((backing_file = crypt_loop_backing_file(metadata_device))) { + log_std(" loop: %s\n", backing_file); + free(backing_file); + } + } + log_std(" sector size: %u bytes\n", crypt_get_sector_size(cd)); + log_std(" interleave sectors: %u\n", ip.interleave_sectors); + log_std(" size: %" PRIu64 " sectors\n", cad.size); + log_std(" mode: %s%s\n", + cad.flags & CRYPT_ACTIVATE_READONLY ? "readonly" : "read/write", + cad.flags & CRYPT_ACTIVATE_RECOVERY ? " recovery" : ""); + log_std(" failures: %" PRIu64 "\n", + crypt_get_active_integrity_failures(cd, action_argv[0])); + if (cad.flags & CRYPT_ACTIVATE_NO_JOURNAL_BITMAP) { + log_std(" bitmap 512-byte sectors per bit: %u\n", ip.journal_watermark); + log_std(" bitmap flush interval: %u ms\n", ip.journal_commit_time); + } if (cad.flags & CRYPT_ACTIVATE_NO_JOURNAL) { + log_std(" journal: not active\n"); + } else { + log_std(" journal size: %" PRIu64 " bytes\n", ip.journal_size); + log_std(" journal watermark: %u%%\n", ip.journal_watermark); + log_std(" journal commit time: %u ms\n", ip.journal_commit_time); + if (ip.journal_integrity) + log_std(" journal integrity MAC: %s\n", ip.journal_integrity); + if (ip.journal_crypt) + log_std(" journal encryption: %s\n", ip.journal_crypt); + } + if (cad.flags & (CRYPT_ACTIVATE_ALLOW_DISCARDS)) + log_std(" flags: %s\n", + (cad.flags & CRYPT_ACTIVATE_ALLOW_DISCARDS) ? "discards " : ""); + } +out: + crypt_free(cd); + if (r == -ENOTSUP) + r = 0; + return r; + return -EINVAL; +} + +static int action_dump(void) +{ + struct crypt_device *cd = NULL; + struct crypt_params_integrity params = {}; + int r; + + if ((r = crypt_init(&cd, action_argv[0]))) + return r; + + r = crypt_load(cd, CRYPT_INTEGRITY, ¶ms); + if (!r) + crypt_dump(cd); + else + log_err(_("Device %s is not a valid INTEGRITY device."), action_argv[0]); + + crypt_free(cd); + return r; +} + +static struct action_type { + const char *type; + int (*handler)(void); + int required_action_argc; + const char *arg_desc; + const char *desc; +} action_types[] = { + { FORMAT_ACTION,action_format, 1, N_("<integrity_device>"),N_("format device") }, + { OPEN_ACTION, action_open, 2, N_("<integrity_device> <name>"),N_("open device as <name>") }, + { CLOSE_ACTION, action_close, 1, N_("<name>"),N_("close device (remove mapping)") }, + { STATUS_ACTION,action_status, 1, N_("<name>"),N_("show active device status") }, + { DUMP_ACTION, action_dump, 1, N_("<integrity_device>"),N_("show on-disk information") }, + { RESIZE_ACTION,action_resize, 1, N_("<name>"), N_("resize active device") }, + {} +}; + +static void help(poptContext popt_context, + enum poptCallbackReason reason __attribute__((unused)), + struct poptOption *key, + const char *arg __attribute__((unused)), + void *data __attribute__((unused))) +{ + struct action_type *action; + + if (key->shortName == '?') { + tools_package_version(PACKAGE_INTEGRITY, false); + poptPrintHelp(popt_context, stdout, 0); + log_std(_("\n" + "<action> is one of:\n")); + for(action = action_types; action->type; action++) + log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc)); + log_std(_("\n" + "<name> is the device to create under %s\n" + "<integrity_device> is the device containing data with integrity tags\n"), + crypt_get_dir()); + + log_std(_("\nDefault compiled-in dm-integrity parameters:\n" + "\tChecksum algorithm: %s\n" + "\tMaximum keyfile size: %dkB\n"), + DEFAULT_ALG_NAME, DEFAULT_INTEGRITY_KEYFILE_SIZE_MAXKB); + tools_cleanup(); + poptFreeContext(popt_context); + exit(EXIT_SUCCESS); + } else if (key->shortName == 'V') { + tools_package_version(PACKAGE_INTEGRITY, false); + tools_cleanup(); + poptFreeContext(popt_context); + exit(EXIT_SUCCESS); + } else + usage(popt_context, EXIT_SUCCESS, NULL, NULL); +} + +static int run_action(struct action_type *action) +{ + int r; + + log_dbg("Running command %s.", action->type); + + r = action->handler(); + + show_status(r); + return translate_errno(r); +} + +static bool needs_size_conversion(unsigned int arg_id) +{ + return (arg_id == OPT_JOURNAL_SIZE_ID || arg_id == OPT_DEVICE_SIZE_ID); +} + +static void basic_options_cb(poptContext popt_context, + enum poptCallbackReason reason __attribute__((unused)), + struct poptOption *key, + const char *arg, + void *data __attribute__((unused))) +{ + char msg[256]; + + tools_parse_arg_value(popt_context, tool_core_args[key->val].type, tool_core_args + key->val, arg, key->val, needs_size_conversion); + + /* special cases additional handling */ + switch (key->val) { + case OPT_DEBUG_ID: + log_parms.debug = true; + /* fall through */ + case OPT_VERBOSE_ID: + log_parms.verbose = true; + break; + case OPT_INTEGRITY_KEY_SIZE_ID: + /* fall through */ + case OPT_JOURNAL_INTEGRITY_KEY_SIZE_ID: + /* fall through */ + case OPT_JOURNAL_CRYPT_KEY_SIZE_ID: + if (ARG_UINT32(key->val) > (DEFAULT_INTEGRITY_KEYFILE_SIZE_MAXKB * 1024)) { + if (snprintf(msg, sizeof(msg), _("Invalid --%s size. Maximum is %u bytes."), + key->longName, DEFAULT_INTEGRITY_KEYFILE_SIZE_MAXKB * 1024) < 0) + msg[0] = '\0'; + usage(popt_context, EXIT_FAILURE, msg, + poptGetInvocationName(popt_context)); + } + } +} + +int main(int argc, const char **argv) +{ + static const char *null_action_argv[] = {NULL}; + static struct poptOption popt_help_options[] = { + { NULL, '\0', POPT_ARG_CALLBACK, help, 0, NULL, NULL }, + { "help", '?', POPT_ARG_NONE, NULL, 0, N_("Show this help message"), NULL }, + { "usage", '\0', POPT_ARG_NONE, NULL, 0, N_("Display brief usage"), NULL }, + { "version",'V', POPT_ARG_NONE, NULL, 0, N_("Print package version"), NULL }, + POPT_TABLEEND + }; + static struct poptOption popt_basic_options[] = { + { NULL, '\0', POPT_ARG_CALLBACK, basic_options_cb, 0, NULL, NULL }, +#define ARG(A, B, C, D, E, F, G, H) { A, B, C, NULL, A ## _ID, D, E }, +#include "integritysetup_arg_list.h" +#undef ARG + POPT_TABLEEND + }; + static struct poptOption popt_options[] = { + { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL }, + { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_basic_options, 0, NULL, NULL }, + POPT_TABLEEND + }; + poptContext popt_context; + struct action_type *action; + const char *aname; + int r; + + crypt_set_log_callback(NULL, tool_log, &log_parms); + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + popt_context = poptGetContext("integrity", argc, argv, popt_options, 0); + poptSetOtherOptionHelp(popt_context, + _("[OPTION...] <action> <action-specific>")); + + + while ((r = poptGetNextOpt(popt_context)) >= 0) { + } + + if (r < -1) + usage(popt_context, EXIT_FAILURE, poptStrerror(r), + poptBadOption(popt_context, POPT_BADOPTION_NOALIAS)); + + if (!(aname = poptGetArg(popt_context))) + usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."), + poptGetInvocationName(popt_context)); + + action_argc = 0; + action_argv = poptGetArgs(popt_context); + /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */ + if (!action_argv) + action_argv = null_action_argv; + + /* Count args, somewhat unnice, change? */ + while (action_argv[action_argc] != NULL) + action_argc++; + + /* Handle aliases */ + if (!strcmp(aname, "create") && action_argc > 1) { + /* create command had historically switched arguments */ + if (action_argv[0] && action_argv[1]) { + const char *tmp = action_argv[0]; + action_argv[0] = action_argv[1]; + action_argv[1] = tmp; + } + aname = "open"; + } else if (!strcmp(aname, "remove")) { + aname = "close"; + } + + for (action = action_types; action->type; action++) + if (strcmp(action->type, aname) == 0) + break; + + if (!action->type) + usage(popt_context, EXIT_FAILURE, _("Unknown action."), + poptGetInvocationName(popt_context)); + + if (action_argc < action->required_action_argc) { + char buf[128]; + if (snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc) < 0) + buf[0] ='\0'; + usage(popt_context, EXIT_FAILURE, buf, + poptGetInvocationName(popt_context)); + } + + tools_check_args(action->type, tool_core_args, ARRAY_SIZE(tool_core_args), popt_context); + + if (ARG_SET(OPT_INTEGRITY_KEY_FILE_ID) != ARG_SET(OPT_INTEGRITY_KEY_SIZE_ID)) + usage(popt_context, EXIT_FAILURE, _("Both key file and key size options must be specified."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_JOURNAL_INTEGRITY_KEY_FILE_ID) != ARG_SET(OPT_JOURNAL_INTEGRITY_KEY_SIZE_ID)) + usage(popt_context, EXIT_FAILURE, _("Both journal integrity key file and key size options must be specified."), + poptGetInvocationName(popt_context)); + if (!ARG_SET(OPT_JOURNAL_INTEGRITY_ID) && ARG_SET(OPT_JOURNAL_INTEGRITY_KEY_FILE_ID)) + usage(popt_context, EXIT_FAILURE, _("Journal integrity algorithm must be specified if journal integrity key is used."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_JOURNAL_CRYPT_KEY_FILE_ID) != ARG_SET(OPT_JOURNAL_CRYPT_KEY_SIZE_ID)) + usage(popt_context, EXIT_FAILURE, _("Both journal encryption key file and key size options must be specified."), + poptGetInvocationName(popt_context)); + if (!ARG_SET(OPT_JOURNAL_CRYPT_ID) && ARG_SET(OPT_JOURNAL_CRYPT_KEY_FILE_ID)) + usage(popt_context, EXIT_FAILURE, _("Journal encryption algorithm must be specified if journal encryption key is used."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_INTEGRITY_RECOVERY_MODE_ID) && ARG_SET(OPT_INTEGRITY_BITMAP_MODE_ID)) + usage(popt_context, EXIT_FAILURE, _("Recovery and bitmap mode options are mutually exclusive."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_INTEGRITY_BITMAP_MODE_ID) && + (ARG_SET(OPT_JOURNAL_INTEGRITY_KEY_FILE_ID) || + ARG_SET(OPT_JOURNAL_CRYPT_ID) || ARG_SET(OPT_JOURNAL_WATERMARK_ID) || + ARG_SET(OPT_JOURNAL_COMMIT_TIME_ID))) + usage(popt_context, EXIT_FAILURE, _("Journal options cannot be used in bitmap mode."), + poptGetInvocationName(popt_context)); + + if (!ARG_SET(OPT_INTEGRITY_BITMAP_MODE_ID) && + (ARG_SET(OPT_BITMAP_FLUSH_TIME_ID) || ARG_SET(OPT_BITMAP_SECTORS_PER_BIT_ID))) + usage(popt_context, EXIT_FAILURE, _("Bitmap options can be used only in bitmap mode."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_CANCEL_DEFERRED_ID) && ARG_SET(OPT_DEFERRED_ID)) + usage(popt_context, EXIT_FAILURE, + _("Options --cancel-deferred and --deferred cannot be used at the same time."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_DEBUG_ID)) { + crypt_set_debug_level(CRYPT_DEBUG_ALL); + dbg_version_and_cmd(argc, argv); + } + + r = run_action(action); + tools_cleanup(); + poptFreeContext(popt_context); + return r; +} diff --git a/src/integritysetup_arg_list.h b/src/integritysetup_arg_list.h new file mode 100644 index 0000000..39f2906 --- /dev/null +++ b/src/integritysetup_arg_list.h @@ -0,0 +1,100 @@ +/* + * Integritysetup command line arguments list + * + * Copyright (C) 2020-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2020-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/* long name, short name, popt type, help description, units, internal argument type, default value */ + +ARG(OPT_ALLOW_DISCARDS, '\0', POPT_ARG_NONE, N_("Allow discards (aka TRIM) requests for device"), NULL, CRYPT_ARG_BOOL, {}, OPT_ALLOW_DISCARDS_ACTIONS) + +ARG(OPT_BATCH_MODE, 'q', POPT_ARG_NONE, N_("Do not ask for confirmation"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_BUFFER_SECTORS, '\0', POPT_ARG_STRING, N_("Buffers size"), N_("SECTORS"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_BITMAP_FLUSH_TIME, '\0', POPT_ARG_STRING, N_("Bitmap mode flush time"), N_("ms"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_BITMAP_SECTORS_PER_BIT, '\0', POPT_ARG_STRING, N_("Number of 512-byte sectors per bit (bitmap mode)."), "INT", CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_CANCEL_DEFERRED, '\0', POPT_ARG_NONE, N_("Cancel a previously set deferred device removal"), NULL, CRYPT_ARG_BOOL, {}, OPT_DEFERRED_ACTIONS) + +ARG(OPT_DATA_DEVICE, '\0', POPT_ARG_STRING, N_("Path to data device (if separated)"), N_("path"), CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_DEBUG, '\0', POPT_ARG_NONE, N_("Show debug messages"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DEFERRED, '\0', POPT_ARG_NONE, N_("Device removal is deferred until the last user closes it"), NULL, CRYPT_ARG_BOOL, {}, OPT_DEFERRED_ACTIONS) + +ARG(OPT_INTEGRITY, 'I', POPT_ARG_STRING, N_("Data integrity algorithm"), NULL, CRYPT_ARG_STRING, { .str_value = CONST_CAST(void *)DEFAULT_ALG_NAME }, {}) + +ARG(OPT_INTEGRITY_KEY_FILE, '\0', POPT_ARG_STRING, N_("Read the integrity key from a file"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_INTEGRITY_KEY_SIZE, '\0', POPT_ARG_STRING, N_("The size of the data integrity key"), N_("BITS"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_INTEGRITY_LEGACY_PADDING, '\0', POPT_ARG_NONE, N_("Use inefficient legacy padding (old kernels)"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_INTEGRITY_LEGACY_HMAC, '\0', POPT_ARG_NONE, N_("Do not protect superblock with HMAC (old kernels)"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_INTEGRITY_LEGACY_RECALC, '\0', POPT_ARG_NONE, N_("Allow recalculating of volumes with HMAC keys (old kernels)"), NULL, CRYPT_ARG_BOOL, {}, OPT_INTEGRITY_RECALCULATE_ACTIONS) + +ARG(OPT_INTEGRITY_NO_JOURNAL, 'D', POPT_ARG_NONE, N_("Disable journal for integrity device"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_INTERLEAVE_SECTORS, '\0', POPT_ARG_STRING, N_("Interleave sectors"), N_("SECTORS"), CRYPT_ARG_UINT32, {}, OPT_INTERLEAVE_SECTORS_ACTIONS) + +ARG(OPT_JOURNAL_COMMIT_TIME, '\0', POPT_ARG_STRING, N_("Journal commit time"), N_("ms"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_JOURNAL_INTEGRITY, '\0', POPT_ARG_STRING, N_("Journal integrity algorithm"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_JOURNAL_INTEGRITY_KEY_SIZE, '\0', POPT_ARG_STRING, N_("The size of the journal integrity key"), N_("BITS"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_JOURNAL_INTEGRITY_KEY_FILE, '\0', POPT_ARG_STRING, N_("Read the journal integrity key from a file"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_JOURNAL_CRYPT, '\0', POPT_ARG_STRING, N_("Journal encryption algorithm"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_JOURNAL_CRYPT_KEY_FILE, '\0', POPT_ARG_STRING, N_("Read the journal encryption key from a file"), NULL, CRYPT_ARG_STRING,{}, {}) + +ARG(OPT_JOURNAL_CRYPT_KEY_SIZE, '\0', POPT_ARG_STRING, N_("The size of the journal encryption key"), N_("BITS"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_JOURNAL_SIZE, 'j', POPT_ARG_STRING, N_("Journal size"), N_("bytes"), CRYPT_ARG_UINT64, {}, OPT_JOURNAL_SIZE_ACTIONS) + +ARG(OPT_JOURNAL_WATERMARK, '\0', POPT_ARG_STRING, N_("Journal watermark"), N_("percent"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_NO_WIPE, '\0', POPT_ARG_NONE, N_("Do not wipe device after format"), NULL, CRYPT_ARG_BOOL, {}, OPT_NO_WIPE_ACTIONS) + +ARG(OPT_WIPE, '\0', POPT_ARG_NONE, N_("Wipe the end of the device after resize"), NULL, CRYPT_ARG_BOOL, {}, OPT_WIPE_ACTIONS) + +ARG(OPT_PROGRESS_FREQUENCY, '\0', POPT_ARG_STRING, N_("Progress line update (in seconds)"), N_("secs"), CRYPT_ARG_UINT32, {}, {}) + +ARG(OPT_PROGRESS_JSON, '\0', POPT_ARG_NONE, N_("Print wipe progress data in json format (suitable for machine processing)"), NULL, CRYPT_ARG_BOOL, {}, OPT_PROGRESS_JSON_ACTIONS) + +ARG(OPT_INTEGRITY_BITMAP_MODE, 'B', POPT_ARG_NONE, N_("Use bitmap to track changes and disable journal for integrity device"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_INTEGRITY_RECALCULATE, '\0', POPT_ARG_NONE, N_("Recalculate initial tags automatically."), NULL, CRYPT_ARG_BOOL, {}, OPT_INTEGRITY_RECALCULATE_ACTIONS) + +ARG(OPT_INTEGRITY_RECALCULATE_RESET, '\0', POPT_ARG_NONE, N_("Reset automatic recalculate position."), NULL, CRYPT_ARG_BOOL, {}, OPT_INTEGRITY_RECALCULATE_ACTIONS) + +ARG(OPT_INTEGRITY_RECOVERY_MODE, 'R', POPT_ARG_NONE, N_("Recovery mode (no journal, no tag checking)"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_SECTOR_SIZE, 's', POPT_ARG_STRING, N_("Sector size"), N_("bytes"), CRYPT_ARG_UINT32, { .u32_value = 512 }, OPT_SECTOR_SIZE_ACTIONS) + +ARG(OPT_TAG_SIZE, 't', POPT_ARG_STRING, N_("Tag size (per-sector)"), N_("bytes"), CRYPT_ARG_UINT32, {}, OPT_TAG_SIZE_ACTIONS) + +ARG(OPT_VERBOSE, 'v', POPT_ARG_NONE, N_("Shows more detailed error messages"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DEVICE_SIZE, '\0', POPT_ARG_STRING, N_("Use only specified device size (ignore rest of device). DANGEROUS!"), N_("bytes"), CRYPT_ARG_UINT64, {}, OPT_DEVICE_SIZE_ACTIONS) + +ARG(OPT_SIZE, 'b', POPT_ARG_STRING, N_("The size of the device"), N_("SECTORS"), CRYPT_ARG_UINT64, {}, OPT_SIZE_ACTIONS) diff --git a/src/integritysetup_args.h b/src/integritysetup_args.h new file mode 100644 index 0000000..8241008 --- /dev/null +++ b/src/integritysetup_args.h @@ -0,0 +1,61 @@ +/* + * Command line arguments helpers + * + * Copyright (C) 2020-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2020-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef INTEGRITYSETUP_ARGS_H +#define INTEGRITYSETUP_ARGS_H + +#include "utils_arg_names.h" +#include "utils_arg_macros.h" + +#define FORMAT_ACTION "format" +#define OPEN_ACTION "open" +#define CLOSE_ACTION "close" +#define STATUS_ACTION "status" +#define DUMP_ACTION "dump" +#define RESIZE_ACTION "resize" + +#define OPT_ALLOW_DISCARDS_ACTIONS { OPEN_ACTION } +#define OPT_DEFERRED_ACTIONS { CLOSE_ACTION } +#define OPT_INTEGRITY_RECALCULATE_ACTIONS { OPEN_ACTION } +#define OPT_JOURNAL_SIZE_ACTIONS { FORMAT_ACTION } +#define OPT_NO_WIPE_ACTIONS { FORMAT_ACTION } +#define OPT_INTERLEAVE_SECTORS_ACTIONS { FORMAT_ACTION } +#define OPT_PROGRESS_JSON_ACTIONS { FORMAT_ACTION, RESIZE_ACTION } +#define OPT_SECTOR_SIZE_ACTIONS { FORMAT_ACTION } +#define OPT_TAG_SIZE_ACTIONS { FORMAT_ACTION } +#define OPT_DEVICE_SIZE_ACTIONS { RESIZE_ACTION } +#define OPT_SIZE_ACTIONS { RESIZE_ACTION } +#define OPT_WIPE_ACTIONS { RESIZE_ACTION } + +enum { +OPT_UNUSED_ID = 0, +#define ARG(A, B, C, D, E, F, G, H) A ## _ID, +#include "integritysetup_arg_list.h" +#undef ARG +}; + +static struct tools_arg tool_core_args[] = { { NULL, false, CRYPT_ARG_BOOL }, // UNUSED +#define ARG(A, B, C, D, E, F, G, H) { A, false, F, G, H }, +#include "integritysetup_arg_list.h" +#undef ARG +}; + +#endif diff --git a/src/utils_arg_macros.h b/src/utils_arg_macros.h new file mode 100644 index 0000000..901b3f4 --- /dev/null +++ b/src/utils_arg_macros.h @@ -0,0 +1,103 @@ +/* + * Command line arguments parsing helpers + * + * Copyright (C) 2020-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2020-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef UTILS_ARG_MACROS_H +#define UTILS_ARG_MACROS_H + +#include <assert.h> + +#define ARG_SET(X) !!tool_core_args[(X)].set + +#define ARG_STR(X) ({ \ + assert(tool_core_args[(X)].type == CRYPT_ARG_STRING); \ + tool_core_args[(X)].u.str_value; \ +}) + +#define ARG_INT32(X) ({ \ + assert(tool_core_args[(X)].type == CRYPT_ARG_INT32); \ + tool_core_args[(X)].u.i32_value; \ +}) + +#define ARG_UINT32(X) ({ \ + assert(tool_core_args[(X)].type == CRYPT_ARG_UINT32); \ + tool_core_args[(X)].u.u32_value; \ +}) + +#define ARG_INT64(X) ({ \ + assert(tool_core_args[(X)].type == CRYPT_ARG_INT64); \ + tool_core_args[(X)].u.i64_value; \ +}) + +#define ARG_UINT64(X) ({ \ + assert(tool_core_args[(X)].type == CRYPT_ARG_UINT64); \ + tool_core_args[(X)].u.u64_value; \ +}) + +#define ARG_SET_TRUE(X) do { \ + tool_core_args[(X)].set = true; \ +} while (0) + +#define ARG_SET_STR(X, Y) \ +do { \ + char *str; \ + assert(tool_core_args[(X)].set == false && tool_core_args[(X)].type == CRYPT_ARG_STRING); \ + str = (Y); \ + assert(str != NULL); \ + tool_core_args[(X)].u.str_value = str; \ + tool_core_args[(X)].set = true; \ +} while (0) + +#define ARG_SET_INT32(X, Y) \ +do { \ + assert(tool_core_args[(X)].set == false && tool_core_args[(X)].type == CRYPT_ARG_INT32); \ + tool_core_args[(X)].u.i32_value = (Y); \ + tool_core_args[(X)].set = true; \ +} while (0) + +#define ARG_SET_UINT32(X, Y) \ +do { \ + assert(tool_core_args[(X)].set == false && tool_core_args[(X)].type == CRYPT_ARG_UINT32); \ + tool_core_args[(X)].u.u32_value = (Y); \ + tool_core_args[(X)].set = true; \ +} while (0) + +#define ARG_SET_INT64(X, Y) \ +do { \ + assert(tool_core_args[(X)].set == false && tool_core_args[(X)].type == CRYPT_ARG_INT64); \ + tool_core_args[(X)].u.i64_value = (Y); \ + tool_core_args[(X)].set = true; \ +} while (0) + +#define ARG_SET_UINT64(X, Y) \ +do { \ + assert(tool_core_args[(X)].set == false && tool_core_args[(X)].type == CRYPT_ARG_UINT64); \ + tool_core_args[(X)].u.u64_value = (Y); \ + tool_core_args[(X)].set = true; \ +} while (0) + + +#define ARG_INIT_ALIAS(X) \ +do { \ + assert(tool_core_args[(X)].type == CRYPT_ARG_ALIAS); \ + tool_core_args[(X)].u.o.ptr = &tool_core_args[tool_core_args[(X)].u.o.id]; \ +} while (0) + +#endif diff --git a/src/utils_arg_names.h b/src/utils_arg_names.h new file mode 100644 index 0000000..66a59e8 --- /dev/null +++ b/src/utils_arg_names.h @@ -0,0 +1,173 @@ +/* + * Command line arguments name list + * + * Copyright (C) 2020-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2020-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef UTILS_ARG_NAMES_H +#define UTILS_ARG_NAMES_H + +#define OPT_ACTIVE_NAME "active-name" +#define OPT_ALIGN_PAYLOAD "align-payload" +#define OPT_ALLOW_DISCARDS "allow-discards" +#define OPT_BATCH_MODE "batch-mode" +#define OPT_BITMAP_FLUSH_TIME "bitmap-flush-time" +#define OPT_BITMAP_SECTORS_PER_BIT "bitmap-sectors-per-bit" +#define OPT_BLOCK_SIZE "block-size" +#define OPT_BUFFER_SECTORS "buffer-sectors" +#define OPT_CANCEL_DEFERRED "cancel-deferred" +#define OPT_CHECK_AT_MOST_ONCE "check-at-most-once" +#define OPT_CIPHER "cipher" +#define OPT_DATA_BLOCK_SIZE "data-block-size" +#define OPT_DATA_BLOCKS "data-blocks" +#define OPT_DATA_DEVICE "data-device" +#define OPT_DEBUG "debug" +#define OPT_DEBUG_JSON "debug-json" +#define OPT_DEFERRED "deferred" +#define OPT_DEVICE_SIZE "device-size" +#define OPT_DECRYPT "decrypt" +#define OPT_DISABLE_EXTERNAL_TOKENS "disable-external-tokens" +#define OPT_DISABLE_KEYRING "disable-keyring" +#define OPT_DISABLE_LOCKS "disable-locks" +#define OPT_DISABLE_VERACRYPT "disable-veracrypt" +#define OPT_DUMP_JSON "dump-json-metadata" +#define OPT_DUMP_MASTER_KEY "dump-master-key" +#define OPT_DUMP_VOLUME_KEY "dump-volume-key" +#define OPT_ENCRYPT "encrypt" +#define OPT_FEC_DEVICE "fec-device" +#define OPT_FEC_OFFSET "fec-offset" +#define OPT_FEC_ROOTS "fec-roots" +#define OPT_FORCE_PASSWORD "force-password" +#define OPT_FORCE_OFFLINE_REENCRYPT "force-offline-reencrypt" +#define OPT_FORMAT "format" +#define OPT_HASH "hash" +#define OPT_HASH_BLOCK_SIZE "hash-block-size" +#define OPT_HASH_OFFSET "hash-offset" +#define OPT_HEADER "header" +#define OPT_HEADER_BACKUP_FILE "header-backup-file" +#define OPT_HOTZONE_SIZE "hotzone-size" +#define OPT_IGNORE_CORRUPTION "ignore-corruption" +#define OPT_IGNORE_ZERO_BLOCKS "ignore-zero-blocks" +#define OPT_INIT_ONLY "init-only" +#define OPT_INTEGRITY "integrity" +#define OPT_INTEGRITY_BITMAP_MODE "integrity-bitmap-mode" +#define OPT_INTEGRITY_KEY_FILE "integrity-key-file" +#define OPT_INTEGRITY_KEY_SIZE "integrity-key-size" +#define OPT_INTEGRITY_LEGACY_PADDING "integrity-legacy-padding" +#define OPT_INTEGRITY_LEGACY_HMAC "integrity-legacy-hmac" +#define OPT_INTEGRITY_LEGACY_RECALC "integrity-legacy-recalculate" +#define OPT_INTEGRITY_NO_JOURNAL "integrity-no-journal" +#define OPT_INTEGRITY_NO_WIPE "integrity-no-wipe" +#define OPT_INTEGRITY_RECALCULATE "integrity-recalculate" +#define OPT_INTEGRITY_RECALCULATE_RESET "integrity-recalculate-reset" +#define OPT_INTEGRITY_RECOVERY_MODE "integrity-recovery-mode" +#define OPT_INTERLEAVE_SECTORS "interleave-sectors" +#define OPT_ITER_TIME "iter-time" +#define OPT_IV_LARGE_SECTORS "iv-large-sectors" +#define OPT_JSON_FILE "json-file" +#define OPT_JOURNAL_COMMIT_TIME "journal-commit-time" +#define OPT_JOURNAL_CRYPT "journal-crypt" +#define OPT_JOURNAL_CRYPT_KEY_FILE "journal-crypt-key-file" +#define OPT_JOURNAL_CRYPT_KEY_SIZE "journal-crypt-key-size" +#define OPT_JOURNAL_INTEGRITY "journal-integrity" +#define OPT_JOURNAL_INTEGRITY_KEY_FILE "journal-integrity-key-file" +#define OPT_JOURNAL_INTEGRITY_KEY_SIZE "journal-integrity-key-size" +#define OPT_JOURNAL_SIZE "journal-size" +#define OPT_JOURNAL_WATERMARK "journal-watermark" +#define OPT_KEEP_KEY "keep-key" +#define OPT_KEY_DESCRIPTION "key-description" +#define OPT_KEY_FILE "key-file" +#define OPT_KEY_SIZE "key-size" +#define OPT_KEY_SLOT "key-slot" +#define OPT_KEYFILE_OFFSET "keyfile-offset" +#define OPT_KEYFILE_SIZE "keyfile-size" +#define OPT_KEYSLOT_CIPHER "keyslot-cipher" +#define OPT_KEYSLOT_KEY_SIZE "keyslot-key-size" +#define OPT_NO_SUPERBLOCK "no-superblock" +#define OPT_NO_WIPE "no-wipe" +#define OPT_WIPE "wipe" +#define OPT_LABEL "label" +#define OPT_LUKS2_KEYSLOTS_SIZE "luks2-keyslots-size" +#define OPT_LUKS2_METADATA_SIZE "luks2-metadata-size" +#define OPT_MASTER_KEY_FILE "master-key-file" +#define OPT_VOLUME_KEY_FILE "volume-key-file" +#define OPT_NEW "new" +#define OPT_NEW_KEY_SLOT "new-key-slot" +#define OPT_NEW_KEYFILE "new-keyfile" +#define OPT_NEW_KEYFILE_OFFSET "new-keyfile-offset" +#define OPT_NEW_KEYFILE_SIZE "new-keyfile-size" +#define OPT_NEW_TOKEN_ID "new-token-id" +#define OPT_OFFSET "offset" +#define OPT_PANIC_ON_CORRUPTION "panic-on-corruption" +#define OPT_PBKDF "pbkdf" +#define OPT_PBKDF_FORCE_ITERATIONS "pbkdf-force-iterations" +#define OPT_PBKDF_MEMORY "pbkdf-memory" +#define OPT_PBKDF_PARALLEL "pbkdf-parallel" +#define OPT_PERF_NO_READ_WORKQUEUE "perf-no_read_workqueue" +#define OPT_PERF_NO_WRITE_WORKQUEUE "perf-no_write_workqueue" +#define OPT_PERF_SAME_CPU_CRYPT "perf-same_cpu_crypt" +#define OPT_PERF_SUBMIT_FROM_CRYPT_CPUS "perf-submit_from_crypt_cpus" +#define OPT_PERSISTENT "persistent" +#define OPT_PLUGIN "plugin" +#define OPT_PRIORITY "priority" +#define OPT_PROGRESS_JSON "progress-json" +#define OPT_PROGRESS_FREQUENCY "progress-frequency" +#define OPT_READONLY "readonly" +#define OPT_REDUCE_DEVICE_SIZE "reduce-device-size" +#define OPT_REFRESH "refresh" +#define OPT_RESILIENCE "resilience" +#define OPT_RESILIENCE_HASH "resilience-hash" +#define OPT_RESTART_ON_CORRUPTION "restart-on-corruption" +#define OPT_RESUME_ONLY "resume-only" +#define OPT_ROOT_HASH_FILE "root-hash-file" +#define OPT_ROOT_HASH_SIGNATURE "root-hash-signature" +#define OPT_SALT "salt" +#define OPT_SECTOR_SIZE "sector-size" +#define OPT_SERIALIZE_MEMORY_HARD_PBKDF "serialize-memory-hard-pbkdf" +#define OPT_SHARED "shared" +#define OPT_SIZE "size" +#define OPT_SKIP "skip" +#define OPT_SUBSYSTEM "subsystem" +#define OPT_TAG_SIZE "tag-size" +#define OPT_TCRYPT_BACKUP "tcrypt-backup" +#define OPT_TCRYPT_HIDDEN "tcrypt-hidden" +#define OPT_TCRYPT_SYSTEM "tcrypt-system" +#define OPT_TEST_ARGS "test-args" +#define OPT_TEST_PASSPHRASE "test-passphrase" +#define OPT_TIMEOUT "timeout" +#define OPT_TOKEN_ID "token-id" +#define OPT_TOKEN_ONLY "token-only" +#define OPT_TOKEN_REPLACE "token-replace" +#define OPT_TOKEN_TYPE "token-type" +#define OPT_TRIES "tries" +#define OPT_TYPE "type" +#define OPT_UNBOUND "unbound" +#define OPT_USE_DIRECTIO "use-directio" +#define OPT_USE_FSYNC "use-fsync" +#define OPT_USE_RANDOM "use-random" +#define OPT_USE_URANDOM "use-urandom" +#define OPT_USE_TASKLETS "use-tasklets" +#define OPT_UUID "uuid" +#define OPT_VERACRYPT "veracrypt" +#define OPT_VERACRYPT_PIM "veracrypt-pim" +#define OPT_VERACRYPT_QUERY_PIM "veracrypt-query-pim" +#define OPT_VERBOSE "verbose" +#define OPT_VERIFY_PASSPHRASE "verify-passphrase" +#define OPT_WRITE_LOG "write-log" + +#endif diff --git a/src/utils_args.c b/src/utils_args.c new file mode 100644 index 0000000..fda2350 --- /dev/null +++ b/src/utils_args.c @@ -0,0 +1,131 @@ +/* + * Command line arguments parsing helpers + * + * Copyright (C) 2020-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2020-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "cryptsetup.h" + +void tools_parse_arg_value(poptContext popt_context, crypt_arg_type_info type, struct tools_arg *arg, const char *popt_arg, int popt_val, bool(*needs_size_conv_fn)(unsigned arg_id)) +{ + char *end, msg[128]; + long long int ll; + long long unsigned int ull; + + errno = 0; + + switch (type) { + case CRYPT_ARG_BOOL: + break; + case CRYPT_ARG_STRING: + if (arg->set) + free(arg->u.str_value); + arg->u.str_value = poptGetOptArg(popt_context); + break; + case CRYPT_ARG_INT32: + ll = strtoll(popt_arg, &end, 10); + if (*end || !*popt_arg || ll > INT32_MAX || ll < INT32_MIN || errno == ERANGE) + usage(popt_context, EXIT_FAILURE, poptStrerror(POPT_ERROR_BADNUMBER), + poptGetInvocationName(popt_context)); + arg->u.i32_value = (int32_t)ll; + break; + case CRYPT_ARG_UINT32: + ull = strtoull(popt_arg, &end, 10); + if (*end || !*popt_arg || ull > UINT32_MAX || errno == ERANGE) + usage(popt_context, EXIT_FAILURE, poptStrerror(POPT_ERROR_BADNUMBER), + poptGetInvocationName(popt_context)); + arg->u.u32_value = (uint32_t)ull; + break; + case CRYPT_ARG_INT64: + ll = strtoll(popt_arg, &end, 10); + if (*end || !*popt_arg || errno == ERANGE) + usage(popt_context, EXIT_FAILURE, poptStrerror(POPT_ERROR_BADNUMBER), + poptGetInvocationName(popt_context)); + arg->u.i64_value = ll; + break; + case CRYPT_ARG_UINT64: + /* special size strings with units converted to integers */ + if (needs_size_conv_fn && needs_size_conv_fn(popt_val)) { + if (tools_string_to_size(popt_arg, &arg->u.u64_value)) { + if (snprintf(msg, sizeof(msg), _("Invalid size specification in parameter --%s."), arg->name) < 0) + msg[0] = '\0'; + usage(popt_context, EXIT_FAILURE, msg, + poptGetInvocationName(popt_context)); + } + } else { + ull = strtoull(popt_arg, &end, 10); + if (*end || !*popt_arg || errno == ERANGE) + usage(popt_context, EXIT_FAILURE, poptStrerror(POPT_ERROR_BADNUMBER), + poptGetInvocationName(popt_context)); + arg->u.u64_value = ull; + } + break; + case CRYPT_ARG_ALIAS: + tools_parse_arg_value(popt_context, arg->u.o.ptr->type, arg->u.o.ptr, popt_arg, arg->u.o.id, needs_size_conv_fn); + break; + default: + /* this signals internal tools coding mistake */ + abort(); + } + + arg->set = true; +} + +void tools_args_free(struct tools_arg *args, size_t args_size) +{ + size_t i; + + for (i = 0; i < args_size; i++) { + if (args[i].set && args[i].type == CRYPT_ARG_STRING) + free(args[i].u.str_value); + args[i].set = false; + } +} + +static bool action_allowed(const char *action, const char * const* list, size_t list_size) +{ + size_t i; + + if (!list[0]) + return true; + + for (i = 0; i < list_size && list[i]; i++) { + if (!strcmp(action, list[i])) + return true; + } + + return false; +} + +void tools_check_args(const char *action, const struct tools_arg *args, size_t args_size, poptContext popt_context) +{ + size_t i; + char msg[256]; + + for (i = 1; i < args_size; i++) { + if (args[i].set) { + if (action_allowed(action, args[i].actions_array, MAX_ACTIONS)) { + continue; + } else { + if (snprintf(msg, sizeof(msg), _("Option --%s is not allowed with %s action."), args[i].name, action) < 0) + msg[0] = '\0'; + usage(popt_context, EXIT_FAILURE, msg, poptGetInvocationName(popt_context)); + } + } + } +} diff --git a/src/utils_blockdev.c b/src/utils_blockdev.c new file mode 100644 index 0000000..ae6dec4 --- /dev/null +++ b/src/utils_blockdev.c @@ -0,0 +1,382 @@ +/* + * Linux block devices helpers + * + * Copyright (C) 2018-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2018-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "cryptsetup.h" +#include <dirent.h> +#ifdef HAVE_SYS_SYSMACROS_H +# include <sys/sysmacros.h> /* for major, minor */ +#endif +#include <uuid/uuid.h> + +#define UUID_LEN 37 /* 36 + \0, libuuid ... */ + +static int dm_prepare_uuid(const char *type, const char *uuid, char *buf, size_t buflen) +{ + char *ptr, uuid2[UUID_LEN] = {0}; + uuid_t uu; + unsigned i = 0; + + /* Remove '-' chars */ + if (uuid) { + if (uuid_parse(uuid, uu) < 0) { + log_dbg("Requested UUID %s has invalid format.", uuid); + return 0; + } + + for (ptr = uuid2, i = 0; i < UUID_LEN; i++) + if (uuid[i] != '-') { + *ptr = uuid[i]; + ptr++; + } + } + + if (snprintf(buf, buflen, DM_UUID_PREFIX "%s%s%s%s", + type ?: "", type ? "-" : "", + uuid2[0] ? uuid2 : "", uuid2[0] ? "-" : "") < 0) + return 0; + + return 1; +} + +/* return number of holders in general, if matched dm_uuid prefix it's returned via dm_name */ +/* negative value is error */ +static int lookup_holder_dm_name(const char *dm_uuid, dev_t devno, char **r_dm_name) +{ + struct dirent *entry; + char dm_subpath[PATH_MAX], data_dev_dir[PATH_MAX], uuid[DM_UUID_LEN], dm_name[PATH_MAX] = {}; + ssize_t s; + struct stat st; + int dmfd, fd, len, r = 0; /* not found */ + DIR *dir; + + if (!r_dm_name) + return -EINVAL; + + len = snprintf(data_dev_dir, PATH_MAX, "/sys/dev/block/%u:%u/holders", major(devno), minor(devno)); + if (len < 0 || len >= PATH_MAX) + return -EINVAL; + + if (!(dir = opendir(data_dev_dir))) + /* map ENOTDIR to ENOENT we'll handle both errors same */ + return errno == ENOTDIR ? -ENOENT : -errno; + + while (r != 1 && (entry = readdir(dir))) { + if (entry->d_name[0] == '.' || + !strncmp(entry->d_name, "..", 2)) + continue; + + /* there's a holder */ + r++; + + /* we already have a dm_name, just count remaining holders */ + if (*dm_name != '\0') + continue; + + len = snprintf(dm_subpath, PATH_MAX, "%s/%s", entry->d_name, "dm"); + if (len < 0 || len >= PATH_MAX) { + r = -EINVAL; + break; + } + + /* looking for dm-X/dm directory, symlinks are fine */ + dmfd = openat(dirfd(dir), dm_subpath, O_DIRECTORY | O_RDONLY); + if (dmfd < 0) + continue; + + fd = openat(dmfd, "uuid", O_RDONLY); + if (fd < 0) { + close(dmfd); + continue; + } + + if (fstat(fd, &st) || !S_ISREG(st.st_mode)) { + close(fd); + close(dmfd); + continue; + } + + /* reads binary data */ + s = read_buffer(fd, uuid, sizeof(uuid) - 1); + close(fd); + uuid[s > 0 ? s : 0] = '\0'; + if (!strncmp(uuid, dm_uuid, strlen(dm_uuid))) + log_dbg("Found candidate device %s", entry->d_name); + else { + close(dmfd); + continue; + } + + fd = openat(dmfd, "name", O_RDONLY); + if (fd < 0) { + close(dmfd); + continue; + } + + if (fstat(fd, &st) || !S_ISREG(st.st_mode)) { + close(fd); + close(dmfd); + continue; + } + + /* reads binary data */ + s = read_buffer(fd, dm_name, sizeof(dm_name)); + close(fd); + close(dmfd); + if (s > 1) { + dm_name[s-1] = '\0'; + log_dbg("Found dm device %s", dm_name); + if (!(*r_dm_name = strdup(dm_name))) + return -ENOMEM; + } + } + + closedir(dir); + + return r; +} + +int tools_lookup_crypt_device(struct crypt_device *cd, const char *type, + const char *data_device_path, char **r_name) +{ + char *c; + struct stat st; + char dev_uuid[DM_UUID_LEN + DM_BY_ID_PREFIX_LEN] = DM_BY_ID_PREFIX; + + if (!dm_prepare_uuid(type, crypt_get_uuid(cd), dev_uuid + DM_BY_ID_PREFIX_LEN, DM_UUID_LEN)) + return -EINVAL; + + c = strrchr(dev_uuid, '-'); + if (!c) + return -EINVAL; + + /* cut of dm name */ + *c = '\0'; + + log_dbg("Looking for any dm device with prefix: %s", dev_uuid); + + if (stat(data_device_path, &st) < 0) + return -ENODEV; + + if (!S_ISBLK(st.st_mode)) + return -ENOTBLK; + + return lookup_holder_dm_name(dev_uuid + DM_BY_ID_PREFIX_LEN, st.st_rdev, r_name); +} + +static void report_partition(const char *value, const char *device, bool batch_mode) +{ + if (batch_mode) + log_dbg("Device %s already contains a '%s' partition signature.", device, value); + else + log_std(_("WARNING: Device %s already contains a '%s' partition signature.\n"), device, value); +} + +static void report_superblock(const char *value, const char *device, bool batch_mode) +{ + if (batch_mode) + log_dbg("Device %s already contains a '%s' superblock signature.", device, value); + else + log_std(_("WARNING: Device %s already contains a '%s' superblock signature.\n"), device, value); +} + +int tools_detect_signatures(const char *device, tools_probe_filter_info filter, + size_t *count,bool batch_mode) +{ + int r; + size_t tmp_count; + struct blkid_handle *h; + blk_probe_status pr; + + if (!count) + count = &tmp_count; + + *count = 0; + + if (!blk_supported()) { + log_dbg("Blkid support disabled."); + return 0; + } + + if ((r = blk_init_by_path(&h, device))) { + log_err(_("Failed to initialize device signature probes.")); + return -EINVAL; + } + + switch (filter) { + case PRB_FILTER_LUKS: + if (blk_superblocks_filter_luks(h)) { + r = -EINVAL; + goto out; + } + /* fall-through */ + case PRB_FILTER_NONE: + blk_set_chains_for_full_print(h); + break; + case PRB_ONLY_LUKS: + blk_set_chains_for_fast_detection(h); + if (blk_superblocks_only_luks(h)) { + r = -EINVAL; + goto out; + } + } + + while ((pr = blk_probe(h)) < PRB_EMPTY) { + if (blk_is_partition(h)) + report_partition(blk_get_partition_type(h), device, batch_mode); + else if (blk_is_superblock(h)) + report_superblock(blk_get_superblock_type(h), device, batch_mode); + else { + log_dbg("Internal tools_detect_signatures() error."); + r = -EINVAL; + goto out; + } + (*count)++; + } + + if (pr == PRB_FAIL) + r = -EINVAL; +out: + blk_free(h); + return r; +} + +int tools_wipe_all_signatures(const char *path, bool exclusive, bool only_luks) +{ + int fd, flags, r; + blk_probe_status pr; + struct stat st; + struct blkid_handle *h = NULL; + + if (!blk_supported()) { + log_dbg("Blkid support disabled."); + return 0; + } + + if (stat(path, &st)) { + log_err(_("Failed to stat device %s."), path); + return -EINVAL; + } + + flags = O_RDWR; + if (S_ISBLK(st.st_mode) && exclusive) + flags |= O_EXCL; + + /* better than opening regular file with O_EXCL (undefined) */ + /* coverity[toctou] */ + fd = open(path, flags); /* lgtm[cpp/toctou-race-condition] */ + if (fd < 0) { + if (errno == EBUSY) + log_err(_("Cannot exclusively open %s, device in use."), path); + else + log_err(_("Failed to open file %s in read/write mode."), path); + return -EINVAL; + } + + if ((r = blk_init_by_fd(&h, fd))) { + log_err(_("Failed to initialize device signature probes.")); + r = -EINVAL; + goto out; + } + + blk_set_chains_for_wipes(h); + if (only_luks && (r = blk_superblocks_only_luks(h))) { + r = -EINVAL; + goto out; + } + + while ((pr = blk_probe(h)) < PRB_EMPTY) { + if (blk_is_partition(h)) + log_verbose(_("Existing '%s' partition signature on device %s will be wiped."), + blk_get_partition_type(h), path); + if (blk_is_superblock(h)) + log_verbose(_("Existing '%s' superblock signature on device %s will be wiped."), + blk_get_superblock_type(h), path); + if (blk_do_wipe(h) || fsync(fd)) { + log_err(_("Failed to wipe device signature.")); + r = -EINVAL; + goto out; + } + } + + if (pr != PRB_EMPTY) { + log_err(_("Failed to probe device %s for a signature."), path); + r = -EINVAL; + } +out: + close(fd); + blk_free(h); + return r; +} + +int tools_superblock_block_size(const char *device, char *sb_name, size_t sb_name_len, unsigned *r_block_size) +{ + struct blkid_handle *h; + const char *name; + int r = 0; + + if (!r_block_size || !sb_name || sb_name_len < 1) + return -EINVAL; + + if (!blk_supported()) { + log_dbg("Blkid support disabled."); + return 0; + } + + if ((r = blk_init_by_path(&h, device))) { + log_err(_("Failed to initialize device signature probes.")); + return -EINVAL; + } + + blk_set_chains_for_superblocks(h); + + switch (blk_probe(h)) { + case PRB_OK: + *r_block_size = blk_get_block_size(h); + if (!*r_block_size) /* same as not-found */ + break; + + if (!(name = blk_get_superblock_type(h))) { + r = -EINVAL; + break; + } + + /* we don't mind truncating */ + strncpy(sb_name, name, sb_name_len - 1); + sb_name[sb_name_len-1] = '\0'; + + log_dbg("Detected superblock %s on device %s (block size: %u).", sb_name, device, *r_block_size); + r = 1; + /* fall-through */ + case PRB_EMPTY: + break; + default: + r = -EINVAL; + } + + blk_free(h); + + return r; +} + +bool tools_blkid_supported(void) +{ + return blk_supported() != 0; +} diff --git a/src/utils_luks.c b/src/utils_luks.c new file mode 100644 index 0000000..6a10ab6 --- /dev/null +++ b/src/utils_luks.c @@ -0,0 +1,274 @@ +/* + * Helper utilities for LUKS2 features + * + * Copyright (C) 2018-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2018-2023 Milan Broz + * Copyright (C) 2018-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "cryptsetup.h" +#include "cryptsetup_args.h" +#include "utils_luks.h" + +extern const char *set_pbkdf; + +const char *luksType(const char *type) +{ + if (type && !strcmp(type, "luks2")) + return CRYPT_LUKS2; + + if (type && !strcmp(type, "luks1")) + return CRYPT_LUKS1; + + if (type && !strcmp(type, "luks")) + return CRYPT_LUKS; /* NULL */ + + if (type && *type) + return type; + + return CRYPT_LUKS; /* NULL */ +} + +bool isLUKS1(const char *type) +{ + return type && !strcmp(type, CRYPT_LUKS1); +} + +bool isLUKS2(const char *type) +{ + return type && !strcmp(type, CRYPT_LUKS2); +} + +int verify_passphrase(int def) +{ + /* Batch mode switch off verify - if not overridden by -y */ + if (ARG_SET(OPT_VERIFY_PASSPHRASE_ID)) + def = 1; + else if (ARG_SET(OPT_BATCH_MODE_ID)) + def = 0; + + /* Non-tty input doesn't allow verify */ + if (def && !isatty(STDIN_FILENO)) { + if (ARG_SET(OPT_VERIFY_PASSPHRASE_ID)) + log_err(_("Can't do passphrase verification on non-tty inputs.")); + def = 0; + } + + return def; +} + +void set_activation_flags(uint32_t *flags) +{ + if (ARG_SET(OPT_READONLY_ID)) + *flags |= CRYPT_ACTIVATE_READONLY; + + if (ARG_SET(OPT_ALLOW_DISCARDS_ID)) + *flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS; + + if (ARG_SET(OPT_PERF_SAME_CPU_CRYPT_ID)) + *flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT; + + if (ARG_SET(OPT_PERF_SUBMIT_FROM_CRYPT_CPUS_ID)) + *flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS; + + if (ARG_SET(OPT_PERF_NO_READ_WORKQUEUE_ID)) + *flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE; + + if (ARG_SET(OPT_PERF_NO_WRITE_WORKQUEUE_ID)) + *flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE; + + if (ARG_SET(OPT_INTEGRITY_NO_JOURNAL_ID)) + *flags |= CRYPT_ACTIVATE_NO_JOURNAL; + + /* In persistent mode, we use what is set on command line */ + if (ARG_SET(OPT_PERSISTENT_ID)) + *flags |= CRYPT_ACTIVATE_IGNORE_PERSISTENT; + + /* Only for LUKS2 but ignored elsewhere */ + if (ARG_SET(OPT_TEST_PASSPHRASE_ID) && + (ARG_SET(OPT_KEY_SLOT_ID) || ARG_SET(OPT_UNBOUND_ID))) + *flags |= CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY; + + if (ARG_SET(OPT_SERIALIZE_MEMORY_HARD_PBKDF_ID)) + *flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF; + + /* Only for plain */ + if (ARG_SET(OPT_IV_LARGE_SECTORS_ID)) + *flags |= CRYPT_ACTIVATE_IV_LARGE_SECTORS; +} + +int set_pbkdf_params(struct crypt_device *cd, const char *dev_type) +{ + const struct crypt_pbkdf_type *pbkdf_default; + struct crypt_pbkdf_type pbkdf = {}; + + pbkdf_default = crypt_get_pbkdf_default(dev_type); + if (!pbkdf_default) + return -EINVAL; + + pbkdf.type = set_pbkdf ?: pbkdf_default->type; + pbkdf.hash = ARG_STR(OPT_HASH_ID) ?: pbkdf_default->hash; + pbkdf.time_ms = ARG_UINT32(OPT_ITER_TIME_ID) ?: pbkdf_default->time_ms; + if (strcmp(pbkdf.type, CRYPT_KDF_PBKDF2)) { + pbkdf.max_memory_kb = ARG_UINT32(OPT_PBKDF_MEMORY_ID) ?: pbkdf_default->max_memory_kb; + pbkdf.parallel_threads = ARG_UINT32(OPT_PBKDF_PARALLEL_ID) ?: pbkdf_default->parallel_threads; + } + + if (ARG_SET(OPT_PBKDF_FORCE_ITERATIONS_ID)) { + pbkdf.iterations = ARG_UINT32(OPT_PBKDF_FORCE_ITERATIONS_ID); + pbkdf.time_ms = 0; + pbkdf.flags |= CRYPT_PBKDF_NO_BENCHMARK; + } + + return crypt_set_pbkdf_type(cd, &pbkdf); +} + +int set_tries_tty(void) +{ + return (tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID)) && isatty(STDIN_FILENO)) ? ARG_UINT32(OPT_TRIES_ID) : 1; +} + +int get_adjusted_key_size(const char *cipher_mode, uint32_t default_size_bits, int integrity_keysize) +{ + uint32_t keysize_bits = ARG_UINT32(OPT_KEY_SIZE_ID); + +#ifdef ENABLE_LUKS_ADJUST_XTS_KEYSIZE + if (!ARG_SET(OPT_KEY_SIZE_ID) && !strncmp(cipher_mode, "xts-", 4)) { + if (default_size_bits == 128) + keysize_bits = 256; + else if (default_size_bits == 256) + keysize_bits = 512; + } +#endif + return (keysize_bits ?: default_size_bits) / 8 + integrity_keysize; +} + +/* + * FIXME: 4MiBs is max LUKS2 mda length (including binary header). + * In future, read max allowed JSON size from config section. + */ +#define LUKS2_MAX_MDA_SIZE 0x400000 +int tools_read_json_file(const char *file, char **json, size_t *json_size, bool batch_mode) +{ + ssize_t ret; + int fd, block, r; + void *buf = NULL; + + block = tools_signals_blocked(); + if (block) + set_int_block(0); + + if (tools_is_stdin(file)) { + fd = STDIN_FILENO; + log_dbg("STDIN descriptor JSON read requested."); + } else { + log_dbg("File descriptor JSON read requested."); + fd = open(file, O_RDONLY); + if (fd < 0) { + log_err(_("Failed to open file %s in read-only mode."), file); + r = -EINVAL; + goto out; + } + } + + buf = malloc(LUKS2_MAX_MDA_SIZE); + if (!buf) { + r = -ENOMEM; + goto out; + } + + if (isatty(fd) && !batch_mode) + log_std(_("Provide valid LUKS2 token JSON:\n")); + + /* we expect JSON (string) */ + r = 0; + ret = read_buffer_intr(fd, buf, LUKS2_MAX_MDA_SIZE - 1, &quit); + if (ret < 0) { + r = -EIO; + log_err(_("Failed to read JSON file.")); + goto out; + } + check_signal(&r); + if (r) { + log_err(_("\nRead interrupted.")); + goto out; + } + + *json_size = (size_t)ret; + *json = buf; + *(*json + ret) = '\0'; +out: + if (block && !quit) + set_int_block(1); + if (fd >= 0 && fd != STDIN_FILENO) + close(fd); + if (r && buf) { + memset(buf, 0, LUKS2_MAX_MDA_SIZE); + free(buf); + } + return r; +} + +int tools_write_json_file(const char *file, const char *json) +{ + int block, fd, r; + size_t json_len; + ssize_t ret; + + if (!json || !(json_len = strlen(json)) || json_len >= LUKS2_MAX_MDA_SIZE) + return -EINVAL; + + block = tools_signals_blocked(); + if (block) + set_int_block(0); + + if (tools_is_stdin(file)) { + fd = STDOUT_FILENO; + log_dbg("STDOUT descriptor JSON write requested."); + } else { + log_dbg("File descriptor JSON write requested."); + fd = open(file, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR); + } + + if (fd < 0) { + log_err(_("Failed to open file %s in write mode."), file ?: ""); + r = -EINVAL; + goto out; + } + + r = 0; + ret = write_buffer_intr(fd, json, json_len, &quit); + check_signal(&r); + if (r) { + log_err(_("\nWrite interrupted.")); + goto out; + } + if (ret < 0 || (size_t)ret != json_len) { + log_err(_("Failed to write JSON file.")); + r = -EIO; + goto out; + } + + if (isatty(fd)) + (void) write_buffer_intr(fd, "\n", 1, &quit); +out: + if (block && !quit) + set_int_block(1); + if (fd >=0 && fd != STDOUT_FILENO) + close(fd); + return r; +} diff --git a/src/utils_luks.h b/src/utils_luks.h new file mode 100644 index 0000000..28220ab --- /dev/null +++ b/src/utils_luks.h @@ -0,0 +1,52 @@ +/* + * Helper utilities for LUKS in cryptsetup + * + * Copyright (C) 2018-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2018-2023 Milan Broz + * Copyright (C) 2018-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef UTILS_LUKS_H +#define UTILS_LUKS_H + +#include <stdint.h> + +const char *luksType(const char *type); + +bool isLUKS1(const char *type); + +bool isLUKS2(const char *type); + +int verify_passphrase(int def); + +void set_activation_flags(uint32_t *flags); + +int set_pbkdf_params(struct crypt_device *cd, const char *dev_type); + +int set_tries_tty(void); + +int get_adjusted_key_size(const char *cipher_mode, uint32_t default_size_bits, int integrity_keysize); + +int luksFormat(struct crypt_device **r_cd, char **r_password, size_t *r_passwordLen); + +int reencrypt(int action_argc, const char **action_argv); + +int reencrypt_luks1(const char *device); + +int reencrypt_luks1_in_progress(const char *device); + +#endif /* UTILS_LUKS_H */ diff --git a/src/utils_password.c b/src/utils_password.c new file mode 100644 index 0000000..3374e18 --- /dev/null +++ b/src/utils_password.c @@ -0,0 +1,331 @@ +/* + * Password quality check wrapper + * + * Copyright (C) 2012-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2012-2023 Milan Broz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "cryptsetup.h" +#include <termios.h> + +#if defined ENABLE_PWQUALITY +#include <pwquality.h> + +static int tools_check_pwquality(const char *password) +{ + int r; + void *auxerror; + pwquality_settings_t *pwq; + + log_dbg("Checking new password using default pwquality settings."); + pwq = pwquality_default_settings(); + if (!pwq) + return -EINVAL; + + r = pwquality_read_config(pwq, NULL, &auxerror); + if (r) { + log_err(_("Cannot check password quality: %s"), + pwquality_strerror(NULL, 0, r, auxerror)); + pwquality_free_settings(pwq); + return -EINVAL; + } + + r = pwquality_check(pwq, password, NULL, NULL, &auxerror); + if (r < 0) { + log_err(_("Password quality check failed:\n %s"), + pwquality_strerror(NULL, 0, r, auxerror)); + r = -EPERM; + } else + r = 0; + + pwquality_free_settings(pwq); + return r; +} +#elif defined ENABLE_PASSWDQC +#include <passwdqc.h> + +static int tools_check_passwdqc(const char *password) +{ + passwdqc_params_t params; + char *parse_reason = NULL; + const char *check_reason; + const char *config = PASSWDQC_CONFIG_FILE; + int r = -EINVAL; + + passwdqc_params_reset(¶ms); + + if (*config && passwdqc_params_load(¶ms, &parse_reason, config)) { + log_err(_("Cannot check password quality: %s"), + (parse_reason ? parse_reason : "Out of memory")); + goto out; + } + + check_reason = passwdqc_check(¶ms.qc, password, NULL, NULL); + if (check_reason) { + log_err(_("Password quality check failed: Bad passphrase (%s)"), + check_reason); + r = -EPERM; + } else + r = 0; +out: +#if HAVE_PASSWDQC_PARAMS_FREE + passwdqc_params_free(¶ms); +#endif + free(parse_reason); + return r; +} +#endif /* ENABLE_PWQUALITY || ENABLE_PASSWDQC */ + +/* coverity[ +tainted_string_sanitize_content : arg-0 ] */ +static int tools_check_password(const char *password) +{ +#if defined ENABLE_PWQUALITY + return tools_check_pwquality(password); +#elif defined ENABLE_PASSWDQC + return tools_check_passwdqc(password); +#else + return 0; +#endif +} + +/* Password reading helpers */ + +/* coverity[ -taint_source : arg-1 ] */ +static ssize_t read_tty_eol(int fd, char *pass, size_t maxlen) +{ + bool eol = false; + size_t read_size = 0; + ssize_t r; + + do { + r = read(fd, pass, maxlen - read_size); + if ((r == -1 && errno != EINTR) || quit) + return -1; + if (r >= 0) { + if (!r || pass[r-1] == '\n') + eol = true; + read_size += (size_t)r; + pass = pass + r; + } + } while (!eol && read_size != maxlen); + + return (ssize_t)read_size; +} + +/* The pass buffer is zeroed and has trailing \0 already " */ +static int untimed_read(int fd, char *pass, size_t maxlen, size_t *realsize) +{ + ssize_t i; + + i = read_tty_eol(fd, pass, maxlen); + if (i > 0) { + if (pass[i-1] == '\n') { + pass[i-1] = '\0'; + *realsize = i - 1; + } else + *realsize = i; + i = 0; + } else if (i == 0) /* empty input */ + i = -1; + + return i; +} + +static int timed_read(int fd, char *pass, size_t maxlen, size_t *realsize, long timeout) +{ + struct timeval t; + fd_set fds = {}; /* Just to avoid scan-build false report for FD_SET */ + int failed = -1; + + FD_ZERO(&fds); + FD_SET(fd, &fds); + t.tv_sec = timeout; + t.tv_usec = 0; + + if (select(fd+1, &fds, NULL, NULL, &t) > 0) + failed = untimed_read(fd, pass, maxlen, realsize); + + return failed; +} + +static int interactive_pass(const char *prompt, char *pass, size_t maxlen, + long timeout) +{ + struct termios orig, tmp; + int failed = -1; + int infd, outfd; + size_t realsize = 0; + + if (maxlen < 1) + return failed; + + /* Read and write to /dev/tty if available */ + infd = open("/dev/tty", O_RDWR); + if (infd == -1) { + infd = STDIN_FILENO; + outfd = STDERR_FILENO; + } else + outfd = infd; + + if (tcgetattr(infd, &orig)) + goto out; + + memcpy(&tmp, &orig, sizeof(tmp)); + tmp.c_lflag &= ~ECHO; + + if (prompt && write(outfd, prompt, strlen(prompt)) < 0) + goto out; + + tcsetattr(infd, TCSAFLUSH, &tmp); + if (timeout) + failed = timed_read(infd, pass, maxlen, &realsize, timeout); + else + failed = untimed_read(infd, pass, maxlen, &realsize); + tcsetattr(infd, TCSAFLUSH, &orig); +out: + if (!failed && write(outfd, "\n", 1)) {}; + + if (realsize == maxlen) + log_dbg("Read stopped at maximal interactive input length, passphrase can be trimmed."); + + if (infd != STDIN_FILENO) + close(infd); + return failed; +} + +static int crypt_get_key_tty(const char *prompt, + char **key, size_t *key_size, + int timeout, int verify) +{ + int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX; + int r = -EINVAL; + char *pass = NULL, *pass_verify = NULL; + + *key = NULL; + *key_size = 0; + + log_dbg("Interactive passphrase entry requested."); + + pass = crypt_safe_alloc(key_size_max + 1); + if (!pass) { + log_err( _("Out of memory while reading passphrase.")); + return -ENOMEM; + } + + if (interactive_pass(prompt, pass, key_size_max, timeout)) { + log_err(_("Error reading passphrase from terminal.")); + goto out; + } + + if (verify) { + pass_verify = crypt_safe_alloc(key_size_max + 1); + if (!pass_verify) { + log_err(_("Out of memory while reading passphrase.")); + r = -ENOMEM; + goto out; + } + + if (interactive_pass(_("Verify passphrase: "), + pass_verify, key_size_max, timeout)) { + log_err(_("Error reading passphrase from terminal.")); + goto out; + } + + if (strncmp(pass, pass_verify, key_size_max)) { + log_err(_("Passphrases do not match.")); + r = -EPERM; + goto out; + } + } + + *key = pass; + /* coverity[string_null] (crypt_safe_alloc wipes string with additional \0) */ + *key_size = strlen(pass); + r = 0; +out: + crypt_safe_free(pass_verify); + if (r) + crypt_safe_free(pass); + return r; +} + +/* + * Note: --key-file=- is interpreted as a read from a binary file (stdin) + * key_size_max == 0 means detect maximum according to input type (tty/file) + */ +int tools_get_key(const char *prompt, + char **key, size_t *key_size, + uint64_t keyfile_offset, size_t keyfile_size_max, + const char *key_file, + int timeout, int verify, int pwquality, + struct crypt_device *cd) +{ + char tmp[PATH_MAX], *backing_file; + int r = -EINVAL, block; + + block = tools_signals_blocked(); + if (block) + set_int_block(0); + + if (tools_is_stdin(key_file)) { + if (isatty(STDIN_FILENO)) { + if (keyfile_offset) { + log_err(_("Cannot use offset with terminal input.")); + } else { + r = 0; + if (!prompt && !crypt_get_device_name(cd)) + r = snprintf(tmp, sizeof(tmp), _("Enter passphrase: ")); + else if (!prompt) { + backing_file = crypt_loop_backing_file(crypt_get_device_name(cd)); + r = snprintf(tmp, sizeof(tmp), _("Enter passphrase for %s: "), backing_file ?: crypt_get_device_name(cd)); + free(backing_file); + } + if (r >= 0) + r = crypt_get_key_tty(prompt ?: tmp, key, key_size, timeout, verify); + else + r = -EINVAL; + } + } else { + log_dbg("STDIN descriptor passphrase entry requested."); + /* No keyfile means STDIN with EOL handling (\n will end input)). */ + r = crypt_keyfile_device_read(cd, NULL, key, key_size, + keyfile_offset, keyfile_size_max, + key_file ? 0 : CRYPT_KEYFILE_STOP_EOL); + } + } else { + log_dbg("File descriptor passphrase entry requested."); + r = crypt_keyfile_device_read(cd, key_file, key, key_size, + keyfile_offset, keyfile_size_max, 0); + } + + if (block && !quit) + set_int_block(1); + + /* Check pwquality for password (not keyfile) */ + if (pwquality && !key_file && !r) + r = tools_check_password(*key); + + return r; +} + +void tools_passphrase_msg(int r) +{ + if (r == -EPERM) + log_err(_("No key available with this passphrase.")); + else if (r == -ENOENT) + log_err(_("No usable keyslot is available.")); +} diff --git a/src/utils_progress.c b/src/utils_progress.c new file mode 100644 index 0000000..76b1818 --- /dev/null +++ b/src/utils_progress.c @@ -0,0 +1,301 @@ +/* + * cryptsetup - progress output utilities + * + * Copyright (C) 2009-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2009-2023 Milan Broz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <assert.h> +#include "cryptsetup.h" + +#define MINUTES_90 UINT64_C(5400000000) /* 90 minutes in microseconds */ +#define HOURS_36 UINT64_C(129600000000) /* 36 hours in microseconds */ + +#define MINUTES(A) (A) / UINT64_C(60000000) /* microseconds to minutes */ +#define SECONDS(A) (A) / UINT64_C(1000000) /* microseconds to seconds */ +#define HOURS(A) (A) / UINT64_C(3600000000) /* microseconds to hours */ +#define DAYS(A) (A) / UINT64_C(86400000000) /* microseconds to days */ + +#define REMAIN_SECONDS(A) (SECONDS((A))) % 60 +#define REMAIN_MINUTES(A) (MINUTES((A))) % 60 + +/* The difference in microseconds between two times in "timeval" format. */ +static uint64_t time_diff(struct timeval *start, struct timeval *end) +{ + return (end->tv_sec - start->tv_sec) * UINT64_C(1000000) + + (end->tv_usec - start->tv_usec); +} + +static void tools_clear_line(void) +{ + /* vt100 code clear line */ + log_std("\33[2K\r"); +} + +static void bytes_to_units(uint64_t *bytes, const char **units) +{ + if (*bytes < (UINT64_C(1) << 32)) { /* less than 4 GiBs */ + *units = "MiB"; + *bytes >>= 20; + } else if (*bytes < (UINT64_C(1) << 42)) { /* less than 4 TiBs */ + *units = "GiB"; + *bytes >>= 30; + } else if (*bytes < (UINT64_C(1) << 52)) { /* less than 4 PiBs */ + *units = "TiB"; + *bytes >>= 40; + } else if (*bytes < (UINT64_C(1) << 62)) { /* less than 4 EiBs */ + *units = "PiB"; + *bytes >>= 50; + } else { + *units = "EiB"; + *bytes >>= 60; + } +} + +static bool time_to_human_string(uint64_t usecs, char *buf, size_t buf_len) +{ + ssize_t r; + + if (usecs < MINUTES_90) + r = snprintf(buf, buf_len, _("%02" PRIu64 "m%02" PRIu64 "s"), MINUTES(usecs), REMAIN_SECONDS(usecs)); + else if (usecs < HOURS_36) + r = snprintf(buf, buf_len, _("%02" PRIu64 "h%02" PRIu64 "m%02" PRIu64 "s"), HOURS(usecs), REMAIN_MINUTES(usecs), REMAIN_SECONDS(usecs)); + else + r = snprintf(buf, buf_len, _("%02" PRIu64 " days"), DAYS(usecs)); + + if (r < 0 || (size_t)r >= buf_len) + return false; + + return true; +} + +static void log_progress(uint64_t bytes, uint64_t device_size, uint64_t eta, double uib, const char *ustr, const char *eol) +{ + double progress; + int r; + const char *units; + char time[128], written[128], speed[128]; + + /* + * TRANSLATORS: 'time' string with examples: + * "12m44s" : meaning 12 minutes 44 seconds + * "26h12m44s" : meaning 26 hours 12 minutes 44 seconds + * "3 days" + */ + if (!time_to_human_string(eta, time, sizeof(time))) + return; + + progress = (double)bytes / device_size * 100.0; + + bytes_to_units(&bytes, &units); + r = snprintf(written, sizeof(written), _("%4" PRIu64 " %s written"), bytes, units); + if (r < 0 || (size_t)r >= sizeof(written)) + return; + + r = snprintf(speed, sizeof(speed), _("speed %5.1f %s/s"), uib, ustr); + if (r < 0 || (size_t)r >= sizeof(speed)) + return; + + /* + * TRANSLATORS: 'time', 'written' and 'speed' string are supposed + * to get translated as well. 'eol' is always new-line or empty. + * See above. + */ + log_std(_("Progress: %5.1f%%, ETA %s, %s, %s%s"), + progress, time, written, speed, eol); +} + +static void log_progress_final(uint64_t time_spent, uint64_t bytes, double uib, const char *ustr) +{ + int r; + const char *units; + char time[128], written[128], speed[128]; + + /* + * TRANSLATORS: 'time' string with examples: + * "12m44s" : meaning 12 minutes 44 seconds + * "26h12m44s" : meaning 26 hours 12 minutes 44 seconds + * "3 days" + */ + if (!time_to_human_string(time_spent, time, sizeof(time))) + return; + + bytes_to_units(&bytes, &units); + r = snprintf(written, sizeof(written) - 1, _("%4" PRIu64 " %s written"), bytes, units); + if (r < 0 || (size_t)r >= sizeof(written)) + return; + + r = snprintf(speed, sizeof(speed) - 1, _("speed %5.1f %s/s"), uib, ustr); + if (r < 0 || (size_t)r >= sizeof(speed)) + return; + + /* + * TRANSLATORS: 'time', 'written' and 'speed' string are supposed + * to get translated as well. See above + */ + log_std(_("Finished, time %s, %s, %s\n"), time, written, speed); +} + +static bool calculate_tdiff(bool final, uint64_t bytes, struct tools_progress_params *parms, double *r_tdiff) +{ + uint64_t frequency; + struct timeval now_time; + + assert(r_tdiff); + + gettimeofday(&now_time, NULL); + if (parms->start_time.tv_sec == 0 && parms->start_time.tv_usec == 0) { + parms->start_time = now_time; + parms->end_time = now_time; + parms->start_offset = bytes; + return false; + } + + if (parms->frequency) + frequency = parms->frequency * UINT64_C(1000000); + else + frequency = 500000; + + if (!final && time_diff(&parms->end_time, &now_time) < frequency) + return false; + + parms->end_time = now_time; + + *r_tdiff = time_diff(&parms->start_time, &parms->end_time) / 1E6; + if (!*r_tdiff) + return false; + + return true; +} + +static void tools_time_progress(uint64_t device_size, uint64_t bytes, struct tools_progress_params *parms) +{ + uint64_t eta; + double tdiff, uib; + const char *eol, *ustr; + bool final = (bytes == device_size); + + if (!calculate_tdiff(final, bytes, parms, &tdiff)) + return; + + if (parms->frequency) + eol = "\n"; + else + eol = ""; + + uib = (double)(bytes - parms->start_offset) / tdiff; + + eta = (uint64_t)((device_size / uib - tdiff) * 1E6); + + if (uib > 1073741824.0f) { + uib /= 1073741824.0f; + ustr = "GiB"; + } else if (uib > 1048576.0f) { + uib /= 1048576.0f; + ustr = "MiB"; + } else if (uib > 1024.0f) { + uib /= 1024.0f; + ustr = "KiB"; + } else + ustr = "B"; + + if (!parms->frequency) + tools_clear_line(); + + if (final) + log_progress_final((uint64_t)(tdiff * 1E6), bytes, uib, ustr); + else + log_progress(bytes, device_size, eta, uib, ustr, eol); + + fflush(stdout); +} + +static void log_progress_json(const char *device, uint64_t bytes, uint64_t device_size, uint64_t eta, uint64_t uib, uint64_t time_spent) +{ + int r; + char json[PATH_MAX+256]; + + r = snprintf(json, sizeof(json) - 1, + "{\"device\":\"%s\"," + "\"device_bytes\":\"%" PRIu64 "\"," /* in bytes */ + "\"device_size\":\"%" PRIu64 "\"," /* in bytes */ + "\"speed\":\"%" PRIu64 "\"," /* in bytes per second */ + "\"eta_ms\":\"%" PRIu64 "\"," /* in milliseconds */ + "\"time_ms\":\"%" PRIu64 "\"}\n", /* in milliseconds */ + device, bytes, device_size, uib, eta, time_spent); + + if (r < 0 || (size_t)r >= sizeof(json) - 1) + return; + + log_std("%s", json); +} + +static void tools_time_progress_json(uint64_t device_size, uint64_t bytes, struct tools_progress_params *parms) +{ + double tdiff, uib; + bool final = (bytes == device_size); + + if (!calculate_tdiff(final, bytes, parms, &tdiff)) + return; + + uib = (double)(bytes - parms->start_offset) / tdiff; + + log_progress_json(parms->device, + bytes, + device_size, + final ? UINT64_C(0) : (uint64_t)((device_size / uib - tdiff) * 1E3), + (uint64_t)uib, + (uint64_t)(tdiff * 1E3)); + + fflush(stdout); +} + +int tools_progress(uint64_t size, uint64_t offset, void *usrptr) +{ + int r = 0; + struct tools_progress_params *parms = (struct tools_progress_params *)usrptr; + + if (parms && parms->json_output) + tools_time_progress_json(size, offset, parms); + else if (parms && !parms->batch_mode) + tools_time_progress(size, offset, parms); + + check_signal(&r); + if (r) { + if (!parms || (!parms->frequency && !parms->json_output)) + tools_clear_line(); + if (parms && parms->interrupt_message) + log_err("%s", parms->interrupt_message); + } + + return r; +} + +const char *tools_get_device_name(const char *device, char **r_backing_file) +{ + char *bfile; + + assert(r_backing_file); + + bfile = crypt_loop_backing_file(device); + if (bfile) { + *r_backing_file = bfile; + return bfile; + } + + return device; +} diff --git a/src/utils_reencrypt.c b/src/utils_reencrypt.c new file mode 100644 index 0000000..a78557c --- /dev/null +++ b/src/utils_reencrypt.c @@ -0,0 +1,1560 @@ +/* + * cryptsetup - action re-encryption utilities + * + * Copyright (C) 2009-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2009-2023 Milan Broz + * Copyright (C) 2021-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <uuid/uuid.h> + +#include "cryptsetup.h" +#include "cryptsetup_args.h" +#include "utils_luks.h" + +extern int64_t data_shift; +extern const char *device_type; +extern const char *set_pbkdf; + +enum device_status_info { + DEVICE_LUKS2 = 0, /* LUKS2 device */ + DEVICE_LUKS2_REENCRYPT, /* LUKS2 device in reencryption */ + DEVICE_LUKS1, /* LUKS1 device */ + DEVICE_LUKS1_UNUSABLE, /* LUKS1 device in reencryption (legacy) */ + DEVICE_NOT_LUKS, /* device is not LUKS type */ + DEVICE_INVALID /* device is invalid */ +}; + +static void _set_reencryption_flags(uint32_t *flags) +{ + if (ARG_SET(OPT_INIT_ONLY_ID)) + *flags |= CRYPT_REENCRYPT_INITIALIZE_ONLY; + + if (ARG_SET(OPT_RESUME_ONLY_ID)) + *flags |= CRYPT_REENCRYPT_RESUME_ONLY; +} + +static int reencrypt_check_passphrase(struct crypt_device *cd, + int keyslot, + const char *passphrase, + size_t passphrase_len) +{ + int r; + + assert(cd); + + r = crypt_activate_by_passphrase(cd, NULL, keyslot, + passphrase, passphrase_len, 0); + check_signal(&r); + tools_passphrase_msg(r); + tools_keyslot_msg(r, UNLOCKED); + + return r; +} + +static int set_keyslot_params(struct crypt_device *cd, int keyslot) +{ + const char *cipher; + struct crypt_pbkdf_type pbkdf; + size_t key_size; + + cipher = crypt_keyslot_get_encryption(cd, keyslot, &key_size); + if (!cipher) + return -EINVAL; + + if (crypt_is_cipher_null(cipher)) { + log_dbg("Keyslot %d uses cipher_null. " + "Replacing with default encryption in new keyslot.", keyslot); + cipher = DEFAULT_LUKS2_KEYSLOT_CIPHER; + key_size = DEFAULT_LUKS2_KEYSLOT_KEYBITS / 8; + } + + if (crypt_keyslot_set_encryption(cd, cipher, key_size)) + return -EINVAL; + + /* if requested any of those just reinitialize context pbkdf */ + if (set_pbkdf || ARG_SET(OPT_HASH_ID) || ARG_SET(OPT_PBKDF_FORCE_ITERATIONS_ID) || + ARG_SET(OPT_ITER_TIME_ID)) + return set_pbkdf_params(cd, CRYPT_LUKS2); + + if (crypt_keyslot_get_pbkdf(cd, keyslot, &pbkdf)) + return -EINVAL; + + pbkdf.flags |= CRYPT_PBKDF_NO_BENCHMARK; + + return crypt_set_pbkdf_type(cd, &pbkdf); +} + +static int get_active_device_name(struct crypt_device *cd, + const char *data_device, + char **r_active_name) +{ + char *msg; + int r; + + assert(data_device); + + r = tools_lookup_crypt_device(cd, crypt_get_type(cd), data_device, r_active_name); + if (r > 0) { + log_dbg("Device %s has %d active holders.", data_device, r); + + if (!*r_active_name) { + log_err(_("Device %s is still in use."), data_device); + return -EINVAL; + } + if (!ARG_SET(OPT_BATCH_MODE_ID)) + log_std(_("Auto-detected active dm device '%s' for data device %s.\n"), + *r_active_name, data_device); + } else if (r < 0) { + if (r != -ENOTBLK) { + log_err(_("Failed to auto-detect device %s holders."), data_device); + return -EINVAL; + } + + r = -EINVAL; + if (!ARG_SET(OPT_BATCH_MODE_ID)) { + log_std(_("Device %s is not a block device.\n"), data_device); + + r = asprintf(&msg, _("Unable to decide if device %s is activated or not.\n" + "Are you sure you want to proceed with reencryption in offline mode?\n" + "It may lead to data corruption if the device is actually activated.\n" + "To run reencryption in online mode, use --active-name parameter instead.\n"), data_device); + if (r < 0) + return -ENOMEM; + r = noDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL; + free(msg); + } else { + log_err(_("Device %s is not a block device. Can not auto-detect if it is active or not.\n" + "Use --force-offline-reencrypt to bypass the check and run in offline mode (dangerous!)."), data_device); + } + } else { + *r_active_name = NULL; + log_dbg("Device %s is unused. Proceeding with offline reencryption.", data_device); + } + + return r; +} + +static int reencrypt_get_active_name(struct crypt_device *cd, + const char *data_device, + char **r_active_name) +{ + assert(cd); + assert(r_active_name); + + if (ARG_SET(OPT_ACTIVE_NAME_ID)) + return (*r_active_name = strdup(ARG_STR(OPT_ACTIVE_NAME_ID))) ? 0 : -ENOMEM; + + return get_active_device_name(cd, data_device, r_active_name); +} + +static int decrypt_verify_and_set_params(struct crypt_params_reencrypt *params) +{ + const char *resilience; + + assert(params); + + if (!ARG_SET(OPT_RESILIENCE_ID)) + return 0; + + resilience = ARG_STR(OPT_RESILIENCE_ID); + + if (!strcmp(resilience, "datashift") || + !strcmp(resilience, "none")) { + log_err(_("Requested --resilience option cannot be applied " + "to current reencryption operation.")); + return -EINVAL; + } else if (!strcmp(resilience, "journal")) + params->resilience = "datashift-journal"; + else if (!strcmp(resilience, "checksum")) + params->resilience = "datashift-checksum"; + else if (!strcmp(resilience, "datashift-checksum") || + !strcmp(resilience, "datashift-journal")) + params->resilience = resilience; + else { + log_err(_("Unsupported resilience mode %s"), resilience); + return -EINVAL; + } + + return 0; +} + +static int reencrypt_verify_and_update_params(struct crypt_params_reencrypt *params, + char **r_hash) +{ + assert(params); + assert(r_hash); + + if (ARG_SET(OPT_ENCRYPT_ID) && params->mode != CRYPT_REENCRYPT_ENCRYPT) { + log_err(_("Device is not in LUKS2 encryption. Conflicting option --encrypt.")); + return -EINVAL; + } + + if (ARG_SET(OPT_DECRYPT_ID) && params->mode != CRYPT_REENCRYPT_DECRYPT) { + log_err(_("Device is not in LUKS2 decryption. Conflicting option --decrypt.")); + return -EINVAL; + } + + if (ARG_SET(OPT_RESILIENCE_ID)) { + if (!strcmp(params->resilience, "datashift") && + strcmp(ARG_STR(OPT_RESILIENCE_ID), "datashift")) { + log_err(_("Device is in reencryption using datashift resilience. " + "Requested --resilience option cannot be applied.")); + return -EINVAL; + } + if (strcmp(params->resilience, "datashift") && + !strcmp(ARG_STR(OPT_RESILIENCE_ID), "datashift")) { + log_err(_("Requested --resilience option cannot be applied " + "to current reencryption operation.")); + return -EINVAL; + } + + if (!strncmp(params->resilience, "datashift-", 10)) { + /* decryption with datashift in progress */ + if (decrypt_verify_and_set_params(params)) + return -EINVAL; + } else if (!strncmp(ARG_STR(OPT_RESILIENCE_ID), "datashift-", 10)) { + log_err(_("Requested --resilience option cannot be applied " + "to current reencryption operation.")); + return -EINVAL; + } else + params->resilience = ARG_STR(OPT_RESILIENCE_ID); + + /* we have to copy hash string returned by API */ + if (params->hash && !ARG_SET(OPT_RESILIENCE_HASH_ID)) { + /* r_hash owns the memory. Freed by caller */ + *r_hash = strdup(params->hash); + if (!*r_hash) + return -ENOMEM; + params->hash = *r_hash; + } + + /* Add default hash when switching to checksum based resilience */ + if (!params->hash && !ARG_SET(OPT_RESILIENCE_HASH_ID) && + (!strcmp(params->resilience, "checksum") || + !strcmp(params->resilience, "datashift-checksum"))) + params->hash = "sha256"; + + if (ARG_SET(OPT_RESILIENCE_HASH_ID)) + params->hash = ARG_STR(OPT_RESILIENCE_HASH_ID); + } else + params->resilience = NULL; + + params->max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE; + params->device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE; + params->flags = CRYPT_REENCRYPT_RESUME_ONLY; + + return 0; +} + +static int reencrypt_hint_force_offline_reencrypt(const char *data_device) +{ + struct stat st; + + if (ARG_SET(OPT_ACTIVE_NAME_ID) || + !ARG_SET(OPT_BATCH_MODE_ID) || + ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID)) + return 0; + + if (stat(data_device, &st) == 0 && S_ISREG(st.st_mode)) { + log_err(_("Device %s is not a block device. Can not auto-detect if it is active or not.\n" + "Use --force-offline-reencrypt to bypass the check and run in offline mode (dangerous!)."), data_device); + return -EINVAL; + } + + return 0; +} + +static int reencrypt_luks2_load(struct crypt_device *cd, const char *data_device) +{ + char *msg; + crypt_reencrypt_info ri; + int r; + size_t passwordLen; + char *active_name = NULL, *hash = NULL, *password = NULL; + struct crypt_params_reencrypt params = {}; + + ri = crypt_reencrypt_status(cd, ¶ms); + if (ri == CRYPT_REENCRYPT_CRASH) + log_err(_("Device requires reencryption recovery. Run repair first.")); + + if (ri != CRYPT_REENCRYPT_CLEAN) + return -EINVAL; + + r = reencrypt_verify_and_update_params(¶ms, &hash); + if (r < 0) + return r; + + r = reencrypt_hint_force_offline_reencrypt(data_device); + if (r < 0) + goto out; + + if (!ARG_SET(OPT_BATCH_MODE_ID) && !ARG_SET(OPT_RESUME_ONLY_ID)) { + r = asprintf(&msg, _("Device %s is already in LUKS2 reencryption. " + "Do you wish to resume previously initialised operation?"), + crypt_get_metadata_device_name(cd) ?: data_device); + if (r < 0) { + r = -ENOMEM; + goto out; + } + r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL; + free(msg); + if (r < 0) + goto out; + } + + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), + ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(0), 0, cd); + if (r < 0) + goto out; + + if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID)) + r = reencrypt_get_active_name(cd, data_device, &active_name); + if (r >= 0) + r = crypt_reencrypt_init_by_passphrase(cd, active_name, password, + passwordLen, ARG_INT32(OPT_KEY_SLOT_ID), + ARG_INT32(OPT_KEY_SLOT_ID), NULL, NULL, ¶ms); +out: + free(hash); + crypt_safe_free(password); + free(active_name); + return r; +} + +/* + * 1: in-progress + * 0: clean luks2 device + * < 0: error + */ +static int luks2_reencrypt_in_progress(struct crypt_device *cd) +{ + uint32_t flags; + + if (crypt_persistent_flags_get(cd, CRYPT_FLAGS_REQUIREMENTS, &flags)) + return -EINVAL; + + if (flags & CRYPT_REQUIREMENT_OFFLINE_REENCRYPT) { + log_err(_("Legacy LUKS2 reencryption is no longer supported.")); + return -EINVAL; + } + + return flags & CRYPT_REQUIREMENT_ONLINE_REENCRYPT; +} + +/* + * Returns crypt context for: + * DEVICE_LUKS2 + * DEVICE_LUKS2_REENCRYPT + * DEVICE_LUKS1 + */ +static enum device_status_info load_luks(struct crypt_device **r_cd, + const char *header_device, + const char *data_device) +{ + int r; + struct crypt_device *cd; + struct stat st; + + assert(r_cd); + assert(data_device); + + if (header_device && stat(header_device, &st) < 0 && errno == ENOENT) + return DEVICE_NOT_LUKS; + + if (crypt_init_data_device(&cd, uuid_or_device(header_device ?: data_device), data_device)) + return DEVICE_INVALID; + + if ((r = crypt_load(cd, CRYPT_LUKS, NULL))) { + crypt_free(cd); + + if (r == -EBUSY) /* luks2 locking error (message printed by libcryptsetup) */ + return DEVICE_INVALID; + + r = reencrypt_luks1_in_progress(uuid_or_device(header_device ?: data_device)); + if (!r) + return DEVICE_LUKS1_UNUSABLE; + + return DEVICE_NOT_LUKS; + } + + if (isLUKS2(crypt_get_type(cd))) { + r = luks2_reencrypt_in_progress(cd); + if (r < 0) { + crypt_free(cd); + return DEVICE_INVALID; + } + } + + *r_cd = cd; + + if (r > 0) + return DEVICE_LUKS2_REENCRYPT; + + return isLUKS2(crypt_get_type(cd)) ? DEVICE_LUKS2 : DEVICE_LUKS1; +} + +static bool luks2_reencrypt_eligible(struct crypt_device *cd) +{ + struct crypt_params_integrity ip = { 0 }; + + /* raw integrity info is available since 2.0 */ + if (crypt_get_integrity_info(cd, &ip) || ip.tag_size) { + log_err(_("Reencryption of device with integrity profile is not supported.")); + return false; + } + + return true; +} + +static enum device_status_info check_luks_device(const char *device) +{ + enum device_status_info dev_st; + struct crypt_device *cd = NULL; + + dev_st = load_luks(&cd, NULL, device); + crypt_free(cd); + + return dev_st; +} + +static int reencrypt_check_data_sb_block_size(const char *data_device, uint32_t new_sector_size) +{ + int r; + char sb_name[32]; + unsigned block_size; + + assert(data_device); + + r = tools_superblock_block_size(data_device, sb_name, sizeof(sb_name), &block_size); + if (r <= 0) + return r; + + if (new_sector_size > block_size) { + log_err(_("Requested --sector-size %" PRIu32 " is incompatible with %s superblock\n" + "(block size: %" PRIu32 " bytes) detected on device %s."), + new_sector_size, sb_name, block_size, data_device); + return -EINVAL; + } + + return 0; +} + +static int reencrypt_check_active_device_sb_block_size(const char *active_device, uint32_t new_sector_size) +{ + int r; + char dm_device[PATH_MAX]; + + r = snprintf(dm_device, sizeof(dm_device), "%s/%s", crypt_get_dir(), active_device); + if (r < 0 || (size_t)r >= sizeof(dm_device)) + return -EINVAL; + + return reencrypt_check_data_sb_block_size(dm_device, new_sector_size); +} + +static int reencrypt_is_header_detached(const char *header_device, const char *data_device) +{ + int r; + struct stat st; + struct crypt_device *cd; + + if (!header_device) + return 0; + + if (header_device && stat(header_device, &st) < 0 && errno == ENOENT) + return 1; + + if ((r = crypt_init_data_device(&cd, header_device, data_device))) + return r; + + r = crypt_header_is_detached(cd); + crypt_free(cd); + return r; +} + +static int encrypt_luks2_init(struct crypt_device **cd, const char *data_device, const char *device_name) +{ + int keyslot, r, fd; + uuid_t uuid; + size_t passwordLen; + char *tmp, uuid_str[37], header_file[PATH_MAX] = { 0 }, *password = NULL; + uint32_t activate_flags = 0; + const struct crypt_params_luks2 luks2_params = { + .sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID) ?: SECTOR_SIZE + }; + struct crypt_params_reencrypt params = { + .mode = CRYPT_REENCRYPT_ENCRYPT, + .direction = data_shift < 0 ? CRYPT_REENCRYPT_BACKWARD : CRYPT_REENCRYPT_FORWARD, + .resilience = ARG_STR(OPT_RESILIENCE_ID) ?: "checksum", + .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256", + .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE, + .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE, + .luks2 = &luks2_params, + .flags = CRYPT_REENCRYPT_INITIALIZE_ONLY + }; + + _set_reencryption_flags(¶ms.flags); + + if (!data_shift) { + r = reencrypt_is_header_detached(ARG_STR(OPT_HEADER_ID), data_device); + if (r < 0) + return r; + if (!r) { + log_err(_("Encryption without detached header (--header) is not possible without data device size reduction (--reduce-device-size).")); + return -ENOTSUP; + } + } + + if (!ARG_SET(OPT_HEADER_ID) && ARG_UINT64(OPT_OFFSET_ID) && + data_shift && (ARG_UINT64(OPT_OFFSET_ID) > (uint64_t)(imaxabs(data_shift) / (2 * SECTOR_SIZE)))) { + log_err(_("Requested data offset must be less than or equal to half of --reduce-device-size parameter.")); + return -EINVAL; + } + + /* TODO: ask user to confirm. It's useless to do data device reduction and than use smaller value */ + if (!ARG_SET(OPT_HEADER_ID) && ARG_UINT64(OPT_OFFSET_ID) && + data_shift && (ARG_UINT64(OPT_OFFSET_ID) < (uint64_t)(imaxabs(data_shift) / (2 * SECTOR_SIZE)))) { + data_shift = -(ARG_UINT64(OPT_OFFSET_ID) * 2 * SECTOR_SIZE); + if (data_shift >= 0) + return -EINVAL; + log_std(_("Adjusting --reduce-device-size value to twice the --offset %" PRIu64 " (sectors).\n"), ARG_UINT64(OPT_OFFSET_ID) * 2); + } + + if (ARG_SET(OPT_UUID_ID) && uuid_parse(ARG_STR(OPT_UUID_ID), uuid) == -1) { + log_err(_("Wrong LUKS UUID format provided.")); + return -EINVAL; + } + + if (ARG_SET(OPT_SECTOR_SIZE_ID)) { + r = reencrypt_check_data_sb_block_size(data_device, ARG_UINT32(OPT_SECTOR_SIZE_ID)); + if (r < 0) + return r; + } + + if (!ARG_SET(OPT_UUID_ID)) { + uuid_generate(uuid); + uuid_unparse(uuid, uuid_str); + if (!(tmp = strdup(uuid_str))) + return -ENOMEM; + ARG_SET_STR(OPT_UUID_ID, tmp); + } + + if (!ARG_SET(OPT_HEADER_ID)) { + r = snprintf(header_file, sizeof(header_file), "LUKS2-temp-%s.new", ARG_STR(OPT_UUID_ID)); + if (r < 0 || (size_t)r >= sizeof(header_file)) + return -EINVAL; + + fd = open(header_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR); + if (fd == -1) { + if (errno == EEXIST) + log_err(_("Temporary header file %s already exists. Aborting."), header_file); + else + log_err(_("Cannot create temporary header file %s."), header_file); + return -EINVAL; + } + + r = posix_fallocate(fd, 0, 4096); + close(fd); + if (r) { + log_err(_("Cannot create temporary header file %s."), header_file); + r = -EINVAL; + goto out; + } + + if (!(tmp = strdup(header_file))) { + r = -ENOMEM; + goto out; + } + ARG_SET_STR(OPT_HEADER_ID, tmp); + + /* + * FIXME: just override offset here, but we should support both. + * offset and implicit offset via data shift (lvprepend?) + */ + if (!ARG_UINT64(OPT_OFFSET_ID)) + ARG_SET_UINT64(OPT_OFFSET_ID, imaxabs(data_shift) / (2 * SECTOR_SIZE)); + data_shift >>= 1; + params.flags |= CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT; + } else if (data_shift < 0) { + if (!ARG_SET(OPT_LUKS2_METADATA_SIZE_ID)) + ARG_SET_UINT64(OPT_LUKS2_METADATA_SIZE_ID, 0x4000); /* missing default here */ + if (!ARG_SET(OPT_LUKS2_KEYSLOTS_SIZE_ID)) + ARG_SET_UINT64(OPT_LUKS2_KEYSLOTS_SIZE_ID, -data_shift - 2 * ARG_UINT64(OPT_LUKS2_METADATA_SIZE_ID)); + if (2 * ARG_UINT64(OPT_LUKS2_METADATA_SIZE_ID) + ARG_UINT64(OPT_LUKS2_KEYSLOTS_SIZE_ID) > (uint64_t)-data_shift) { + log_err(_("LUKS2 metadata size is larger than data shift value.")); + return -EINVAL; + } + } + + r = luksFormat(cd, &password, &passwordLen); + if (r < 0) + goto out; + + if (!luks2_reencrypt_eligible(*cd)) { + r = -EINVAL; + goto out; + } + + if (data_shift) { + params.data_shift = imaxabs(data_shift) / SECTOR_SIZE, + params.resilience = "datashift"; + } + keyslot = !ARG_SET(OPT_KEY_SLOT_ID) ? 0 : ARG_INT32(OPT_KEY_SLOT_ID); + r = crypt_reencrypt_init_by_passphrase(*cd, NULL, password, passwordLen, + CRYPT_ANY_SLOT, keyslot, crypt_get_cipher(*cd), + crypt_get_cipher_mode(*cd), ¶ms); + if (r < 0) { + crypt_keyslot_destroy(*cd, keyslot); + goto out; + } + + /* Restore temporary header in head of data device */ + if (*header_file) { + crypt_free(*cd); + *cd = NULL; + + r = crypt_init(cd, data_device); + if (!r) + r = crypt_header_restore(*cd, CRYPT_LUKS2, header_file); + + if (r) { + log_err(_("Failed to place new header at head of device %s."), data_device); + goto out; + } + } + + /* activate device */ + if (device_name) { + set_activation_flags(&activate_flags); + r = crypt_activate_by_passphrase(*cd, device_name, ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen, activate_flags); + if (r >= 0) + log_std(_("%s/%s is now active and ready for online encryption.\n"), crypt_get_dir(), device_name); + } + + if (r < 0) + goto out; + + /* just load reencryption context to continue reencryption */ + if (!ARG_SET(OPT_INIT_ONLY_ID)) { + params.flags &= ~CRYPT_REENCRYPT_INITIALIZE_ONLY; + r = crypt_reencrypt_init_by_passphrase(*cd, device_name, password, passwordLen, + CRYPT_ANY_SLOT, keyslot, NULL, NULL, ¶ms); + } +out: + crypt_safe_free(password); + if (*header_file) + unlink(header_file); + return r; +} + +static enum device_status_info load_luks2_by_name(struct crypt_device **r_cd, const char *active_name, const char *header_device) +{ + int r; + struct crypt_device *cd; + struct stat st; + + assert(r_cd); + assert(active_name); + + if (header_device && stat(header_device, &st) < 0 && errno == ENOENT) + return DEVICE_NOT_LUKS; + + r = crypt_init_by_name_and_header(&cd, active_name, header_device); + if (r) + return DEVICE_INVALID; + + if (!isLUKS2(crypt_get_type(cd))) { + log_err(_("Active device %s is not LUKS2."), active_name); + crypt_free(cd); + return DEVICE_INVALID; + } + + r = luks2_reencrypt_in_progress(cd); + if (r < 0) { + crypt_free(cd); + return DEVICE_INVALID; + } + + *r_cd = cd; + + return !r ? DEVICE_LUKS2 : DEVICE_LUKS2_REENCRYPT; +} + +static int reencrypt_restore_header(struct crypt_device **cd, + const char *data_device, const char *header) +{ + int r; + + assert(cd); + assert(data_device); + assert(header); + + crypt_free(*cd); + *cd = NULL; + + log_verbose(_("Restoring original LUKS2 header.")); + + r = crypt_init(cd, data_device); + if (r < 0) + return r; + + r = crypt_header_restore(*cd, CRYPT_LUKS2, header); + if (r < 0) + log_err(_("Original LUKS2 header restore failed.")); + + return r; +} + +static int decrypt_luks2_datashift_init(struct crypt_device **cd, + const char *data_device, + const char *expheader) +{ + int fd, r; + size_t passwordLen; + struct stat hdr_st; + bool remove_header = false; + char *msg, *active_name = NULL, *password = NULL; + struct crypt_params_reencrypt params = { + .mode = CRYPT_REENCRYPT_DECRYPT, + .direction = CRYPT_REENCRYPT_FORWARD, + .resilience = "datashift-checksum", + .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256", + .data_shift = crypt_get_data_offset(*cd), + .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE, + .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE, + .flags = CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT + }; + + if (!ARG_SET(OPT_BATCH_MODE_ID)) { + r = asprintf(&msg, _("Header file %s does not exist. Do you want to initialize LUKS2 " + "decryption of device %s and export LUKS2 header to file %s?"), + expheader, data_device, expheader); + if (r < 0) + return -ENOMEM; + r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL; + free(msg); + if (r < 0) + return r; + } + + if ((r = decrypt_verify_and_set_params(¶ms))) + return r; + + r = reencrypt_hint_force_offline_reencrypt(data_device); + if (r < 0) + return r; + + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), + ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID), + verify_passphrase(0), 0, *cd); + if (r < 0) + return r; + + r = reencrypt_check_passphrase(*cd, ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen); + if (r < 0) + goto out; + + r = crypt_header_backup(*cd, CRYPT_LUKS2, expheader); + if (r < 0) + goto out; + + remove_header = true; + + fd = open(expheader, O_RDONLY); + if (fd < 0) + goto out; + + if (fstat(fd, &hdr_st)) { + close(fd); + r = -EINVAL; + goto out; + } + + r = fchmod(fd, hdr_st.st_mode | S_IRUSR | S_IWUSR); + close(fd); + if (r) { + log_err(_("Failed to add read/write permissions to exported header file.")); + r = -EINVAL; + goto out; + } + + crypt_free(*cd); + *cd = NULL; + + /* reload with exported header */ + if (ARG_SET(OPT_ACTIVE_NAME_ID)) { + if (load_luks2_by_name(cd, ARG_STR(OPT_ACTIVE_NAME_ID), expheader) != DEVICE_LUKS2) { + r = -EINVAL; + goto out; + } + } else { + if ((r = crypt_init_data_device(cd, expheader, data_device))) + goto out; + if ((r = crypt_load(*cd, CRYPT_LUKS2, NULL))) + goto out; + } + + _set_reencryption_flags(¶ms.flags); + + if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID)) + r = reencrypt_get_active_name(*cd, data_device, &active_name); + + if (r < 0) + goto out; + + r = tools_wipe_all_signatures(data_device, active_name == NULL, true); + if (r < 0) { + /* if header restore fails keep original header backup */ + if (reencrypt_restore_header(cd, data_device, expheader) < 0) + remove_header = false; + goto out; + } + + remove_header = false; + + r = crypt_reencrypt_init_by_passphrase(*cd, active_name, password, + passwordLen, ARG_INT32(OPT_KEY_SLOT_ID), CRYPT_ANY_SLOT, + NULL, NULL, ¶ms); + + if (r < 0 && crypt_reencrypt_status(*cd, NULL) == CRYPT_REENCRYPT_NONE) { + /* if restore is successful we can remove header backup */ + if (!reencrypt_restore_header(cd, data_device, expheader)) + remove_header = true; + } +out: + free(active_name); + crypt_safe_free(password); + + if (r < 0 && !remove_header && !stat(expheader, &hdr_st) && S_ISREG(hdr_st.st_mode)) + log_err(_("Reencryption initialization failed. Header backup is available in %s."), + expheader); + if (remove_header) + unlink(expheader); + + return r; +} + +static int decrypt_luks2_init(struct crypt_device *cd, const char *data_device) +{ + int r; + size_t passwordLen; + char *active_name = NULL, *password = NULL; + struct crypt_params_reencrypt params = { + .mode = CRYPT_REENCRYPT_DECRYPT, + .direction = data_shift > 0 ? CRYPT_REENCRYPT_FORWARD : CRYPT_REENCRYPT_BACKWARD, + .resilience = data_shift ? "datashift" : (ARG_STR(OPT_RESILIENCE_ID) ?: "checksum"), + .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256", + .data_shift = imaxabs(data_shift) / SECTOR_SIZE, + .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE, + .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE, + }; + + if (!luks2_reencrypt_eligible(cd)) + return -EINVAL; + + if ((!crypt_get_metadata_device_name(cd) || crypt_header_is_detached(cd) <= 0 || + crypt_get_data_offset(cd) > 0)) { + log_err(_("LUKS2 decryption is supported with detached header device only (with data offset set to 0).")); + return -ENOTSUP; + } + + r = reencrypt_hint_force_offline_reencrypt(data_device); + if (r < 0) + return r; + + _set_reencryption_flags(¶ms.flags); + + r = tools_get_key(NULL, &password, &passwordLen, + ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), + ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd); + if (r < 0) + return r; + + r = reencrypt_check_passphrase(cd, ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen); + if (r < 0) + goto out; + + if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID)) + r = reencrypt_get_active_name(cd, data_device, &active_name); + if (r >= 0) + r = crypt_reencrypt_init_by_passphrase(cd, active_name, password, + passwordLen, ARG_INT32(OPT_KEY_SLOT_ID), CRYPT_ANY_SLOT, NULL, NULL, ¶ms); + +out: + free(active_name); + crypt_safe_free(password); + return r; +} + +struct keyslot_passwords { + char *password; + size_t passwordLen; + int new; +}; + +static struct keyslot_passwords *init_keyslot_passwords(size_t count) +{ + size_t i; + struct keyslot_passwords *tmp = calloc(count, sizeof(struct keyslot_passwords)); + + if (!tmp) + return tmp; + + for (i = 0; i < count; i++) + tmp[i].new = -1; + + return tmp; +} + +static int init_passphrase(struct keyslot_passwords *kp, size_t keyslot_passwords_length, + struct crypt_device *cd, const char *msg, int slot_to_check) +{ + crypt_keyslot_info ki; + char *password; + int r = -EINVAL, retry_count; + size_t passwordLen; + + if (slot_to_check != CRYPT_ANY_SLOT) { + ki = crypt_keyslot_status(cd, slot_to_check); + if (ki < CRYPT_SLOT_ACTIVE || ki == CRYPT_SLOT_UNBOUND) + return -ENOENT; + } + + retry_count = set_tries_tty(); + + while (retry_count--) { + r = tools_get_key(msg, &password, &passwordLen, 0, 0, + ARG_STR(OPT_KEY_FILE_ID), 0, 0, 0 /*pwquality*/, cd); + if (r < 0) + return r; + if (quit) { + crypt_safe_free(password); + password = NULL; + passwordLen = 0; + return -EAGAIN; + } + + r = crypt_activate_by_passphrase(cd, NULL, slot_to_check, + password, passwordLen, 0); + if (r < 0) { + crypt_safe_free(password); + password = NULL; + passwordLen = 0; + } + if (r < 0 && r != -EPERM) + return r; + + if (r >= 0) { + tools_keyslot_msg(r, UNLOCKED); + if ((size_t)r >= keyslot_passwords_length) { + crypt_safe_free(password); + return -EINVAL; + } + kp[r].password = password; + kp[r].passwordLen = passwordLen; + break; + } + tools_passphrase_msg(r); + } + + password = NULL; + passwordLen = 0; + + return r; +} + +static int _check_luks2_keyslots(struct crypt_device *cd, bool vk_change) +{ + int i, new_vk_slot = (vk_change ? 1 : 0), max = crypt_keyslot_max(CRYPT_LUKS2), active = 0, unbound = 0; + + if (max < 0) + return max; + + for (i = 0; i < max; i++) { + switch (crypt_keyslot_status(cd, i)) { + case CRYPT_SLOT_INVALID: + return -EINVAL; + case CRYPT_SLOT_ACTIVE: + /* fall-through */ + case CRYPT_SLOT_ACTIVE_LAST: + active++; + break; + case CRYPT_SLOT_UNBOUND: + unbound++; + /* fall-through */ + default: + break; + } + } + + /* at least one keyslot for reencryption plus new volume key (if needed) */ + if (active + unbound + new_vk_slot + 1 > max) { + log_err(_("Not enough free keyslots for reencryption.")); + return -EINVAL; + } + + if (!vk_change) + return 0; + + if ((ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT) && + (2 * active + unbound + 1 > max)) { + log_err(_("Not enough free keyslots for reencryption.")); + return -EINVAL; + } + + return 0; +} + +static int fill_keyslot_passwords(struct crypt_device *cd, + struct keyslot_passwords *kp, size_t kp_size, + bool vk_change) +{ + char msg[128]; + crypt_keyslot_info ki; + int i, r = 0; + + if (vk_change && ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT && ARG_SET(OPT_KEY_FILE_ID)) { + for (i = 0; (size_t)i < kp_size; i++) { + ki = crypt_keyslot_status(cd, i); + if (ki == CRYPT_SLOT_INVALID) + return -EINVAL; + if (ki == CRYPT_SLOT_ACTIVE) { + log_err(_("Key file can be used only with --key-slot or with " + "exactly one key slot active.")); + return -EINVAL; + } + } + } + + if (ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT) { + for (i = 0; (size_t)i < kp_size; i++) { + if (snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %d: "), i) < 0) + return -EINVAL; + r = init_passphrase(kp, kp_size, cd, msg, i); + /* no need to initialize all keyslots with --keep-key */ + if (r >= 0 && !vk_change) + break; + if (r == -ENOENT) + r = 0; + if (r < 0) + break; + } + } else { + if (snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %u: "), ARG_INT32(OPT_KEY_SLOT_ID)) < 0) + return -EINVAL; + r = init_passphrase(kp, kp_size, cd, msg, ARG_INT32(OPT_KEY_SLOT_ID)); + } + + return r < 0 ? r : 0; +} + +static int assign_tokens(struct crypt_device *cd, int keyslot_old, int keyslot_new) +{ + int token = 0, r = crypt_token_is_assigned(cd, token, keyslot_old); + + while (r != -EINVAL) { + if (!r && (token != crypt_token_assign_keyslot(cd, token, keyslot_new))) + return -EINVAL; + token++; + r = crypt_token_is_assigned(cd, token, keyslot_old); + } + + /* we reached max token number, exit */ + return 0; +} + +static int reencrypt_luks2_init(struct crypt_device *cd, const char *data_device) +{ + bool vk_size_change, sector_size_change, sector_size_increase, vk_change; + size_t i, vk_size, kp_size; + int r, keyslot_old = CRYPT_ANY_SLOT, keyslot_new = CRYPT_ANY_SLOT, key_size; + char cipher[MAX_CIPHER_LEN], mode[MAX_CIPHER_LEN], *vk = NULL, *active_name = NULL; + const char *new_cipher = NULL; + struct keyslot_passwords *kp = NULL; + struct crypt_params_luks2 luks2_params = {}; + struct crypt_params_reencrypt params = { + .mode = CRYPT_REENCRYPT_REENCRYPT, + .direction = data_shift < 0 ? CRYPT_REENCRYPT_BACKWARD : CRYPT_REENCRYPT_FORWARD, + .resilience = data_shift ? "datashift" : (ARG_STR(OPT_RESILIENCE_ID) ?: "checksum"), + .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256", + .data_shift = imaxabs(data_shift) / SECTOR_SIZE, + .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE, + .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE, + .luks2 = &luks2_params, + }; + + if (!luks2_reencrypt_eligible(cd)) + return -EINVAL; + + _set_reencryption_flags(¶ms.flags); + + /* cipher */ + if (ARG_SET(OPT_CIPHER_ID)) + new_cipher = ARG_STR(OPT_CIPHER_ID); + else if (!ARG_SET(OPT_CIPHER_ID) && crypt_is_cipher_null(crypt_get_cipher(cd))) { + log_std(_("Switching data encryption cipher to %s.\n"), DEFAULT_CIPHER(LUKS1)); + new_cipher = DEFAULT_CIPHER(LUKS1); + } + + if (!new_cipher) { + strncpy(cipher, crypt_get_cipher(cd), MAX_CIPHER_LEN - 1); + strncpy(mode, crypt_get_cipher_mode(cd), MAX_CIPHER_LEN - 1); + cipher[MAX_CIPHER_LEN-1] = '\0'; + mode[MAX_CIPHER_LEN-1] = '\0'; + } else { + if ((r = crypt_parse_name_and_mode(new_cipher, cipher, NULL, mode))) { + log_err(_("No known cipher specification pattern detected.")); + return r; + } + + /* the segment cipher is identical with existing one */ + if (!strcmp(cipher, crypt_get_cipher(cd)) && !strcmp(mode, crypt_get_cipher_mode(cd))) + new_cipher = NULL; + } + + /* sector size */ + luks2_params.sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID) ?: (uint32_t)crypt_get_sector_size(cd); + sector_size_change = luks2_params.sector_size != (uint32_t)crypt_get_sector_size(cd); + sector_size_increase = luks2_params.sector_size > (uint32_t)crypt_get_sector_size(cd); + + /* key size */ + if (ARG_SET(OPT_KEY_SIZE_ID) || new_cipher) + key_size = get_adjusted_key_size(mode, DEFAULT_LUKS1_KEYBITS, 0); + else + key_size = crypt_get_volume_key_size(cd); + + if (!key_size) + return -EINVAL; + vk_size = key_size; + + vk_size_change = key_size != crypt_get_volume_key_size(cd); + + /* volume key */ + vk_change = !ARG_SET(OPT_KEEP_KEY_ID); + + if (vk_change && ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &vk, key_size); + if (r < 0) + goto out; + + if (!crypt_volume_key_verify(cd, vk, key_size)) { + /* passed key was valid volume key */ + vk_change = false; + crypt_safe_free(vk); + vk = NULL; + } + } + + if (!vk_change && !vk_size_change && !new_cipher && !sector_size_change) { + log_err(_("No data segment parameters changed. Reencryption aborted.")); + r = -EINVAL; + goto out; + } + + if (!ARG_SET(OPT_INIT_ONLY_ID) || (tools_blkid_supported() && sector_size_increase)) { + r = reencrypt_hint_force_offline_reencrypt(data_device); + if (r < 0) + goto out; + } + + r = _check_luks2_keyslots(cd, vk_change); + if (r) + goto out; + + r = crypt_keyslot_max(CRYPT_LUKS2); + if (r < 0) + goto out; + kp_size = r; + + kp = init_keyslot_passwords(kp_size); + if (!kp) { + r = -ENOMEM; + goto out; + } + + /* coverity[overrun-call] */ + r = fill_keyslot_passwords(cd, kp, kp_size, vk_change); + if (r) + goto out; + + r = -ENOENT; + + for (i = 0; i < kp_size; i++) { + if (!vk_change) { + if (kp[i].password) { + r = keyslot_old = kp[i].new = i; + break; + } + continue; + } + + if (kp[i].password && keyslot_new < 0) { + r = set_keyslot_params(cd, i); + if (r < 0) + break; + r = crypt_keyslot_add_by_key(cd, CRYPT_ANY_SLOT, vk, key_size, + kp[i].password, kp[i].passwordLen, CRYPT_VOLUME_KEY_NO_SEGMENT); + tools_keyslot_msg(r, CREATED); + if (r < 0) + break; + + kp[i].new = r; + keyslot_new = r; + keyslot_old = i; + if (!vk) { + /* key generated in crypt_keyslot_add_by_key() call above */ + vk = crypt_safe_alloc(key_size); + if (!vk) { + r = -ENOMEM; + break; + } + r = crypt_volume_key_get(cd, keyslot_new, vk, &vk_size, kp[i].password, kp[i].passwordLen); + if (r < 0) + break; + } + r = assign_tokens(cd, i, r); + if (r < 0) + break; + } else if (kp[i].password) { + r = set_keyslot_params(cd, i); + if (r < 0) + break; + r = crypt_keyslot_add_by_key(cd, CRYPT_ANY_SLOT, vk, key_size, + kp[i].password, kp[i].passwordLen, CRYPT_VOLUME_KEY_NO_SEGMENT | CRYPT_VOLUME_KEY_DIGEST_REUSE); + tools_keyslot_msg(r, CREATED); + if (r < 0) + break; + kp[i].new = r; + r = assign_tokens(cd, i, r); + if (r < 0) + break; + } + } + + if (r < 0) + goto out; + + /* + * with --init-only lookup active device only if + * blkid probes are allowed and sector size increase + * is requested. + */ + if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID) && + (!ARG_SET(OPT_INIT_ONLY_ID) || (tools_blkid_supported() && sector_size_increase))) { + r = reencrypt_get_active_name(cd, data_device, &active_name); + if (r < 0) + goto out; + } + + if (sector_size_increase && !active_name && tools_blkid_supported() && + !ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID)) { + log_err(_("Encryption sector size increase on offline device is not supported.\n" + "Activate the device first or use --force-offline-reencrypt option (dangerous!).")); + r = -EINVAL; + goto out; + } + + if (sector_size_increase && active_name) { + r = reencrypt_check_active_device_sb_block_size(active_name, luks2_params.sector_size); + if (r < 0) + goto out; + } + + r = crypt_reencrypt_init_by_passphrase(cd, + ARG_SET(OPT_INIT_ONLY_ID) ? NULL : active_name, + kp[keyslot_old].password, kp[keyslot_old].passwordLen, + keyslot_old, kp[keyslot_old].new, cipher, mode, ¶ms); +out: + crypt_safe_free(vk); + if (kp) { + for (i = 0; i < kp_size; i++) { + crypt_safe_free(kp[i].password); + if (r < 0 && kp[i].new >= 0 && kp[i].new != (int)i && + crypt_reencrypt_status(cd, NULL) == CRYPT_REENCRYPT_NONE && + crypt_keyslot_destroy(cd, kp[i].new)) + log_dbg("Failed to remove keyslot %d with unbound key.", kp[i].new); + } + free(kp); + } + free(active_name); + return r; +} + +static int reencrypt_luks2_resume(struct crypt_device *cd) +{ + int r; + char *backing_file = NULL; + struct tools_progress_params prog_parms = { + .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID), + .batch_mode = ARG_SET(OPT_BATCH_MODE_ID), + .json_output = ARG_SET(OPT_PROGRESS_JSON_ID), + .interrupt_message = _("\nReencryption interrupted."), + .device = tools_get_device_name(crypt_get_device_name(cd), &backing_file) + }; + + if (ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID) && !ARG_SET(OPT_BATCH_MODE_ID)) + log_std(_("Resuming LUKS reencryption in forced offline mode.\n")); + + set_int_handler(0); + r = crypt_reencrypt_run(cd, tools_progress, &prog_parms); + free(backing_file); + return r; +} + +static int check_broken_luks_signature(const char *device) +{ + int r; + size_t count; + + r = tools_detect_signatures(device, PRB_ONLY_LUKS, &count, ARG_SET(OPT_BATCH_MODE_ID)); + if (r < 0) + return -EINVAL; + if (count) { + log_err(_("Device %s contains broken LUKS metadata. Aborting operation."), device); + return -EINVAL; + } + + return 0; +} + +static int _encrypt(struct crypt_device *cd, const char *type, enum device_status_info dev_st, int action_argc, const char **action_argv) +{ + const char *device_ptr; + enum device_status_info data_dev_st; + struct stat st; + struct crypt_device *encrypt_cd = NULL; + int r = -EINVAL; + + if (dev_st == DEVICE_LUKS2 || dev_st == DEVICE_LUKS1) { + log_err(_("Device %s is already LUKS device. Aborting operation."), + uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0])); + return -EINVAL; + } + + if (dev_st == DEVICE_NOT_LUKS && + (!ARG_SET(OPT_HEADER_ID) || !stat(ARG_STR(OPT_HEADER_ID), &st))) { + device_ptr = ARG_SET(OPT_HEADER_ID) ? ARG_STR(OPT_HEADER_ID) : action_argv[0]; + r = check_broken_luks_signature(device_ptr); + if (r < 0) + return r; + } + + /* check data device type/state */ + if (ARG_SET(OPT_HEADER_ID)) { + device_ptr = cd ? crypt_get_device_name(cd) : action_argv[0]; + data_dev_st = check_luks_device(device_ptr); + + if (data_dev_st == DEVICE_INVALID) + return -EINVAL; + + if (data_dev_st == DEVICE_LUKS2 || data_dev_st == DEVICE_LUKS1) { + log_err(_("Device %s is already LUKS device. Aborting operation."), + device_ptr); + return -EINVAL; + } + + if (data_dev_st == DEVICE_LUKS2_REENCRYPT || data_dev_st == DEVICE_LUKS1_UNUSABLE) { + log_err(_("Device %s is already in LUKS reencryption. Aborting operation."), + device_ptr); + return -EINVAL; + } + + r = check_broken_luks_signature(device_ptr); + if (r < 0) + return r; + } + + if (!type) + type = crypt_get_default_type(); + + if (dev_st == DEVICE_LUKS1_UNUSABLE || isLUKS1(type)) { + r = reencrypt_is_header_detached(ARG_STR(OPT_HEADER_ID), action_argv[0]); + if (r < 0) + return r; + if (!r && !ARG_SET(OPT_REDUCE_DEVICE_SIZE_ID)) { + log_err(_("Encryption without detached header (--header) is not possible without data device size reduction (--reduce-device-size).")); + return -ENOTSUP; + } + return reencrypt_luks1(action_argv[0]); + } else if (dev_st == DEVICE_NOT_LUKS) { + r = encrypt_luks2_init(&encrypt_cd, action_argv[0], action_argc > 1 ? action_argv[1] : NULL); + if (r < 0 || ARG_SET(OPT_INIT_ONLY_ID)) { + crypt_free(encrypt_cd); + return r; + } + cd = encrypt_cd; + dev_st = DEVICE_LUKS2_REENCRYPT; + } else if (dev_st == DEVICE_LUKS2_REENCRYPT && + (r = reencrypt_luks2_load(cd, action_argv[0])) < 0) + return r; + + if (dev_st != DEVICE_LUKS2_REENCRYPT) + return -EINVAL; + + r = reencrypt_luks2_resume(cd); + + crypt_free(encrypt_cd); + return r; +} + +static int _decrypt(struct crypt_device **cd, enum device_status_info dev_st, const char *data_device) +{ + int r; + struct stat st; + bool export_header = false; + + assert(cd); + + if (dev_st == DEVICE_LUKS1 || dev_st == DEVICE_LUKS1_UNUSABLE) + return reencrypt_luks1(data_device); + + /* header file does not exist, try loading device type from data device */ + if (dev_st == DEVICE_NOT_LUKS && ARG_SET(OPT_HEADER_ID) && + (stat(ARG_STR(OPT_HEADER_ID), &st) < 0) && errno == ENOENT) { + if (ARG_SET(OPT_ACTIVE_NAME_ID)) + dev_st = load_luks2_by_name(cd, ARG_STR(OPT_ACTIVE_NAME_ID), NULL); + else + dev_st = load_luks(cd, NULL, uuid_or_device(data_device)); + + /* + * If data device is not LUKS2 report 'header is missing' error + * message user would get originally. + */ + if (dev_st != DEVICE_LUKS2) { + log_err(_("Device %s does not exist or access denied."), + ARG_STR(OPT_HEADER_ID)); + return -EINVAL; + } + + export_header = true; + } + + if (dev_st == DEVICE_LUKS2_REENCRYPT) { + if ((r = reencrypt_luks2_load(*cd, data_device)) < 0) + return r; + } else if (dev_st == DEVICE_LUKS2) { + if (!ARG_SET(OPT_HEADER_ID)) { + log_err(_("LUKS2 decryption requires --header option.")); + return -EINVAL; + } + + if (export_header) + r = decrypt_luks2_datashift_init(cd, data_device, ARG_STR(OPT_HEADER_ID)); + else + r = decrypt_luks2_init(*cd, data_device); + + if (r < 0 || ARG_SET(OPT_INIT_ONLY_ID)) + return r; + } else if (dev_st == DEVICE_NOT_LUKS) { + log_err(_("Device %s is not a valid LUKS device."), + ARG_STR(OPT_HEADER_ID) ?: uuid_or_device(data_device)); + return -EINVAL; + } + + r = reencrypt_luks2_resume(*cd); + return r; +} + +static int _reencrypt(struct crypt_device *cd, enum device_status_info dev_st, const char *data_device) +{ + int r; + + if (dev_st == DEVICE_LUKS1 || dev_st == DEVICE_LUKS1_UNUSABLE) + return reencrypt_luks1(data_device); + else if (dev_st == DEVICE_LUKS2_REENCRYPT) { + if ((r = reencrypt_luks2_load(cd, data_device)) < 0) + return r; + } else if (dev_st == DEVICE_LUKS2) { + r = reencrypt_luks2_init(cd, data_device); + if (r < 0|| ARG_SET(OPT_INIT_ONLY_ID)) + return r; + } else + return -EINVAL; + + return reencrypt_luks2_resume(cd); +} + +int reencrypt(int action_argc, const char **action_argv) +{ + enum device_status_info dev_st; + int r = -EINVAL; + struct crypt_device *cd = NULL; + const char *type = luksType(device_type); + + if (action_argc < 1 && (!ARG_SET(OPT_ACTIVE_NAME_ID) || ARG_SET(OPT_ENCRYPT_ID))) { + log_err(_("Command requires device as argument.")); + return r; + } + + if (ARG_SET(OPT_ACTIVE_NAME_ID)) + dev_st = load_luks2_by_name(&cd, ARG_STR(OPT_ACTIVE_NAME_ID), ARG_STR(OPT_HEADER_ID)); + else + dev_st = load_luks(&cd, ARG_STR(OPT_HEADER_ID), uuid_or_device(action_argv[0])); + + if (dev_st == DEVICE_INVALID) + return r; + + if (dev_st == DEVICE_LUKS1 && isLUKS2(type)) { + log_err(_("Conflicting versions. Device %s is LUKS1."), + uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0])); + goto out; + } + + if (dev_st == DEVICE_LUKS1_UNUSABLE && isLUKS2(type)) { + log_err(_("Conflicting versions. Device %s is in LUKS1 reencryption."), + uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0])); + goto out; + } + + if (dev_st == DEVICE_LUKS2 && isLUKS1(type)) { + log_err(_("Conflicting versions. Device %s is LUKS2."), + uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0])); + goto out; + } + + if (dev_st == DEVICE_LUKS2_REENCRYPT && isLUKS1(type)) { + log_err(_("Conflicting versions. Device %s is in LUKS2 reencryption."), + uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0])); + goto out; + } + + if (dev_st == DEVICE_LUKS2_REENCRYPT && ARG_SET(OPT_INIT_ONLY_ID)) { + log_err(_("LUKS2 reencryption already initialized. Aborting operation.")); + r = -EINVAL; + goto out; + } + + if (ARG_SET(OPT_RESUME_ONLY_ID) && + (dev_st == DEVICE_LUKS2 || dev_st == DEVICE_LUKS1 || dev_st == DEVICE_NOT_LUKS)) { + log_err(_("Device reencryption not in progress.")); + r = -EINVAL; + goto out; + } + + if (ARG_SET(OPT_ENCRYPT_ID)) + r = _encrypt(cd, type, dev_st, action_argc, action_argv); + else if (ARG_SET(OPT_DECRYPT_ID)) + r = _decrypt(&cd, dev_st, action_argv[0]); + else + r = _reencrypt(cd, dev_st, action_argv[0]); + +out: + crypt_free(cd); + return r; +} diff --git a/src/utils_reencrypt_luks1.c b/src/utils_reencrypt_luks1.c new file mode 100644 index 0000000..ae849c0 --- /dev/null +++ b/src/utils_reencrypt_luks1.c @@ -0,0 +1,1354 @@ +/* + * cryptsetup - LUKS1 utility for offline re-encryption + * + * Copyright (C) 2012-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2012-2023 Milan Broz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <sys/ioctl.h> +#include <linux/fs.h> +#include <uuid/uuid.h> + +#include "cryptsetup.h" +#include "cryptsetup_args.h" +#include "utils_luks.h" + +#define NO_UUID "cafecafe-cafe-cafe-cafe-cafecafeeeee" + +extern int64_t data_shift; + +#define MAX_SLOT 8 + +struct reenc_ctx { + char *device; + char *device_header; + char *device_uuid; + const char *type; + uint64_t device_size; /* overridden by parameter */ + uint64_t device_size_new_real; + uint64_t device_size_org_real; + uint64_t device_offset; + uint64_t device_shift; + uint64_t data_offset; + + bool stained; + bool in_progress; + enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction; + enum { REENCRYPT = 0, ENCRYPT = 1, DECRYPT = 2 } reencrypt_mode; + + char header_file_org[PATH_MAX]; + char header_file_new[PATH_MAX]; + char log_file[PATH_MAX]; + + char crypt_path_org[PATH_MAX]; + char crypt_path_new[PATH_MAX]; + int log_fd; + char log_buf[SECTOR_SIZE]; + + struct { + char *password; + size_t passwordLen; + } p[MAX_SLOT]; + int keyslot; + + uint64_t resume_bytes; +}; + +char MAGIC[] = {'L','U','K','S', 0xba, 0xbe}; +char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad}; +int MAGIC_L = 6; + +typedef enum { + MAKE_UNUSABLE, + MAKE_USABLE, + CHECK_UNUSABLE, + CHECK_OPEN, +} header_magic; + +static void _quiet_log(int level, const char *msg, void *usrptr) +{ + if (!ARG_SET(OPT_DEBUG_ID)) + return; + tool_log(level, msg, usrptr); +} + +static int alignment(int fd) +{ + int alignment; + + alignment = fpathconf(fd, _PC_REC_XFER_ALIGN); + if (alignment < 0) + alignment = 4096; + return alignment; +} + +static size_t pagesize(void) +{ + long r = sysconf(_SC_PAGESIZE); + return r < 0 ? 4096 : (size_t)r; +} + +static const char *hdr_device(const struct reenc_ctx *rc) +{ + return rc->device_header ?: rc->device; +} + +/* Depends on the first two fields of LUKS1 header format, magic and version */ +static int device_check(struct reenc_ctx *rc, const char *device, header_magic set_magic, bool exclusive) +{ + char *buf = NULL; + int r, devfd; + ssize_t s; + uint16_t version; + size_t buf_size = pagesize(); + struct stat st; + + if (stat(device, &st)) { + log_err(_("Cannot open device %s."), device); + return -EINVAL; + } + + /* coverity[toctou] */ + devfd = open(device, O_RDWR | ((S_ISBLK(st.st_mode) && exclusive) ? O_EXCL : 0)); /* lgtm[cpp/toctou-race-condition] */ + if (devfd == -1) { + if (errno == EBUSY) { + log_err(_("Cannot exclusively open %s, device in use."), + device); + return -EBUSY; + } + log_err(_("Cannot open device %s."), device); + return -EINVAL; + } + + if (set_magic == CHECK_OPEN) { + r = 0; + goto out; + } + + if (posix_memalign((void *)&buf, alignment(devfd), buf_size)) { + log_err(_("Allocation of aligned memory failed.")); + r = -ENOMEM; + goto out; + } + + s = read(devfd, buf, buf_size); + if (s < 0 || s != (ssize_t)buf_size) { + log_err(_("Cannot read device %s."), device); + r = -EIO; + goto out; + } + + /* Be sure that we do not process new version of header */ + memcpy((void*)&version, &buf[MAGIC_L], sizeof(uint16_t)); + version = be16_to_cpu(version); + + if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L) && + version == 1) { + log_verbose(_("Marking LUKS1 device %s unusable."), device); + memcpy(buf, NOMAGIC, MAGIC_L); + r = 0; + } else if (set_magic == CHECK_UNUSABLE && version == 1) { + r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0; + if (rc && !r) + rc->device_uuid = strndup(&buf[0xa8], 40); + goto out; + } else + r = -EINVAL; + + if (!r && version == 1) { + if (lseek(devfd, 0, SEEK_SET) == -1) + goto out; + s = write(devfd, buf, buf_size); + if (s < 0 || s != (ssize_t)buf_size || fsync(devfd) < 0) { + log_err(_("Cannot write device %s."), device); + r = -EIO; + } + if (rc && s > 0 && set_magic == MAKE_UNUSABLE) + rc->stained = true; + } + if (r) + log_dbg("LUKS signature check failed for %s.", device); +out: + if (buf) + memset(buf, 0, buf_size); + free(buf); + close(devfd); + return r; +} + +static int create_empty_header(const char *new_file) +{ + int fd, r = 0; + + log_dbg("Creating empty file %s of size 4096.", new_file); + + /* coverity[toctou] */ + fd = open(new_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR); + if (fd == -1 || posix_fallocate(fd, 0, 4096)) + r = -EINVAL; + if (fd >= 0) + close(fd); + + return r; +} + +static int write_log(struct reenc_ctx *rc) +{ + ssize_t r; + + memset(rc->log_buf, 0, SECTOR_SIZE); + if (snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n" + "version = %d\nUUID = %s\ndirection = %d\nmode = %d\n" + "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n", + 2, rc->device_uuid, rc->reencrypt_direction, rc->reencrypt_mode, + rc->device_offset, rc->device_shift) < 0) + return -EINVAL; + + if (lseek(rc->log_fd, 0, SEEK_SET) == -1) + return -EIO; + + r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE); + if (r < 0 || r != SECTOR_SIZE) { + log_err(_("Cannot write reencryption log file.")); + return -EIO; + } + + return 0; +} + +static int parse_line_log(struct reenc_ctx *rc, const char *line) +{ + uint64_t u64; + int i; + char s[64]; + + /* whole line is comment */ + if (*line == '#') + return 0; + + if (sscanf(line, "version = %d", &i) == 1) { + if (i < 1 || i > 2) { + log_dbg("Log: Unexpected version = %i", i); + return -EINVAL; + } + } else if (sscanf(line, "UUID = %40s", s) == 1) { + if (!rc->device_uuid || strcmp(rc->device_uuid, s)) { + log_dbg("Log: Unexpected UUID %s", s); + return -EINVAL; + } + } else if (sscanf(line, "direction = %d", &i) == 1) { + log_dbg("Log: direction = %i", i); + rc->reencrypt_direction = i; + } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) { + log_dbg("Log: offset = %" PRIu64, u64); + rc->device_offset = u64; + } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) { + log_dbg("Log: shift = %" PRIu64, u64); + rc->device_shift = u64; + } else if (sscanf(line, "mode = %d", &i) == 1) { /* added in v2 */ + log_dbg("Log: mode = %i", i); + rc->reencrypt_mode = i; + if (rc->reencrypt_mode != REENCRYPT && + rc->reencrypt_mode != ENCRYPT && + rc->reencrypt_mode != DECRYPT) + return -EINVAL; + } else + return -EINVAL; + + return 0; +} + +static int parse_log(struct reenc_ctx *rc) +{ + char *start, *end; + ssize_t s; + + s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE); + if (s == -1) { + log_err(_("Cannot read reencryption log file.")); + return -EIO; + } + + rc->log_buf[SECTOR_SIZE - 1] = '\0'; + start = rc->log_buf; + do { + end = strchr(start, '\n'); + if (end) { + *end++ = '\0'; + if (parse_line_log(rc, start)) { + log_err(_("Wrong log format.")); + return -EINVAL; + } + } + + start = end; + } while (start); + + return 0; +} + +static void close_log(struct reenc_ctx *rc) +{ + log_dbg("Closing LUKS reencryption log file %s.", rc->log_file); + if (rc->log_fd != -1) + close(rc->log_fd); +} + +static int open_log(struct reenc_ctx *rc) +{ + int flags = ARG_SET(OPT_USE_FSYNC_ID) ? O_SYNC : 0; + + rc->log_fd = open(rc->log_file, O_RDWR|O_EXCL|O_CREAT|flags, S_IRUSR|S_IWUSR); + if (rc->log_fd != -1) { + log_dbg("Created LUKS reencryption log file %s.", rc->log_file); + rc->stained = 0; + } else if (errno == EEXIST) { + log_std(_("Log file %s exists, resuming reencryption.\n"), rc->log_file); + rc->log_fd = open(rc->log_file, O_RDWR|flags); + rc->in_progress = true; + } + + if (rc->log_fd == -1) + return -EINVAL; + + if (!rc->in_progress && write_log(rc) < 0) { + close_log(rc); + return -EIO; + } + + /* Be sure it is correct format */ + return parse_log(rc); +} + +static int activate_luks_headers(struct reenc_ctx *rc) +{ + struct crypt_device *cd = NULL, *cd_new = NULL; + const char *pwd_old, *pwd_new, pwd_empty[] = ""; + size_t pwd_old_len, pwd_new_len; + int r; + + log_dbg("Activating LUKS devices from headers."); + + /* Never use real password for empty header processing */ + if (rc->reencrypt_mode == REENCRYPT) { + pwd_old = rc->p[rc->keyslot].password; + pwd_old_len = rc->p[rc->keyslot].passwordLen; + pwd_new = pwd_old; + pwd_new_len = pwd_old_len; + } else if (rc->reencrypt_mode == DECRYPT) { + pwd_old = rc->p[rc->keyslot].password; + pwd_old_len = rc->p[rc->keyslot].passwordLen; + pwd_new = pwd_empty; + pwd_new_len = 0; + } else if (rc->reencrypt_mode == ENCRYPT) { + pwd_old = pwd_empty; + pwd_old_len = 0; + pwd_new = rc->p[rc->keyslot].password; + pwd_new_len = rc->p[rc->keyslot].passwordLen; + } else + return -EINVAL; + + if ((r = crypt_init_data_device(&cd, rc->header_file_org, rc->device)) || + (r = crypt_load(cd, CRYPT_LUKS1, NULL))) + goto out; + + log_verbose(_("Activating temporary device using old LUKS header.")); + if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org, + ARG_INT32(OPT_KEY_SLOT_ID), pwd_old, pwd_old_len, + CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0) + goto out; + + if ((r = crypt_init_data_device(&cd_new, rc->header_file_new, rc->device)) || + (r = crypt_load(cd_new, CRYPT_LUKS1, NULL))) + goto out; + + log_verbose(_("Activating temporary device using new LUKS header.")); + if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new, + ARG_INT32(OPT_KEY_SLOT_ID), pwd_new, pwd_new_len, + CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0) + goto out; + r = 0; +out: + crypt_free(cd); + crypt_free(cd_new); + if (r < 0) + log_err(_("Activation of temporary devices failed.")); + return r; +} + +static int create_new_keyslot(struct reenc_ctx *rc, int keyslot, + struct crypt_device *cd_old, + struct crypt_device *cd_new) +{ + int r; + char *key = NULL; + size_t key_size; + + if (cd_old && crypt_keyslot_status(cd_old, keyslot) == CRYPT_SLOT_UNBOUND) { + key_size = 4096; + key = crypt_safe_alloc(key_size); + if (!key) + return -ENOMEM; + r = crypt_volume_key_get(cd_old, keyslot, key, &key_size, + rc->p[keyslot].password, rc->p[keyslot].passwordLen); + if (r == keyslot) { + r = crypt_keyslot_add_by_key(cd_new, keyslot, key, key_size, + rc->p[keyslot].password, rc->p[keyslot].passwordLen, + CRYPT_VOLUME_KEY_NO_SEGMENT); + } else + r = -EINVAL; + crypt_safe_free(key); + } else + r = crypt_keyslot_add_by_volume_key(cd_new, keyslot, NULL, 0, + rc->p[keyslot].password, rc->p[keyslot].passwordLen); + + return r; +} + +static int create_new_header(struct reenc_ctx *rc, struct crypt_device *cd_old, + const char *cipher, const char *cipher_mode, + const char *uuid, + const char *key, int key_size, + uint64_t metadata_size, + uint64_t keyslots_size, + void *params) +{ + struct crypt_device *cd_new = NULL; + int i, r; + + if ((r = crypt_init(&cd_new, rc->header_file_new))) + goto out; + + if (ARG_SET(OPT_USE_RANDOM_ID)) + crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM); + else if (ARG_SET(OPT_USE_URANDOM_ID)) + crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM); + + r = set_pbkdf_params(cd_new, CRYPT_LUKS1); + if (r) { + log_err(_("Failed to set pbkdf parameters.")); + goto out; + } + + r = crypt_set_data_offset(cd_new, rc->data_offset); + if (r) { + log_err(_("Failed to set data offset.")); + goto out; + } + + r = crypt_set_metadata_size(cd_new, metadata_size, keyslots_size); + if (r) { + log_err(_("Failed to set metadata size.")); + goto out; + } + + r = crypt_format(cd_new, CRYPT_LUKS1, cipher, cipher_mode, uuid, key, key_size, params); + check_signal(&r); + if (r < 0) + goto out; + log_verbose(_("New LUKS header for device %s created."), rc->device); + + for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) { + if (!rc->p[i].password) + continue; + + r = create_new_keyslot(rc, i, cd_old, cd_new); + check_signal(&r); + if (r < 0) + goto out; + tools_keyslot_msg(r, CREATED); + r = 0; + } +out: + crypt_free(cd_new); + return r; +} + +static int backup_luks_headers(struct reenc_ctx *rc) +{ + struct crypt_device *cd = NULL; + struct crypt_params_luks1 params = {0}; + char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN]; + char *key = NULL; + size_t key_size; + uint64_t mdata_size = 0, keyslots_size = 0; + int r; + + log_dbg("Creating LUKS header backup for device %s.", hdr_device(rc)); + + if ((r = crypt_init(&cd, hdr_device(rc))) || + (r = crypt_load(cd, CRYPT_LUKS1, NULL))) + goto out; + + if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rc->header_file_org))) + goto out; + + log_verbose(_("%s header backup of device %s created."), "LUKS1", rc->device); + + /* For decrypt, new header will be fake one, so we are done here. */ + if (rc->reencrypt_mode == DECRYPT) + goto out; + + rc->data_offset = crypt_get_data_offset(cd) + ROUND_SECTOR(ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID)); + + if ((r = create_empty_header(rc->header_file_new))) + goto out; + + params.hash = ARG_STR(OPT_HASH_ID) ?: DEFAULT_LUKS1_HASH; + params.data_device = rc->device; + + if (ARG_SET(OPT_CIPHER_ID)) { + r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID), cipher, NULL, cipher_mode); + if (r < 0) { + log_err(_("No known cipher specification pattern detected.")); + goto out; + } + } + + key_size = ARG_SET(OPT_KEY_SIZE_ID) ? ARG_UINT32(OPT_KEY_SIZE_ID) / 8 : (uint32_t)crypt_get_volume_key_size(cd); + + if (ARG_SET(OPT_KEEP_KEY_ID)) { + log_dbg("Keeping key from old header."); + key_size = crypt_get_volume_key_size(cd); + key = crypt_safe_alloc(key_size); + if (!key) { + r = -ENOMEM; + goto out; + } + r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, key, &key_size, + rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen); + } else if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) { + log_dbg("Loading new key from file."); + r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &key, key_size); + } + + if (r < 0) + goto out; + + r = create_new_header(rc, cd, + ARG_SET(OPT_CIPHER_ID) ? cipher : crypt_get_cipher(cd), + ARG_SET(OPT_CIPHER_ID) ? cipher_mode : crypt_get_cipher_mode(cd), + crypt_get_uuid(cd), + key, + key_size, + mdata_size, + keyslots_size, + (void*)¶ms); + +out: + crypt_free(cd); + crypt_safe_free(key); + if (r) + log_err(_("Creation of LUKS backup headers failed.")); + return r; +} + +/* Create fake header for original device */ +static int backup_fake_header(struct reenc_ctx *rc) +{ + struct crypt_device *cd_new = NULL; + struct crypt_params_luks1 params = {0}; + char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN]; + const char *header_file_fake; + int r; + + log_dbg("Creating fake (cipher_null) header for %s device.", + (rc->reencrypt_mode == DECRYPT) ? "new" : "original"); + + header_file_fake = (rc->reencrypt_mode == DECRYPT) ? rc->header_file_new : rc->header_file_org; + + if (!ARG_SET(OPT_KEY_SIZE_ID)) + ARG_SET_UINT32(OPT_KEY_SIZE_ID, DEFAULT_LUKS1_KEYBITS); + + if (ARG_SET(OPT_CIPHER_ID)) { + r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID), cipher, NULL, cipher_mode); + if (r < 0) { + log_err(_("No known cipher specification pattern detected.")); + goto out; + } + } + + r = create_empty_header(header_file_fake); + if (r < 0) + return r; + + params.hash = ARG_STR(OPT_HASH_ID) ?: DEFAULT_LUKS1_HASH; + params.data_alignment = 0; + params.data_device = rc->device; + + r = crypt_init(&cd_new, header_file_fake); + if (r < 0) + return r; + + r = crypt_format(cd_new, CRYPT_LUKS1, "cipher_null", "ecb", + NO_UUID, NULL, ARG_UINT32(OPT_KEY_SIZE_ID) / 8, ¶ms); + check_signal(&r); + if (r < 0) + goto out; + + r = crypt_keyslot_add_by_volume_key(cd_new, rc->keyslot, NULL, 0, + rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen); + check_signal(&r); + if (r < 0) + goto out; + + /* The real header is backup header created in backup_luks_headers() */ + if (rc->reencrypt_mode == DECRYPT) { + r = 0; + goto out; + } + + r = create_empty_header(rc->header_file_new); + if (r < 0) + goto out; + + params.data_alignment = ROUND_SECTOR(ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID)); + r = create_new_header(rc, NULL, + ARG_SET(OPT_CIPHER_ID) ? cipher : DEFAULT_LUKS1_CIPHER, + ARG_SET(OPT_CIPHER_ID) ? cipher_mode : DEFAULT_LUKS1_MODE, + NULL, NULL, + ARG_UINT32(OPT_KEY_SIZE_ID) / 8, + 0, + 0, + (void*)¶ms); +out: + crypt_free(cd_new); + return r; +} + +static void remove_headers(struct reenc_ctx *rc) +{ + struct crypt_device *cd = NULL; + + log_dbg("Removing headers."); + + if (crypt_init(&cd, NULL)) + return; + crypt_set_log_callback(cd, _quiet_log, NULL); + if (*rc->header_file_org) + (void)crypt_deactivate(cd, rc->header_file_org); + if (*rc->header_file_new) + (void)crypt_deactivate(cd, rc->header_file_new); + crypt_free(cd); +} + +static int restore_luks_header(struct reenc_ctx *rc) +{ + struct stat st; + struct crypt_device *cd = NULL; + int fd, r; + + log_dbg("Restoring header for %s from %s.", hdr_device(rc), rc->header_file_new); + + /* + * For new encryption and new detached header in file just move it. + * For existing file try to ensure we have preallocated space for restore. + */ + if (ARG_SET(OPT_ENCRYPT_ID) && rc->device_header) { + r = stat(rc->device_header, &st); + if (r == -1) { + r = rename(rc->header_file_new, rc->device_header); + goto out; + } else if ((st.st_mode & S_IFMT) == S_IFREG && + stat(rc->header_file_new, &st) != -1) { + /* coverity[toctou] */ + fd = open(rc->device_header, O_WRONLY); + if (fd != -1) { + if (posix_fallocate(fd, 0, st.st_size)) {}; + close(fd); + } + } + } + + r = crypt_init(&cd, hdr_device(rc)); + if (r == 0) { + r = crypt_header_restore(cd, CRYPT_LUKS1, rc->header_file_new); + } + + crypt_free(cd); +out: + if (r) + log_err(_("Cannot restore %s header on device %s."), "LUKS1", hdr_device(rc)); + else { + log_verbose(_("%s header on device %s restored."), "LUKS1", hdr_device(rc)); + rc->stained = false; + } + return r; +} + +static ssize_t read_buf(int fd, void *buf, size_t count) +{ + size_t read_size = 0; + ssize_t s; + + do { + /* This expects that partial read is aligned in buffer */ + s = read(fd, buf, count - read_size); + if (s == -1 && errno != EINTR) + return s; + if (s == 0) + return (ssize_t)read_size; + if (s > 0) { + if (s != (ssize_t)count) + log_dbg("Partial read %zd / %zu.", s, count); + read_size += (size_t)s; + buf = (uint8_t*)buf + s; + } + } while (read_size != count); + + return (ssize_t)count; +} + +static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new, + size_t block_size, void *buf, uint64_t *bytes) +{ + ssize_t s1, s2; + int r = -EIO; + char *backing_file = NULL; + struct tools_progress_params prog_parms = { + .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID), + .batch_mode = ARG_SET(OPT_BATCH_MODE_ID), + .json_output = ARG_SET(OPT_PROGRESS_JSON_ID), + .interrupt_message = _("\nReencryption interrupted."), + .device = tools_get_device_name(rc->device, &backing_file) + }; + + log_dbg("Reencrypting in forward direction."); + + if (lseek(fd_old, rc->device_offset, SEEK_SET) < 0 || + lseek(fd_new, rc->device_offset, SEEK_SET) < 0) { + log_err(_("Cannot seek to device offset.")); + goto out; + } + + rc->resume_bytes = *bytes = rc->device_offset; + + tools_progress(rc->device_size, *bytes, &prog_parms); + + if (write_log(rc) < 0) + goto out; + + while (!quit && rc->device_offset < rc->device_size) { + if ((rc->device_size - rc->device_offset) < (uint64_t)block_size) + block_size = rc->device_size - rc->device_offset; + s1 = read_buf(fd_old, buf, block_size); + if (s1 < 0 || ((size_t)s1 != block_size && + (rc->device_offset + s1) != rc->device_size)) { + log_dbg("Read error, expecting %zu, got %zd.", + block_size, s1); + goto out; + } + + /* If device_size is forced, never write more than limit */ + if ((s1 + rc->device_offset) > rc->device_size) + s1 = rc->device_size - rc->device_offset; + + s2 = write(fd_new, buf, s1); + if (s2 < 0) { + log_dbg("Write error, expecting %zu, got %zd.", + block_size, s2); + goto out; + } + + rc->device_offset += s1; + if (ARG_SET(OPT_WRITE_LOG_ID) && write_log(rc) < 0) + goto out; + + if (ARG_SET(OPT_USE_FSYNC_ID) && fsync(fd_new) < 0) { + log_dbg("Write error, fsync."); + goto out; + } + + *bytes += (uint64_t)s2; + + tools_progress(rc->device_size, *bytes, &prog_parms); + } + + r = 0; +out: + free(backing_file); + return quit ? -EAGAIN : r; +} + +static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new, + size_t block_size, void *buf, uint64_t *bytes) +{ + ssize_t s1, s2, working_block; + off_t working_offset; + int r = -EIO; + char *backing_file = NULL; + struct tools_progress_params prog_parms = { + .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID), + .batch_mode = ARG_SET(OPT_BATCH_MODE_ID), + .json_output = ARG_SET(OPT_PROGRESS_JSON_ID), + .interrupt_message = _("\nReencryption interrupted."), + .device = tools_get_device_name(rc->device, &backing_file) + }; + + log_dbg("Reencrypting in backward direction."); + + if (!rc->in_progress) { + rc->device_offset = rc->device_size; + rc->resume_bytes = 0; + *bytes = 0; + } else { + rc->resume_bytes = rc->device_size - rc->device_offset; + *bytes = rc->resume_bytes; + } + + tools_progress(rc->device_size, *bytes, &prog_parms); + + if (write_log(rc) < 0) + goto out; + + /* dirty the device during ENCRYPT mode */ + rc->stained = true; + + while (!quit && rc->device_offset) { + if (rc->device_offset < block_size) { + working_offset = 0; + working_block = rc->device_offset; + } else { + working_offset = rc->device_offset - block_size; + working_block = block_size; + } + + if (lseek(fd_old, working_offset, SEEK_SET) < 0 || + lseek(fd_new, working_offset, SEEK_SET) < 0) { + log_err(_("Cannot seek to device offset.")); + goto out; + } + + s1 = read_buf(fd_old, buf, working_block); + if (s1 < 0 || (s1 != working_block)) { + log_dbg("Read error, expecting %zu, got %zd.", + block_size, s1); + goto out; + } + + s2 = write(fd_new, buf, working_block); + if (s2 < 0) { + log_dbg("Write error, expecting %zu, got %zd.", + block_size, s2); + goto out; + } + + rc->device_offset -= s1; + if (ARG_SET(OPT_WRITE_LOG_ID) && write_log(rc) < 0) + goto out; + + if (ARG_SET(OPT_USE_FSYNC_ID) && fsync(fd_new) < 0) { + log_dbg("Write error, fsync."); + goto out; + } + + *bytes += (uint64_t)s2; + + tools_progress(rc->device_size, *bytes, &prog_parms); + } + + r = 0; +out: + free(backing_file); + return quit ? -EAGAIN : r; +} + +static void zero_rest_of_device(int fd, size_t block_size, void *buf, + uint64_t *bytes, uint64_t offset) +{ + ssize_t s1, s2; + + log_dbg("Zeroing rest of device."); + + if (lseek(fd, offset, SEEK_SET) < 0) { + log_dbg("Cannot seek to device offset."); + return; + } + + memset(buf, 0, block_size); + s1 = block_size; + + while (!quit && *bytes) { + if (*bytes < (uint64_t)s1) + s1 = *bytes; + + s2 = write(fd, buf, s1); + if (s2 != s1) { + log_dbg("Write error, expecting %zd, got %zd.", + s1, s2); + return; + } + + if (ARG_SET(OPT_USE_FSYNC_ID) && fsync(fd) < 0) { + log_dbg("Write error, fsync."); + return; + } + + *bytes -= s2; + } +} + +static int copy_data(struct reenc_ctx *rc) +{ + size_t block_size = ARG_UINT32(OPT_BLOCK_SIZE_ID) * 1024 * 1024; + int fd_old = -1, fd_new = -1; + int r = -EINVAL; + void *buf = NULL; + uint64_t bytes = 0; + + log_dbg("Data copy preparation."); + + fd_old = open(rc->crypt_path_org, O_RDONLY | (ARG_SET(OPT_USE_DIRECTIO_ID) ? O_DIRECT : 0)); + if (fd_old == -1) { + log_err(_("Cannot open temporary LUKS device.")); + goto out; + } + + fd_new = open(rc->crypt_path_new, O_WRONLY | (ARG_SET(OPT_USE_DIRECTIO_ID) ? O_DIRECT : 0)); + if (fd_new == -1) { + log_err(_("Cannot open temporary LUKS device.")); + goto out; + } + + if (ioctl(fd_old, BLKGETSIZE64, &rc->device_size_org_real) < 0) { + log_err(_("Cannot get device size.")); + goto out; + } + + if (ioctl(fd_new, BLKGETSIZE64, &rc->device_size_new_real) < 0) { + log_err(_("Cannot get device size.")); + goto out; + } + + if (ARG_SET(OPT_DEVICE_SIZE_ID)) + rc->device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID); + else if (rc->reencrypt_mode == DECRYPT) + rc->device_size = rc->device_size_org_real; + else + rc->device_size = rc->device_size_new_real; + + if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) { + log_err(_("Allocation of aligned memory failed.")); + r = -ENOMEM; + goto out; + } + + set_int_handler(0); + + if (rc->reencrypt_direction == FORWARD) + r = copy_data_forward(rc, fd_old, fd_new, block_size, buf, &bytes); + else + r = copy_data_backward(rc, fd_old, fd_new, block_size, buf, &bytes); + + /* Zero (wipe) rest of now plain-only device when decrypting. + * (To not leave any sign of encryption here.) */ + if (!r && rc->reencrypt_mode == DECRYPT && + rc->device_size_new_real > rc->device_size_org_real) { + bytes = rc->device_size_new_real - rc->device_size_org_real; + zero_rest_of_device(fd_new, block_size, buf, &bytes, rc->device_size_org_real); + } + + set_int_block(1); + + if (r < 0 && r != -EAGAIN) + log_err(_("IO error during reencryption.")); + + (void)write_log(rc); +out: + if (fd_old != -1) + close(fd_old); + if (fd_new != -1) + close(fd_new); + free(buf); + return r; +} + +static int initialize_uuid(struct reenc_ctx *rc) +{ + struct crypt_device *cd = NULL; + int r; + uuid_t device_uuid; + + log_dbg("Initialising UUID."); + + if (ARG_SET(OPT_ENCRYPT_ID)) { + rc->device_uuid = strdup(NO_UUID); + return 0; + } + + if (ARG_SET(OPT_DECRYPT_ID) && ARG_SET(OPT_UUID_ID)) { + r = uuid_parse(ARG_STR(OPT_UUID_ID), device_uuid); + if (!r) + rc->device_uuid = strdup(ARG_STR(OPT_UUID_ID)); + else + log_err(_("Provided UUID is invalid.")); + + return r; + } + + /* Try to load LUKS from device */ + if ((r = crypt_init(&cd, hdr_device(rc)))) + return r; + crypt_set_log_callback(cd, _quiet_log, NULL); + r = crypt_load(cd, CRYPT_LUKS1, NULL); + if (!r) + rc->device_uuid = strdup(crypt_get_uuid(cd)); + else + /* Reencryption already in progress - magic header? */ + r = device_check(rc, hdr_device(rc), CHECK_UNUSABLE, true); + + crypt_free(cd); + return r; +} + +static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd, + const char *msg, int slot_to_check, int check, int verify) +{ + crypt_keyslot_info ki; + char *password; + int r = -EINVAL, retry_count; + size_t passwordLen; + + /* mode ENCRYPT call this without header */ + if (cd && slot_to_check != CRYPT_ANY_SLOT) { + ki = crypt_keyslot_status(cd, slot_to_check); + if (ki < CRYPT_SLOT_ACTIVE) + return -ENOENT; + } else + ki = CRYPT_SLOT_ACTIVE; + + retry_count = ARG_UINT32(OPT_TRIES_ID) ?: 1; + while (retry_count--) { + r = tools_get_key(msg, &password, &passwordLen, 0, 0, + NULL /*opt_key_file*/, 0, verify, 0 /*pwquality*/, cd); + if (r < 0) + return r; + if (quit) { + crypt_safe_free(password); + password = NULL; + passwordLen = 0; + return -EAGAIN; + } + + if (check) + r = crypt_activate_by_passphrase(cd, NULL, slot_to_check, + password, passwordLen, CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY); + else + r = (slot_to_check == CRYPT_ANY_SLOT) ? 0 : slot_to_check; + + if (r < 0) { + crypt_safe_free(password); + password = NULL; + passwordLen = 0; + } + if (r < 0 && r != -EPERM) + return r; + + if (r >= 0) { + tools_keyslot_msg(r, UNLOCKED); + rc->p[r].password = password; + rc->p[r].passwordLen = passwordLen; + if (ki != CRYPT_SLOT_UNBOUND) + rc->keyslot = r; + break; + } + tools_passphrase_msg(r); + } + + password = NULL; + passwordLen = 0; + + return r; +} + +static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check) +{ + char *password; + int r; + size_t passwordLen; + + r = tools_get_key(NULL, &password, &passwordLen, ARG_UINT64(OPT_KEYFILE_OFFSET_ID), + ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), 0, 0, 0, cd); + if (r < 0) + return r; + + /* mode ENCRYPT call this without header */ + if (cd) { + r = crypt_activate_by_passphrase(cd, NULL, slot_check, password, + passwordLen, 0); + + /* + * Allow keyslot only if it is last slot or if user explicitly + * specify which slot to use (IOW others will be disabled). + */ + if (r >= 0 && ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT && + crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) { + log_err(_("Key file can be used only with --key-slot or with " + "exactly one key slot active.")); + r = -EINVAL; + } + } else { + r = slot_check == CRYPT_ANY_SLOT ? 0 : slot_check; + } + + if (r < 0) { + crypt_safe_free(password); + tools_passphrase_msg(r); + } else { + rc->keyslot = r; + rc->p[r].password = password; + rc->p[r].passwordLen = passwordLen; + } + + password = NULL; + passwordLen = 0; + + return r; +} + +static int initialize_passphrase(struct reenc_ctx *rc, const char *device) +{ + struct crypt_device *cd = NULL; + char msg[256]; + int i, r; + + log_dbg("Passphrases initialization."); + + if (rc->reencrypt_mode == ENCRYPT && !rc->in_progress) { + if (ARG_SET(OPT_KEY_FILE_ID)) + r = init_keyfile(rc, NULL, ARG_INT32(OPT_KEY_SLOT_ID)); + else + r = init_passphrase1(rc, NULL, _("Enter new passphrase: "), ARG_INT32(OPT_KEY_SLOT_ID), 0, 1); + return r > 0 ? 0 : r; + } + + if ((r = crypt_init_data_device(&cd, device, rc->device)) || + (r = crypt_load(cd, CRYPT_LUKS1, NULL))) { + crypt_free(cd); + return r; + } + + if (ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT) + snprintf(msg, sizeof(msg), + _("Enter passphrase for key slot %d: "), ARG_INT32(OPT_KEY_SLOT_ID)); + else + snprintf(msg, sizeof(msg), _("Enter any existing passphrase: ")); + + if (ARG_SET(OPT_KEY_FILE_ID)) { + r = init_keyfile(rc, cd, ARG_INT32(OPT_KEY_SLOT_ID)); + } else if (rc->in_progress || + ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT || + rc->reencrypt_mode == DECRYPT) { + r = init_passphrase1(rc, cd, msg, ARG_INT32(OPT_KEY_SLOT_ID), 1, 0); + } else for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) { + snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %d: "), i); + r = init_passphrase1(rc, cd, msg, i, 1, 0); + if (r == -ENOENT) { + r = 0; + continue; + } + if (r < 0) + break; + } + + crypt_free(cd); + return r > 0 ? 0 : r; +} + +static int initialize_context(struct reenc_ctx *rc, const char *device) +{ + log_dbg("Initialising reencryption context."); + + memset(rc, 0, sizeof(*rc)); + + rc->in_progress = false; + rc->stained = true; + rc->log_fd = -1; + + if (!(rc->device = strndup(device, PATH_MAX))) + return -ENOMEM; + + if (ARG_SET(OPT_HEADER_ID) && !(rc->device_header = strndup(ARG_STR(OPT_HEADER_ID), PATH_MAX))) + return -ENOMEM; + + if (device_check(rc, rc->device, CHECK_OPEN, true) < 0) + return -EINVAL; + + if (initialize_uuid(rc)) { + log_err(_("Device %s is not a valid LUKS device."), device); + return -EINVAL; + } + + if (ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT && + ARG_INT32(OPT_KEY_SLOT_ID) >= crypt_keyslot_max(CRYPT_LUKS1)) { + log_err(_("Key slot is invalid.")); + return -EINVAL; + } + + /* Prepare device names */ + if (snprintf(rc->log_file, PATH_MAX, + "LUKS-%s.log", rc->device_uuid) < 0) + return -ENOMEM; + if (snprintf(rc->header_file_org, PATH_MAX, + "LUKS-%s.org", rc->device_uuid) < 0) + return -ENOMEM; + if (snprintf(rc->header_file_new, PATH_MAX, + "LUKS-%s.new", rc->device_uuid) < 0) + return -ENOMEM; + + /* Paths to encrypted devices */ + if (snprintf(rc->crypt_path_org, PATH_MAX, + "%s/%s", crypt_get_dir(), rc->header_file_org) < 0) + return -ENOMEM; + if (snprintf(rc->crypt_path_new, PATH_MAX, + "%s/%s", crypt_get_dir(), rc->header_file_new) < 0) + return -ENOMEM; + + remove_headers(rc); + + if (open_log(rc) < 0) { + log_err(_("Cannot open reencryption log file.")); + return -EINVAL; + } + + if (!rc->in_progress) { + if (ARG_SET(OPT_UUID_ID)) { + log_err(_("No decryption in progress, provided UUID can " + "be used only to resume suspended decryption process.")); + return -EINVAL; + } + + if (!ARG_SET(OPT_REDUCE_DEVICE_SIZE_ID)) + rc->reencrypt_direction = FORWARD; + else { + rc->reencrypt_direction = BACKWARD; + rc->device_offset = (uint64_t)~0; + } + + if (ARG_SET(OPT_ENCRYPT_ID)) + rc->reencrypt_mode = ENCRYPT; + else if (ARG_SET(OPT_DECRYPT_ID)) + rc->reencrypt_mode = DECRYPT; + else + rc->reencrypt_mode = REENCRYPT; + } + + return 0; +} + +static void destroy_context(struct reenc_ctx *rc) +{ + int i; + + log_dbg("Destroying reencryption context."); + + close_log(rc); + remove_headers(rc); + + if (!rc->stained) { + unlink(rc->log_file); + unlink(rc->header_file_org); + unlink(rc->header_file_new); + } + + for (i = 0; i < MAX_SLOT; i++) + crypt_safe_free(rc->p[i].password); + + free(rc->device); + free(rc->device_header); + free(rc->device_uuid); +} + +int reencrypt_luks1(const char *device) +{ + int r = -EINVAL; + struct reenc_ctx *rc; + + rc = malloc(sizeof(*rc)); + if (!rc) + return -ENOMEM; + + if (!ARG_SET(OPT_BATCH_MODE_ID)) + log_verbose(_("Reencryption will change: %s%s%s%s%s%s."), + ARG_SET(OPT_KEEP_KEY_ID) ? "" : _("volume key"), + (!ARG_SET(OPT_KEEP_KEY_ID) && ARG_SET(OPT_HASH_ID)) ? ", " : "", + ARG_SET(OPT_HASH_ID) ? _("set hash to ") : "", ARG_STR(OPT_HASH_ID) ?: "", + ARG_SET(OPT_CIPHER_ID) ? _(", set cipher to "): "", ARG_STR(OPT_CIPHER_ID) ?: ""); + /* FIXME: block all non pbkdf2 pkdfs */ + + set_int_handler(0); + + if (initialize_context(rc, device)) + goto out; + + log_dbg("Running reencryption."); + + if (!rc->in_progress) { + if ((r = initialize_passphrase(rc, hdr_device(rc)))) + goto out; + + log_dbg("Storing backup of LUKS headers."); + if (rc->reencrypt_mode == ENCRYPT) { + /* Create fake header for existing device */ + if ((r = backup_fake_header(rc))) + goto out; + } else { + if ((r = backup_luks_headers(rc))) + goto out; + /* Create fake header for decrypted device */ + if (rc->reencrypt_mode == DECRYPT && + (r = backup_fake_header(rc))) + goto out; + if ((r = device_check(rc, hdr_device(rc), MAKE_UNUSABLE, true))) + goto out; + } + } else { + if ((r = initialize_passphrase(rc, ARG_SET(OPT_DECRYPT_ID) ? rc->header_file_org : rc->header_file_new))) + goto out; + } + + if (!ARG_SET(OPT_KEEP_KEY_ID)) { + log_dbg("Running data area reencryption."); + if ((r = activate_luks_headers(rc))) + goto out; + + if ((r = copy_data(rc))) + goto out; + } else + log_dbg("Keeping existing key, skipping data area reencryption."); + + // FIXME: fix error path above to not skip this + if (rc->reencrypt_mode != DECRYPT) + r = restore_luks_header(rc); + else + rc->stained = false; +out: + destroy_context(rc); + free(rc); + + return r; +} + +int reencrypt_luks1_in_progress(const char *device) +{ + struct stat st; + + if (stat(device, &st) || (size_t)st.st_size < pagesize()) + return -EINVAL; + + return device_check(NULL, device, CHECK_UNUSABLE, false); +} diff --git a/src/utils_tools.c b/src/utils_tools.c new file mode 100644 index 0000000..a0e2ebc --- /dev/null +++ b/src/utils_tools.c @@ -0,0 +1,468 @@ +/* + * cryptsetup - setup cryptographic volumes for dm-crypt + * + * Copyright (C) 2004 Jana Saout <jana@saout.de> + * Copyright (C) 2004-2007 Clemens Fruhwirth <clemens@endorphin.org> + * Copyright (C) 2009-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2009-2023 Milan Broz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "cryptsetup.h" +#include <signal.h> + +/* interrupt handling */ +volatile int quit = 0; +static int signals_blocked = 0; + +static void int_handler(int sig __attribute__((__unused__))) +{ + quit++; +} + +int tools_signals_blocked(void) +{ + return signals_blocked; +} + +void set_int_block(int block) +{ + sigset_t signals_open; + + log_dbg("%slocking interruption on signal.", block ? "B" : "Unb"); + + sigemptyset(&signals_open); + sigaddset(&signals_open, SIGINT); + sigaddset(&signals_open, SIGTERM); + sigprocmask(block ? SIG_SETMASK : SIG_UNBLOCK, &signals_open, NULL); + signals_blocked = block; + quit = 0; +} + +void set_int_handler(int block) +{ + struct sigaction sigaction_open; + + log_dbg("Installing SIGINT/SIGTERM handler."); + memset(&sigaction_open, 0, sizeof(struct sigaction)); + sigaction_open.sa_handler = int_handler; + sigaction(SIGINT, &sigaction_open, 0); + sigaction(SIGTERM, &sigaction_open, 0); + set_int_block(block); +} + +void check_signal(int *r) +{ + if (quit && !*r) + *r = -EINTR; +} + +void tool_log(int level, const char *msg, void *usrptr) +{ + struct tools_log_params *params = (struct tools_log_params *)usrptr; + + switch (level) { + + case CRYPT_LOG_NORMAL: + fprintf(stdout, "%s", msg); + break; + case CRYPT_LOG_VERBOSE: + if (params && params->verbose) + fprintf(stdout, "%s", msg); + break; + case CRYPT_LOG_ERROR: + fprintf(stderr, "%s", msg); + break; + case CRYPT_LOG_DEBUG_JSON: + case CRYPT_LOG_DEBUG: + if (params && params->debug) + fprintf(stdout, "# %s", msg); + break; + } +} + +void quiet_log(int level, const char *msg, void *usrptr) +{ + struct tools_log_params *params = (struct tools_log_params *)usrptr; + + if ((!params || !params->verbose) && (level == CRYPT_LOG_ERROR || level == CRYPT_LOG_NORMAL)) + return; + tool_log(level, msg, usrptr); +} + +static int _dialog(const char *msg, void *usrptr, int default_answer) +{ + const char *fail_msg = (const char *)usrptr; + char *answer = NULL; + size_t size = 0; + int r = default_answer, block; + + block = tools_signals_blocked(); + if (block) + set_int_block(0); + + if (isatty(STDIN_FILENO)) { + log_std(_("\nWARNING!\n========\n")); + /* TRANSLATORS: User must type "YES" (in capital letters), do not translate this word. */ + log_std(_("%s\n\nAre you sure? (Type 'yes' in capital letters): "), msg); + fflush(stdout); + if(getline(&answer, &size, stdin) == -1) { + r = 0; + /* Aborted by signal */ + if (!quit) + log_err(_("Error reading response from terminal.")); + else + log_dbg("Query interrupted on signal."); + } else { + r = !strcmp(answer, "YES\n"); + if (!r && fail_msg) + log_err("%s", fail_msg); + } + } + + if (block && !quit) + set_int_block(1); + + free(answer); + return r; +} + +int yesDialog(const char *msg, void *usrptr) +{ + return _dialog(msg, usrptr, 1); +} + +int noDialog(const char *msg, void *usrptr) +{ + return _dialog(msg, usrptr, 0); +} + +void show_status(int errcode) +{ + char *crypt_error; + + if (!errcode) { + log_verbose(_("Command successful.")); + return; + } + + if (errcode < 0) + errcode = translate_errno(errcode); + + if (errcode == 1) + crypt_error = _("wrong or missing parameters"); + else if (errcode == 2) + crypt_error = _("no permission or bad passphrase"); + else if (errcode == 3) + crypt_error = _("out of memory"); + else if (errcode == 4) + crypt_error = _("wrong device or file specified"); + else if (errcode == 5) + crypt_error = _("device already exists or device is busy"); + else + crypt_error = _("unknown error"); + + log_verbose(_("Command failed with code %i (%s)."), -errcode, crypt_error); +} + +const char *uuid_or_device(const char *spec) +{ + static char device[PATH_MAX]; + char s, *ptr; + int i = 0, uuid_len = 5; + + /* Check if it is correct UUID=<LUKS_UUID> format */ + if (spec && !strncmp(spec, "UUID=", uuid_len)) { + strcpy(device, "/dev/disk/by-uuid/"); + ptr = &device[strlen(device)]; + i = uuid_len; + while ((s = spec[i++]) && i < (PATH_MAX - 13)) { + if (!isxdigit(s) && s != '-') + return spec; /* Bail it out */ + if (isalpha(s)) + s = tolower(s); + *ptr++ = s; + } + *ptr = '\0'; + return device; + } + + return spec; +} + +__attribute__ ((noreturn)) void usage(poptContext popt_context, + int exitcode, const char *error, + const char *more) +{ + poptPrintUsage(popt_context, stderr, 0); + if (error) + log_err("%s: %s", more, error); + tools_cleanup(); + poptFreeContext(popt_context); + exit(exitcode); +} + +void dbg_version_and_cmd(int argc, const char **argv) +{ + int i; + + log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION); + for (i = 0; i < argc; i++) { + if (i) + log_std(" "); + log_std("%s", argv[i]); + } + log_std("\"\n"); +} + +/* Translate exit code to simple codes */ +int translate_errno(int r) +{ + switch (r) { + case 0: r = EXIT_SUCCESS; break; + case -EEXIST: + case -EBUSY: r = 5; break; + case -ENOTBLK: + case -ENODEV: r = 4; break; + case -ENOMEM: r = 3; break; + case -EPERM: r = 2; break; + case -EINVAL: + case -ENOENT: + case -ENOSYS: + default: r = EXIT_FAILURE; + } + return r; +} + +void tools_keyslot_msg(int keyslot, crypt_object_op op) +{ + if (keyslot < 0) + return; + + if (op == CREATED) + log_verbose(_("Key slot %i created."), keyslot); + else if (op == UNLOCKED) + log_verbose(_("Key slot %i unlocked."), keyslot); + else if (op == REMOVED) + log_verbose(_("Key slot %i removed."), keyslot); +} + +void tools_token_msg(int token, crypt_object_op op) +{ + if (token < 0) + return; + + if (op == CREATED) + log_verbose(_("Token %i created."), token); + else if (op == REMOVED) + log_verbose(_("Token %i removed."), token); +} + +void tools_token_error_msg(int error, const char *type, int token, bool pin_provided) +{ + if (error >= 0) + return; + + if (error == -ENOANO) { + if (pin_provided) + log_verbose(_("No token could be unlocked with this PIN.")); + else if (token != CRYPT_ANY_TOKEN) + log_verbose(_("Token %i requires PIN."), token); + else if (type) + log_verbose(_("Token (type %s) requires PIN."), type); + } else if (error == -EPERM) { + if (token != CRYPT_ANY_TOKEN) + log_verbose(_("Token %i cannot unlock assigned keyslot(s) (wrong keyslot passphrase)."), token); + else if (type) + log_verbose(_("Token (type %s) cannot unlock assigned keyslot(s) (wrong keyslot passphrase)."), type); + } if (error == -EAGAIN) { + if (token != CRYPT_ANY_TOKEN) + log_verbose(_("Token %i requires additional missing resource."), token); + else if (type) + log_verbose(_("Token (type %s) requires additional missing resource."), type); + } if (error == -ENOENT) { + if (type) + log_verbose(_("No usable token (type %s) is available."), type); + else + log_verbose(_("No usable token is available.")); + } +} + +/* + * Device size string parsing, suffixes: + * s|S - 512 bytes sectors + * k |K |m |M |g |G |t |T - 1024 base + * kiB|KiB|miB|MiB|giB|GiB|tiB|TiB - 1024 base + * kb |KB |mM |MB |gB |GB |tB |TB - 1000 base + */ +int tools_string_to_size(const char *s, uint64_t *size) +{ + char *endp = NULL; + size_t len; + uint64_t mult_base, mult, tmp; + + *size = strtoull(s, &endp, 10); + if (!isdigit(s[0]) || + (errno == ERANGE && *size == ULLONG_MAX) || + (errno != 0 && *size == 0)) + return -EINVAL; + + if (!endp || !*endp) + return 0; + + len = strlen(endp); + /* Allow "B" and "iB" suffixes */ + if (len > 3 || + (len == 3 && (endp[1] != 'i' || endp[2] != 'B')) || + (len == 2 && endp[1] != 'B')) + return -EINVAL; + + if (len == 1 || len == 3) + mult_base = 1024; + else + mult_base = 1000; + + mult = 1; + switch (endp[0]) { + case 's': + case 'S': mult = 512; + break; + case 't': + case 'T': mult *= mult_base; + /* Fall through */ + case 'g': + case 'G': mult *= mult_base; + /* Fall through */ + case 'm': + case 'M': mult *= mult_base; + /* Fall through */ + case 'k': + case 'K': mult *= mult_base; + break; + default: + return -EINVAL; + } + + tmp = *size * mult; + if (*size && (tmp / *size) != mult) { + log_dbg("Device size overflow."); + return -EINVAL; + } + + *size = tmp; + return 0; +} + +/* + * Keyfile - is standard input treated as a binary file (no EOL handling). + */ +int tools_is_stdin(const char *key_file) +{ + if (!key_file) + return 1; + + return strcmp(key_file, "-") ? 0 : 1; +} + +int tools_read_vk(const char *file, char **key, int keysize) +{ + int fd = -1, r = -EINVAL; + + if (keysize <= 0 || !key) + return -EINVAL; + + *key = crypt_safe_alloc(keysize); + if (!*key) + return -ENOMEM; + + fd = open(file, O_RDONLY); + if (fd == -1) { + log_err(_("Cannot read keyfile %s."), file); + goto out; + } + + if (read_buffer(fd, *key, keysize) != keysize) { + log_err(_("Cannot read %d bytes from keyfile %s."), keysize, file); + goto out; + } + r = 0; +out: + if (fd != -1) + close(fd); + + if (r) { + crypt_safe_free(*key); + *key = NULL; + } + + return r; +} + +int tools_write_mk(const char *file, const char *key, int keysize) +{ + int fd, r = -EINVAL; + + if (keysize <= 0 || !key) + return -EINVAL; + + fd = open(file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR); + if (fd < 0) { + log_err(_("Cannot open keyfile %s for write."), file); + return r; + } + + if (write_buffer(fd, key, keysize) == keysize) + r = 0; + else + log_err(_("Cannot write to keyfile %s."), file); + + close(fd); + return r; +} + +void tools_package_version(const char *name, bool use_pwlibs) +{ + bool udev = false, blkid = false, keyring = false, fips = false; + bool kernel_capi = false, pwquality = false, passwdqc = false; +#ifdef USE_UDEV + udev = true; +#endif +#ifdef HAVE_BLKID + blkid = true; +#endif +#ifdef KERNEL_KEYRING + keyring = true; +#endif +#ifdef ENABLE_FIPS + fips = true; +#endif +#ifdef ENABLE_AF_ALG + kernel_capi = true; +#endif +#if defined(ENABLE_PWQUALITY) + pwquality = true; +#elif defined(ENABLE_PASSWDQC) + passwdqc = true; +#endif + log_std("%s %s flags: %s%s%s%s%s%s%s\n", name, PACKAGE_VERSION, + udev ? "UDEV " : "", + blkid ? "BLKID " : "", + keyring ? "KEYRING " : "", + fips ? "FIPS " : "", + kernel_capi ? "KERNEL_CAPI " : "", + pwquality && use_pwlibs ? "PWQUALITY " : "", + passwdqc && use_pwlibs ? "PASSWDQC " : ""); +} diff --git a/src/veritysetup.c b/src/veritysetup.c new file mode 100644 index 0000000..8be81cc --- /dev/null +++ b/src/veritysetup.c @@ -0,0 +1,680 @@ +/* + * veritysetup - setup cryptographic volumes for dm-verity + * + * Copyright (C) 2012-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2012-2023 Milan Broz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "cryptsetup.h" +#include "veritysetup_args.h" + +#define PACKAGE_VERITY "veritysetup" + +static const char **action_argv; +static int action_argc; +static struct tools_log_params log_parms; + +void tools_cleanup(void) +{ + tools_args_free(tool_core_args, ARRAY_SIZE(tool_core_args)); +} + +static int _prepare_format(struct crypt_params_verity *params, + const char *data_device, + uint32_t flags) +{ + char *salt = NULL; + int len; + + params->hash_name = ARG_STR(OPT_HASH_ID); + params->data_device = data_device; + params->fec_device = ARG_STR(OPT_FEC_DEVICE_ID); + params->fec_roots = ARG_UINT32(OPT_FEC_ROOTS_ID); + + if (ARG_STR(OPT_SALT_ID) && !strcmp(ARG_STR(OPT_SALT_ID), "-")) { + params->salt_size = 0; + params->salt = NULL; + } else if (ARG_SET(OPT_SALT_ID)) { + len = crypt_hex_to_bytes(ARG_STR(OPT_SALT_ID), &salt, 0); + if (len < 0) { + log_err(_("Invalid salt string specified.")); + return -EINVAL; + } + params->salt_size = len; + params->salt = salt; + } else { + params->salt_size = DEFAULT_VERITY_SALT_SIZE; + params->salt = NULL; + } + + params->data_block_size = ARG_UINT32(OPT_DATA_BLOCK_SIZE_ID); + params->hash_block_size = ARG_UINT32(OPT_HASH_BLOCK_SIZE_ID); + params->data_size = ARG_UINT64(OPT_DATA_BLOCKS_ID); + params->hash_area_offset = ARG_UINT64(OPT_HASH_OFFSET_ID); + params->fec_area_offset = ARG_UINT64(OPT_FEC_OFFSET_ID); + params->hash_type = ARG_UINT32(OPT_FORMAT_ID); + params->flags = flags; + + return 0; +} + +static int action_format(void) +{ + struct crypt_device *cd = NULL; + struct crypt_params_verity params = {}; + uint32_t flags = CRYPT_VERITY_CREATE_HASH; + char *root_hash_bytes = NULL; + size_t root_hash_size; + int root_hash_fd = -1, i, r; + + /* Try to create hash image if doesn't exist */ + r = open(action_argv[1], O_WRONLY | O_EXCL | O_CREAT, S_IRUSR | S_IWUSR); + if (r < 0 && errno != EEXIST) { + log_err(_("Cannot create hash image %s for writing."), action_argv[1]); + return -EINVAL; + } else if (r >= 0) { + log_dbg("Created hash image %s.", action_argv[1]); + close(r); + } + /* Try to create FEC image if doesn't exist */ + if (ARG_SET(OPT_FEC_DEVICE_ID)) { + r = open(ARG_STR(OPT_FEC_DEVICE_ID), O_WRONLY | O_EXCL | O_CREAT, S_IRUSR | S_IWUSR); + if (r < 0 && errno != EEXIST) { + log_err(_("Cannot create FEC image %s for writing."), ARG_STR(OPT_FEC_DEVICE_ID)); + return -EINVAL; + } else if (r >= 0) { + log_dbg("Created FEC image %s.", ARG_STR(OPT_FEC_DEVICE_ID)); + close(r); + } + } + + if ((r = crypt_init(&cd, action_argv[1]))) + goto out; + + if (ARG_SET(OPT_NO_SUPERBLOCK_ID)) + flags |= CRYPT_VERITY_NO_HEADER; + + r = _prepare_format(¶ms, action_argv[0], flags); + if (r < 0) + goto out; + + r = crypt_format(cd, CRYPT_VERITY, NULL, NULL, ARG_STR(OPT_UUID_ID), NULL, 0, ¶ms); + if (r < 0) + goto out; + + crypt_dump(cd); + + /* Create or overwrite the root hash file */ + if (ARG_SET(OPT_ROOT_HASH_FILE_ID)) { + root_hash_size = crypt_get_volume_key_size(cd); + root_hash_bytes = malloc(root_hash_size); + if (!root_hash_bytes) { + r = -ENOMEM; + goto out; + } + + r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_bytes, &root_hash_size, NULL, 0); + if (r < 0) + goto out; + + root_hash_fd = open(ARG_STR(OPT_ROOT_HASH_FILE_ID), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR); + if (root_hash_fd == -1) { + log_err(_("Cannot create root hash file %s for writing."), ARG_STR(OPT_ROOT_HASH_FILE_ID)); + r = -EINVAL; + goto out; + } + + for (i = 0; i < (int)root_hash_size; i++) + if (dprintf(root_hash_fd, "%02hhx", root_hash_bytes[i]) != 2) { + log_err(_("Cannot write to root hash file %s."), ARG_STR(OPT_ROOT_HASH_FILE_ID)); + r = -EIO; + goto out; + } + + log_dbg("Created root hash file %s.", ARG_STR(OPT_ROOT_HASH_FILE_ID)); + } +out: + crypt_free(cd); + free(CONST_CAST(char*)params.salt); + free(root_hash_bytes); + if (root_hash_fd != -1) + close(root_hash_fd); + return r; +} + +static int _activate(const char *dm_device, + const char *data_device, + const char *hash_device, + const char *root_hash, + uint32_t flags) +{ + struct crypt_device *cd = NULL; + struct crypt_params_verity params = {}; + uint32_t activate_flags = CRYPT_ACTIVATE_READONLY; + char *root_hash_bytes = NULL, *root_hash_from_file = NULL; + ssize_t hash_size, hash_size_hex; + struct stat st; + char *signature = NULL; + int signature_size = 0, root_hash_fd = -1, r; + + if ((r = crypt_init_data_device(&cd, hash_device, data_device))) + goto out; + + if (ARG_SET(OPT_IGNORE_CORRUPTION_ID)) + activate_flags |= CRYPT_ACTIVATE_IGNORE_CORRUPTION; + if (ARG_SET(OPT_RESTART_ON_CORRUPTION_ID)) + activate_flags |= CRYPT_ACTIVATE_RESTART_ON_CORRUPTION; + if (ARG_SET(OPT_PANIC_ON_CORRUPTION_ID)) + activate_flags |= CRYPT_ACTIVATE_PANIC_ON_CORRUPTION; + if (ARG_SET(OPT_IGNORE_ZERO_BLOCKS_ID)) + activate_flags |= CRYPT_ACTIVATE_IGNORE_ZERO_BLOCKS; + if (ARG_SET(OPT_CHECK_AT_MOST_ONCE_ID)) + activate_flags |= CRYPT_ACTIVATE_CHECK_AT_MOST_ONCE; + if (ARG_SET(OPT_USE_TASKLETS_ID)) + activate_flags |= CRYPT_ACTIVATE_TASKLETS; + + if (!ARG_SET(OPT_NO_SUPERBLOCK_ID)) { + params.flags = flags; + params.hash_area_offset = ARG_UINT64(OPT_HASH_OFFSET_ID); + params.fec_area_offset = ARG_UINT64(OPT_FEC_OFFSET_ID); + params.fec_device = ARG_STR(OPT_FEC_DEVICE_ID); + params.fec_roots = ARG_UINT32(OPT_FEC_ROOTS_ID); + r = crypt_load(cd, CRYPT_VERITY, ¶ms); + if (r) + log_err(_("Device %s is not a valid VERITY device."), hash_device); + + } else { + r = _prepare_format(¶ms, data_device, flags | CRYPT_VERITY_NO_HEADER); + if (r < 0) + goto out; + r = crypt_format(cd, CRYPT_VERITY, NULL, NULL, NULL, NULL, 0, ¶ms); + } + if (r < 0) + goto out; + + hash_size = crypt_get_volume_key_size(cd); + hash_size_hex = 2 * hash_size; + + if (!root_hash) { + root_hash_fd = open(ARG_STR(OPT_ROOT_HASH_FILE_ID), O_RDONLY); + if (root_hash_fd == -1) { + log_err(_("Cannot read root hash file %s."), ARG_STR(OPT_ROOT_HASH_FILE_ID)); + goto out; + } + + if (fstat(root_hash_fd, &st) || !S_ISREG(st.st_mode) || st.st_size < hash_size_hex) { + log_err(_("Invalid root hash file %s."), ARG_STR(OPT_ROOT_HASH_FILE_ID)); + r = -EINVAL; + goto out; + } + + root_hash_from_file = malloc(hash_size_hex + 1); + if (!root_hash_from_file) { + r = -ENOMEM; + goto out; + } + + if (read_buffer(root_hash_fd, root_hash_from_file, hash_size_hex) != hash_size_hex) { + log_err(_("Cannot read root hash file %s."), root_hash_from_file); + goto out; + } + + root_hash_from_file[hash_size_hex] = '\0'; + root_hash = root_hash_from_file; + } + + if (crypt_hex_to_bytes(root_hash, &root_hash_bytes, 0) != hash_size) { + log_err(_("Invalid root hash string specified.")); + r = -EINVAL; + goto out; + } + + if (ARG_SET(OPT_ROOT_HASH_SIGNATURE_ID)) { + // FIXME: check max file size + if (stat(ARG_STR(OPT_ROOT_HASH_SIGNATURE_ID), &st) || !S_ISREG(st.st_mode) || !st.st_size) { + log_err(_("Invalid signature file %s."), ARG_STR(OPT_ROOT_HASH_SIGNATURE_ID)); + r = -EINVAL; + goto out; + } + signature_size = st.st_size; + r = tools_read_vk(ARG_STR(OPT_ROOT_HASH_SIGNATURE_ID), &signature, signature_size); + if (r < 0) { + log_err(_("Cannot read signature file %s."), ARG_STR(OPT_ROOT_HASH_SIGNATURE_ID)); + goto out; + } + } + r = crypt_activate_by_signed_key(cd, dm_device, + root_hash_bytes, + hash_size, + signature, signature_size, + activate_flags); +out: + crypt_safe_free(signature); + crypt_free(cd); + free(root_hash_from_file); + free(root_hash_bytes); + free(CONST_CAST(char*)params.salt); + if (root_hash_fd != -1) + close(root_hash_fd); + return r; +} + +static int action_open(void) +{ + if (action_argc < 4 && !ARG_SET(OPT_ROOT_HASH_FILE_ID)) { + log_err(_("Command requires <root_hash> or --root-hash-file option as argument.")); + return -EINVAL; + } + + return _activate(action_argv[1], + action_argv[0], + action_argv[2], + ARG_SET(OPT_ROOT_HASH_FILE_ID) ? NULL : action_argv[3], + ARG_SET(OPT_ROOT_HASH_SIGNATURE_ID) ? CRYPT_VERITY_ROOT_HASH_SIGNATURE : 0); +} + +static int action_verify(void) +{ + if (action_argc < 3 && !ARG_SET(OPT_ROOT_HASH_FILE_ID)) { + log_err(_("Command requires <root_hash> or --root-hash-file option as argument.")); + return -EINVAL; + } + + return _activate(NULL, + action_argv[0], + action_argv[1], + ARG_SET(OPT_ROOT_HASH_FILE_ID) ? NULL : action_argv[2], + CRYPT_VERITY_CHECK_HASH); +} + +static int action_close(void) +{ + struct crypt_device *cd = NULL; + crypt_status_info ci; + uint32_t flags = 0; + int r; + + if (ARG_SET(OPT_DEFERRED_ID)) + flags |= CRYPT_DEACTIVATE_DEFERRED; + if (ARG_SET(OPT_CANCEL_DEFERRED_ID)) + flags |= CRYPT_DEACTIVATE_DEFERRED_CANCEL; + + r = crypt_init_by_name(&cd, action_argv[0]); + if (r == 0) + r = crypt_deactivate_by_name(cd, action_argv[0], flags); + + if (!r && ARG_SET(OPT_DEFERRED_ID)) { + ci = crypt_status(cd, action_argv[0]); + if (ci == CRYPT_ACTIVE || ci == CRYPT_BUSY) + log_std(_("Device %s is still active and scheduled for deferred removal.\n"), + action_argv[0]); + } + + crypt_free(cd); + return r; +} + +static int action_status(void) +{ + crypt_status_info ci; + struct crypt_active_device cad; + struct crypt_params_verity vp = {}; + struct crypt_device *cd = NULL; + struct stat st; + char *backing_file, *root_hash; + size_t root_hash_size; + unsigned path = 0; + int r = 0; + + /* perhaps a path, not a dm device name */ + if (strchr(action_argv[0], '/') && !stat(action_argv[0], &st)) + path = 1; + + ci = crypt_status(NULL, action_argv[0]); + switch (ci) { + case CRYPT_INVALID: + r = -EINVAL; + break; + case CRYPT_INACTIVE: + if (path) + log_std("%s is inactive.\n", action_argv[0]); + else + log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]); + r = -ENODEV; + break; + case CRYPT_ACTIVE: + case CRYPT_BUSY: + if (path) + log_std("%s is active%s.\n", action_argv[0], + ci == CRYPT_BUSY ? " and is in use" : ""); + else + log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0], + ci == CRYPT_BUSY ? " and is in use" : ""); + + r = crypt_init_by_name_and_header(&cd, action_argv[0], NULL); + if (r < 0) + goto out; + + log_std(" type: %s\n", crypt_get_type(cd) ?: "n/a"); + + r = crypt_get_active_device(cd, action_argv[0], &cad); + if (r < 0) + goto out; + + /* Print only VERITY type devices */ + r = crypt_get_verity_info(cd, &vp); + if (r < 0) + goto out; + + log_std(" status: %s%s\n", + cad.flags & CRYPT_ACTIVATE_CORRUPTED ? "corrupted" : "verified", + vp.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE ? " (with signature)" : ""); + + log_std(" hash type: %u\n", vp.hash_type); + log_std(" data block: %u\n", vp.data_block_size); + log_std(" hash block: %u\n", vp.hash_block_size); + log_std(" hash name: %s\n", vp.hash_name); + log_std(" salt: "); + if (vp.salt_size) + crypt_log_hex(NULL, vp.salt, vp.salt_size, "", 0, NULL); + else + log_std("-"); + log_std("\n"); + + log_std(" data device: %s\n", vp.data_device); + if ((backing_file = crypt_loop_backing_file(vp.data_device))) { + log_std(" data loop: %s\n", backing_file); + free(backing_file); + } + log_std(" size: %" PRIu64 " sectors\n", cad.size); + log_std(" mode: %s\n", cad.flags & CRYPT_ACTIVATE_READONLY ? + "readonly" : "read/write"); + + log_std(" hash device: %s\n", vp.hash_device); + if ((backing_file = crypt_loop_backing_file(vp.hash_device))) { + log_std(" hash loop: %s\n", backing_file); + free(backing_file); + } + log_std(" hash offset: %" PRIu64 " sectors\n", + vp.hash_area_offset * vp.hash_block_size / 512); + + if (vp.fec_device) { + log_std(" FEC device: %s\n", vp.fec_device); + if ((backing_file = crypt_loop_backing_file(ARG_STR(OPT_FEC_DEVICE_ID)))) { + log_std(" FEC loop: %s\n", backing_file); + free(backing_file); + } + log_std(" FEC offset: %" PRIu64 " sectors\n", + vp.fec_area_offset * vp.hash_block_size / 512); + log_std(" FEC roots: %u\n", vp.fec_roots); + } + + root_hash_size = crypt_get_volume_key_size(cd); + if (root_hash_size > 0 && (root_hash = malloc(root_hash_size))) { + r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash, &root_hash_size, NULL, 0); + if (!r) { + log_std(" root hash: "); + crypt_log_hex(NULL, root_hash, root_hash_size, "", 0, NULL); + log_std("\n"); + } + free(root_hash); + } + + if (cad.flags & (CRYPT_ACTIVATE_IGNORE_CORRUPTION| + CRYPT_ACTIVATE_RESTART_ON_CORRUPTION| + CRYPT_ACTIVATE_PANIC_ON_CORRUPTION| + CRYPT_ACTIVATE_IGNORE_ZERO_BLOCKS| + CRYPT_ACTIVATE_CHECK_AT_MOST_ONCE| + CRYPT_ACTIVATE_TASKLETS)) + log_std(" flags: %s%s%s%s%s%s\n", + (cad.flags & CRYPT_ACTIVATE_IGNORE_CORRUPTION) ? "ignore_corruption " : "", + (cad.flags & CRYPT_ACTIVATE_RESTART_ON_CORRUPTION) ? "restart_on_corruption " : "", + (cad.flags & CRYPT_ACTIVATE_PANIC_ON_CORRUPTION) ? "panic_on_corruption " : "", + (cad.flags & CRYPT_ACTIVATE_IGNORE_ZERO_BLOCKS) ? "ignore_zero_blocks " : "", + (cad.flags & CRYPT_ACTIVATE_CHECK_AT_MOST_ONCE) ? "check_at_most_once" : "", + (cad.flags & CRYPT_ACTIVATE_TASKLETS) ? "try_verify_in_tasklet" : ""); + } +out: + crypt_free(cd); + if (r == -ENOTSUP) + r = 0; + return r; +} + +static int action_dump(void) +{ + struct crypt_device *cd = NULL; + struct crypt_params_verity params = {}; + int r; + + if ((r = crypt_init(&cd, action_argv[0]))) + return r; + + params.hash_area_offset = ARG_UINT64(OPT_HASH_OFFSET_ID); + params.fec_area_offset = ARG_UINT64(OPT_FEC_OFFSET_ID); + params.fec_device = ARG_STR(OPT_FEC_DEVICE_ID); + params.fec_roots = ARG_UINT32(OPT_FEC_ROOTS_ID); + + r = crypt_load(cd, CRYPT_VERITY, ¶ms); + if (!r) + crypt_dump(cd); + else + log_err(_("Device %s is not a valid VERITY device."), action_argv[0]); + + crypt_free(cd); + return r; +} + +static struct action_type { + const char *type; + int (*handler)(void); + int required_action_argc; + const char *arg_desc; + const char *desc; +} action_types[] = { + { "format", action_format, 2, N_("<data_device> <hash_device>"),N_("format device") }, + { "verify", action_verify, 2, N_("<data_device> <hash_device> [<root_hash>]"),N_("verify device") }, + { "open", action_open, 3, N_("<data_device> <name> <hash_device> [<root_hash>]"),N_("open device as <name>") }, + { "close", action_close, 1, N_("<name>"),N_("close device (remove mapping)") }, + { "status", action_status, 1, N_("<name>"),N_("show active device status") }, + { "dump", action_dump, 1, N_("<hash_device>"),N_("show on-disk information") }, + { NULL, NULL, 0, NULL, NULL } +}; + +static void help(poptContext popt_context, + enum poptCallbackReason reason __attribute__((unused)), + struct poptOption *key, + const char *arg __attribute__((unused)), + void *data __attribute__((unused))) +{ + struct action_type *action; + + if (key->shortName == '?') { + tools_package_version(PACKAGE_VERITY, false); + poptPrintHelp(popt_context, stdout, 0); + log_std(_("\n" + "<action> is one of:\n")); + for(action = action_types; action->type; action++) + log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc)); + log_std(_("\n" + "<name> is the device to create under %s\n" + "<data_device> is the data device\n" + "<hash_device> is the device containing verification data\n" + "<root_hash> hash of the root node on <hash_device>\n"), + crypt_get_dir()); + + log_std(_("\nDefault compiled-in dm-verity parameters:\n" + "\tHash: %s, Data block (bytes): %u, " + "Hash block (bytes): %u, Salt size: %u, Hash format: %u\n"), + DEFAULT_VERITY_HASH, DEFAULT_VERITY_DATA_BLOCK, + DEFAULT_VERITY_HASH_BLOCK, DEFAULT_VERITY_SALT_SIZE, + 1); + tools_cleanup(); + poptFreeContext(popt_context); + exit(EXIT_SUCCESS); + } else if (key->shortName == 'V') { + tools_package_version(PACKAGE_VERITY, false); + tools_cleanup(); + poptFreeContext(popt_context); + exit(EXIT_SUCCESS); + } else + usage(popt_context, EXIT_SUCCESS, NULL, NULL); +} + +static int run_action(struct action_type *action) +{ + int r; + + log_dbg("Running command %s.", action->type); + + r = action->handler(); + + show_status(r); + return translate_errno(r); +} + +static void basic_options_cb(poptContext popt_context, + enum poptCallbackReason reason __attribute__((unused)), + struct poptOption *key, + const char *arg, + void *data __attribute__((unused))) +{ + tools_parse_arg_value(popt_context, tool_core_args[key->val].type, tool_core_args + key->val, arg, key->val, NULL); + + switch (key->val) { + case OPT_DEBUG_ID: + log_parms.debug = true; + /* fall through */ + case OPT_VERBOSE_ID: + log_parms.verbose = true; + } +} + +int main(int argc, const char **argv) +{ + static const char *null_action_argv[] = {NULL}; + static struct poptOption popt_help_options[] = { + { NULL, '\0', POPT_ARG_CALLBACK, help, 0, NULL, NULL }, + { "help", '?', POPT_ARG_NONE, NULL, 0, N_("Show this help message"), NULL }, + { "usage", '\0', POPT_ARG_NONE, NULL, 0, N_("Display brief usage"), NULL }, + { "version",'V', POPT_ARG_NONE, NULL, 0, N_("Print package version"), NULL }, + POPT_TABLEEND + }; + static struct poptOption popt_basic_options[] = { + { NULL, '\0', POPT_ARG_CALLBACK, basic_options_cb, 0, NULL, NULL }, +#define ARG(A, B, C, D, E, F, G, H) { A, B, C, NULL, A ## _ID, D, E }, +#include "veritysetup_arg_list.h" +#undef ARG + POPT_TABLEEND + }; + static struct poptOption popt_options[] = { + { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL }, + { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_basic_options, 0, NULL, NULL }, + POPT_TABLEEND + }; + + poptContext popt_context; + struct action_type *action; + const char *aname; + int r; + + crypt_set_log_callback(NULL, tool_log, &log_parms); + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + popt_context = poptGetContext("verity", argc, argv, popt_options, 0); + poptSetOtherOptionHelp(popt_context, + _("[OPTION...] <action> <action-specific>")); + + while((r = poptGetNextOpt(popt_context)) > 0) {} + + if (r < -1) + usage(popt_context, EXIT_FAILURE, poptStrerror(r), + poptBadOption(popt_context, POPT_BADOPTION_NOALIAS)); + + if (!(aname = poptGetArg(popt_context))) + usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."), + poptGetInvocationName(popt_context)); + + action_argc = 0; + action_argv = poptGetArgs(popt_context); + /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */ + if(!action_argv) + action_argv = null_action_argv; + + /* Count args, somewhat unnice, change? */ + while(action_argv[action_argc] != NULL) + action_argc++; + + /* Handle aliases */ + if (!strcmp(aname, "create") && action_argc > 1) { + /* create command had historically switched arguments */ + if (action_argv[0] && action_argv[1]) { + const char *tmp = action_argv[0]; + action_argv[0] = action_argv[1]; + action_argv[1] = tmp; + } + aname = "open"; + } else if (!strcmp(aname, "remove")) { + aname = "close"; + } + + for (action = action_types; action->type; action++) + if (strcmp(action->type, aname) == 0) + break; + + if (!action->type) + usage(popt_context, EXIT_FAILURE, _("Unknown action."), + poptGetInvocationName(popt_context)); + + if (action_argc < action->required_action_argc) { + char buf[128]; + if (snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc) < 0) + buf[0] = '\0'; + usage(popt_context, EXIT_FAILURE, buf, + poptGetInvocationName(popt_context)); + } + + tools_check_args(action->type, tool_core_args, ARRAY_SIZE(tool_core_args), popt_context); + + if (ARG_SET(OPT_IGNORE_CORRUPTION_ID) && ARG_SET(OPT_RESTART_ON_CORRUPTION_ID)) + usage(popt_context, EXIT_FAILURE, + _("Option --ignore-corruption and --restart-on-corruption cannot be used together."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_PANIC_ON_CORRUPTION_ID) && ARG_SET(OPT_RESTART_ON_CORRUPTION_ID)) + usage(popt_context, EXIT_FAILURE, + _("Option --panic-on-corruption and --restart-on-corruption cannot be used together."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_CANCEL_DEFERRED_ID) && ARG_SET(OPT_DEFERRED_ID)) + usage(popt_context, EXIT_FAILURE, + _("Options --cancel-deferred and --deferred cannot be used at the same time."), + poptGetInvocationName(popt_context)); + + if (ARG_SET(OPT_DEBUG_ID)) { + crypt_set_debug_level(CRYPT_DEBUG_ALL); + dbg_version_and_cmd(argc, argv); + } + + r = run_action(action); + tools_cleanup(); + poptFreeContext(popt_context); + return r; +} diff --git a/src/veritysetup_arg_list.h b/src/veritysetup_arg_list.h new file mode 100644 index 0000000..014273e --- /dev/null +++ b/src/veritysetup_arg_list.h @@ -0,0 +1,70 @@ +/* + * Veritysetup command line arguments list + * + * Copyright (C) 2020-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2020-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/* long name, short name, popt type, help description, units, internal argument type, default value, allowed actions (empty=global) */ + +ARG(OPT_CANCEL_DEFERRED, '\0', POPT_ARG_NONE, N_("Cancel a previously set deferred device removal"), NULL, CRYPT_ARG_BOOL, {}, OPT_DEFERRED_ACTIONS) + +ARG(OPT_CHECK_AT_MOST_ONCE, '\0', POPT_ARG_NONE, N_("Verify data block only the first time it is read"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DATA_BLOCK_SIZE, '\0', POPT_ARG_STRING, N_("Block size on the data device"), N_("bytes"), CRYPT_ARG_UINT32, { .u32_value = DEFAULT_VERITY_DATA_BLOCK }, {}) + +ARG(OPT_DATA_BLOCKS, '\0', POPT_ARG_STRING, N_("The number of blocks in the data file"), N_("blocks"), CRYPT_ARG_UINT64, {}, {}) + +ARG(OPT_DEBUG, '\0', POPT_ARG_NONE, N_("Show debug messages"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_DEFERRED, '\0', POPT_ARG_NONE, N_("Device removal is deferred until the last user closes it"), NULL, CRYPT_ARG_BOOL, {}, OPT_DEFERRED_ACTIONS) + +ARG(OPT_FEC_DEVICE, '\0', POPT_ARG_STRING, N_("Path to device with error correction data"), N_("path"), CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_FEC_OFFSET, '\0', POPT_ARG_STRING, N_("Starting offset on the FEC device"), N_("bytes"), CRYPT_ARG_UINT64, {}, {}) + +ARG(OPT_FEC_ROOTS, '\0', POPT_ARG_STRING, N_("FEC parity bytes"), N_("bytes"), CRYPT_ARG_UINT32, { .u32_value = DEFAULT_VERITY_FEC_ROOTS }, {}) + +ARG(OPT_FORMAT, '\0', POPT_ARG_STRING, N_("Format type (1 - normal, 0 - original Chrome OS)"), N_("number"), CRYPT_ARG_UINT32, { .u32_value = 1 }, {}) + +ARG(OPT_HASH, 'h', POPT_ARG_STRING, N_("Hash algorithm"), N_("string"), CRYPT_ARG_STRING, { .str_value = CONST_CAST(void *)DEFAULT_VERITY_HASH }, {}) + +ARG(OPT_HASH_BLOCK_SIZE, '\0', POPT_ARG_STRING, N_("Block size on the hash device"), N_("bytes"), CRYPT_ARG_UINT32, { .u32_value = DEFAULT_VERITY_HASH_BLOCK }, {}) + +ARG(OPT_HASH_OFFSET, '\0', POPT_ARG_STRING, N_("Starting offset on the hash device"), N_("bytes"), CRYPT_ARG_UINT64, {}, {}) + +ARG(OPT_IGNORE_CORRUPTION, '\0', POPT_ARG_NONE, N_("Ignore corruption, log it only"), NULL, CRYPT_ARG_BOOL, {}, OPT_IGNORE_CORRUPTION_ACTIONS) + +ARG(OPT_IGNORE_ZERO_BLOCKS, '\0', POPT_ARG_NONE, N_("Do not verify zeroed blocks"), NULL, CRYPT_ARG_BOOL, {}, OPT_IGNORE_ZERO_BLOCKS_ACTIONS) + +ARG(OPT_NO_SUPERBLOCK, '\0', POPT_ARG_NONE, N_("Do not use verity superblock"), NULL, CRYPT_ARG_BOOL, {}, {}) + +ARG(OPT_PANIC_ON_CORRUPTION, '\0', POPT_ARG_NONE, N_("Panic kernel if corruption is detected"), NULL, CRYPT_ARG_BOOL, {}, OPT_PANIC_ON_CORRUPTION_ACTIONS) + +ARG(OPT_RESTART_ON_CORRUPTION, '\0', POPT_ARG_NONE, N_("Restart kernel if corruption is detected"), NULL, CRYPT_ARG_BOOL, {}, OPT_RESTART_ON_CORRUPTION_ACTIONS) + +ARG(OPT_ROOT_HASH_FILE, '\0', POPT_ARG_STRING, N_("Path to root hash file"), NULL, CRYPT_ARG_STRING, {}, OPT_ROOT_HASH_FILE_ACTIONS) + +ARG(OPT_ROOT_HASH_SIGNATURE, '\0', POPT_ARG_STRING, N_("Path to root hash signature file"), NULL, CRYPT_ARG_STRING, {}, OPT_ROOT_HASH_SIGNATURE_ACTIONS) + +ARG(OPT_SALT, 's', POPT_ARG_STRING, N_("Salt"), N_("hex string"), CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_USE_TASKLETS, '\0', POPT_ARG_NONE, N_("Use kernel tasklets for performance"), NULL, CRYPT_ARG_BOOL, {}, OPT_USE_TASKLETS_ACTIONS) + +ARG(OPT_UUID, '\0', POPT_ARG_STRING, N_("UUID for device to use"), NULL, CRYPT_ARG_STRING, {}, {}) + +ARG(OPT_VERBOSE, 'v', POPT_ARG_NONE, N_("Shows more detailed error messages"), NULL, CRYPT_ARG_BOOL, {}, {}) diff --git a/src/veritysetup_args.h b/src/veritysetup_args.h new file mode 100644 index 0000000..d47813d --- /dev/null +++ b/src/veritysetup_args.h @@ -0,0 +1,57 @@ +/* + * Command line arguments helpers + * + * Copyright (C) 2020-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2020-2023 Ondrej Kozina + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef VERITYSETUP_ARGS_H +#define VERITYSETUP_ARGS_H + +#include "utils_arg_names.h" +#include "utils_arg_macros.h" + +#define CLOSE_ACTION "close" +#define DUMP_ACTION "dump" +#define FORMAT_ACTION "format" +#define OPEN_ACTION "open" +#define STATUS_ACTION "status" +#define VERIFY_ACTION "verify" + +#define OPT_DEFERRED_ACTIONS { CLOSE_ACTION } +#define OPT_IGNORE_CORRUPTION_ACTIONS { OPEN_ACTION } +#define OPT_IGNORE_ZERO_BLOCKS_ACTIONS { OPEN_ACTION } +#define OPT_RESTART_ON_CORRUPTION_ACTIONS { OPEN_ACTION } +#define OPT_PANIC_ON_CORRUPTION_ACTIONS { OPEN_ACTION } +#define OPT_ROOT_HASH_FILE_ACTIONS { FORMAT_ACTION, OPEN_ACTION, VERIFY_ACTION } +#define OPT_ROOT_HASH_SIGNATURE_ACTIONS { OPEN_ACTION } +#define OPT_USE_TASKLETS_ACTIONS { OPEN_ACTION } + +enum { +OPT_UNUSED_ID = 0, +#define ARG(A, B, C, D, E, F, G, H) A ## _ID, +#include "veritysetup_arg_list.h" +#undef ARG +}; + +static struct tools_arg tool_core_args[] = { { NULL, false, CRYPT_ARG_BOOL }, // UNUSED +#define ARG(A, B, C, D, E, F, G, H) { A, false, F, G, H }, +#include "veritysetup_arg_list.h" +#undef ARG +}; + +#endif |