"Fossies" - the Fresh Open Source Software Archive

Member "cryptsetup-2.4.3/src/cryptsetup.c" (13 Jan 2022, 125205 Bytes) of package /linux/misc/cryptsetup-2.4.3.tar.xz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "cryptsetup.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.4.2_vs_2.4.3.

    1 /*
    2  * cryptsetup - setup cryptographic volumes for dm-crypt
    3  *
    4  * Copyright (C) 2004 Jana Saout <jana@saout.de>
    5  * Copyright (C) 2004-2007 Clemens Fruhwirth <clemens@endorphin.org>
    6  * Copyright (C) 2009-2021 Red Hat, Inc. All rights reserved.
    7  * Copyright (C) 2009-2021 Milan Broz
    8  *
    9  * This program is free software; you can redistribute it and/or
   10  * modify it under the terms of the GNU General Public License
   11  * as published by the Free Software Foundation; either version 2
   12  * of the License, or (at your option) any later version.
   13  *
   14  * This program is distributed in the hope that it will be useful,
   15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
   16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17  * GNU General Public License for more details.
   18  *
   19  * You should have received a copy of the GNU General Public License
   20  * along with this program; if not, write to the Free Software
   21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
   22  */
   23 
   24 #include <uuid/uuid.h>
   25 
   26 #include "cryptsetup.h"
   27 #include "cryptsetup_args.h"
   28 
   29 static char *keyfiles[MAX_KEYFILES];
   30 static char *keyfile_stdin = NULL;
   31 
   32 static int keyfiles_count = 0;
   33 static int64_t data_shift = 0;
   34 
   35 static const char *device_type = "luks";
   36 static const char *set_pbkdf = NULL;
   37 
   38 static const char **action_argv;
   39 static int action_argc;
   40 static const char *null_action_argv[] = {NULL, NULL};
   41 static int total_keyfiles = 0;
   42 
   43 static struct tools_log_params log_parms;
   44 
   45 void tools_cleanup(void)
   46 {
   47     tools_args_free(tool_core_args, ARRAY_SIZE(tool_core_args));
   48 
   49     FREE_AND_NULL(keyfile_stdin);
   50 
   51     while (keyfiles_count)
   52         free(keyfiles[--keyfiles_count]);
   53 
   54     total_keyfiles = 0;
   55 }
   56 
   57 static const char *uuid_or_device_header(const char **data_device)
   58 {
   59     if (data_device)
   60         *data_device = ARG_SET(OPT_HEADER_ID) ? action_argv[0] : NULL;
   61 
   62     return uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]);
   63 }
   64 
   65 static const char *luksType(const char *type)
   66 {
   67     if (type && !strcmp(type, "luks2"))
   68         return CRYPT_LUKS2;
   69 
   70     if (type && !strcmp(type, "luks1"))
   71         return CRYPT_LUKS1;
   72 
   73     if (type && !strcmp(type, "luks"))
   74         return CRYPT_LUKS; /* NULL */
   75 
   76     if (type && *type)
   77         return type;
   78 
   79     return CRYPT_LUKS; /* NULL */
   80 }
   81 
   82 static bool isLUKS1(const char *type)
   83 {
   84     return type && !strcmp(type, CRYPT_LUKS1);
   85 }
   86 
   87 static bool isLUKS2(const char *type)
   88 {
   89     return type && !strcmp(type, CRYPT_LUKS2);
   90 }
   91 
   92 static bool isLUKS(const char *type)
   93 {
   94     return isLUKS2(type) || isLUKS1(type);
   95 }
   96 
   97 static int _verify_passphrase(int def)
   98 {
   99     /* Batch mode switch off verify - if not overridden by -y */
  100     if (ARG_SET(OPT_VERIFY_PASSPHRASE_ID))
  101         def = 1;
  102     else if (ARG_SET(OPT_BATCH_MODE_ID))
  103         def = 0;
  104 
  105     /* Non-tty input doesn't allow verify */
  106     if (def && !isatty(STDIN_FILENO)) {
  107         if (ARG_SET(OPT_VERIFY_PASSPHRASE_ID))
  108             log_err(_("Can't do passphrase verification on non-tty inputs."));
  109         def = 0;
  110     }
  111 
  112     return def;
  113 }
  114 
  115 static void _set_activation_flags(uint32_t *flags)
  116 {
  117     if (ARG_SET(OPT_READONLY_ID))
  118         *flags |= CRYPT_ACTIVATE_READONLY;
  119 
  120     if (ARG_SET(OPT_ALLOW_DISCARDS_ID))
  121         *flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
  122 
  123     if (ARG_SET(OPT_PERF_SAME_CPU_CRYPT_ID))
  124         *flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
  125 
  126     if (ARG_SET(OPT_PERF_SUBMIT_FROM_CRYPT_CPUS_ID))
  127         *flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
  128 
  129     if (ARG_SET(OPT_PERF_NO_READ_WORKQUEUE_ID))
  130         *flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
  131 
  132     if (ARG_SET(OPT_PERF_NO_WRITE_WORKQUEUE_ID))
  133         *flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
  134 
  135     if (ARG_SET(OPT_INTEGRITY_NO_JOURNAL_ID))
  136         *flags |= CRYPT_ACTIVATE_NO_JOURNAL;
  137 
  138     /* In persistent mode, we use what is set on command line */
  139     if (ARG_SET(OPT_PERSISTENT_ID))
  140         *flags |= CRYPT_ACTIVATE_IGNORE_PERSISTENT;
  141 
  142     /* Only for LUKS2 but ignored elsewhere */
  143     if (ARG_SET(OPT_TEST_PASSPHRASE_ID))
  144         *flags |= CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY;
  145 
  146     if (ARG_SET(OPT_SERIALIZE_MEMORY_HARD_PBKDF_ID))
  147         *flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF;
  148 
  149     /* Only for plain */
  150     if (ARG_SET(OPT_IV_LARGE_SECTORS_ID))
  151         *flags |= CRYPT_ACTIVATE_IV_LARGE_SECTORS;
  152 }
  153 
  154 static void _set_reencryption_flags(uint32_t *flags)
  155 {
  156     if (ARG_SET(OPT_INIT_ONLY_ID))
  157         *flags |= CRYPT_REENCRYPT_INITIALIZE_ONLY;
  158 
  159     if (ARG_SET(OPT_RESUME_ONLY_ID))
  160         *flags |= CRYPT_REENCRYPT_RESUME_ONLY;
  161 }
  162 
  163 static int _set_keyslot_encryption_params(struct crypt_device *cd)
  164 {
  165     const char *type = crypt_get_type(cd);
  166 
  167     if (!ARG_SET(OPT_KEYSLOT_KEY_SIZE_ID) && !ARG_SET(OPT_KEYSLOT_CIPHER_ID))
  168         return 0;
  169 
  170     if (!isLUKS2(type)) {
  171         log_err(_("Keyslot encryption parameters can be set only for LUKS2 device."));
  172         return -EINVAL;
  173     }
  174 
  175     return crypt_keyslot_set_encryption(cd, ARG_STR(OPT_KEYSLOT_CIPHER_ID), ARG_UINT32(OPT_KEYSLOT_KEY_SIZE_ID) / 8);
  176 }
  177 
  178 static int _set_tries_tty(void)
  179 {
  180     return (tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID)) && isatty(STDIN_FILENO)) ? ARG_UINT32(OPT_TRIES_ID) : 1;
  181 }
  182 
  183 static int _try_token_pin_unlock(struct crypt_device *cd,
  184                  int token_id,
  185                  const char *activated_name,
  186                  const char *token_type,
  187                  uint32_t activate_flags,
  188                  int tries)
  189 {
  190     size_t pin_len;
  191     char msg[64], *pin = NULL;
  192     int r;
  193 
  194     assert(tries >= 1);
  195     assert(token_id >= 0 || token_id == CRYPT_ANY_TOKEN);
  196 
  197     if (token_id == CRYPT_ANY_TOKEN)
  198         r = snprintf(msg, sizeof(msg), _("Enter token PIN:"));
  199     else
  200         r = snprintf(msg, sizeof(msg), _("Enter token %d PIN:"), token_id);
  201     if (r < 0 || (size_t)r >= sizeof(msg))
  202         return -EINVAL;
  203 
  204     do {
  205         r = tools_get_key(msg, &pin, &pin_len, 0, 0, NULL,
  206                 ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(0), 0, cd);
  207         if (r < 0)
  208             break;
  209 
  210         r = crypt_activate_by_token_pin(cd, activated_name, token_type, ARG_INT32(OPT_TOKEN_ID_ID),
  211                         pin, pin_len, NULL, activate_flags);
  212         crypt_safe_free(pin);
  213         pin = NULL;
  214         tools_keyslot_msg(r, UNLOCKED);
  215         tools_token_error_msg(r, ARG_STR(OPT_TOKEN_TYPE_ID), ARG_INT32(OPT_TOKEN_ID_ID), true);
  216         check_signal(&r);
  217     } while (r == -ENOANO && (--tries > 0));
  218 
  219     return r;
  220 }
  221 
  222 static int action_open_plain(void)
  223 {
  224     struct crypt_device *cd = NULL, *cd1 = NULL;
  225     const char *pcipher, *pmode;
  226     char *msg, cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
  227     struct crypt_active_device cad;
  228     struct crypt_params_plain params = {
  229         .hash = ARG_SET(OPT_HASH_ID) ? ARG_STR(OPT_HASH_ID) : DEFAULT_PLAIN_HASH,
  230         .skip = ARG_UINT64(OPT_SKIP_ID),
  231         .offset = ARG_UINT64(OPT_OFFSET_ID),
  232         .size = ARG_UINT64(OPT_SIZE_ID),
  233         .sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID) ?: SECTOR_SIZE
  234     };
  235     char *password = NULL;
  236     const char *activated_name = NULL;
  237     size_t passwordLen, key_size_max, signatures = 0,
  238            key_size = (ARG_UINT32(OPT_KEY_SIZE_ID) ?: DEFAULT_PLAIN_KEYBITS) / 8;
  239     uint32_t activate_flags = 0;
  240     int r;
  241 
  242     r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID) ?: DEFAULT_CIPHER(PLAIN),
  243                       cipher, NULL, cipher_mode);
  244     if (r < 0) {
  245         log_err(_("No known cipher specification pattern detected."));
  246         goto out;
  247     }
  248 
  249     /* FIXME: temporary hack, no hashing for keyfiles in plain mode */
  250     if (ARG_SET(OPT_KEY_FILE_ID) && !tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID))) {
  251         params.hash = NULL;
  252         if (!ARG_SET(OPT_BATCH_MODE_ID) && ARG_SET(OPT_HASH_ID))
  253             log_std(_("WARNING: The --hash parameter is being ignored "
  254                  "in plain mode with keyfile specified.\n"));
  255     }
  256 
  257     if (params.hash && !strcmp(params.hash, "plain"))
  258         params.hash = NULL;
  259 
  260     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))
  261         log_std(_("WARNING: The --keyfile-size option is being ignored, "
  262              "the read size is the same as the encryption key size.\n"));
  263 
  264     if (ARG_SET(OPT_REFRESH_ID)) {
  265         activated_name = action_argc > 1 ? action_argv[1] : action_argv[0];
  266         r = crypt_init_by_name_and_header(&cd1, activated_name, NULL);
  267         if (r)
  268             goto out;
  269         r = crypt_get_active_device(cd1, activated_name, &cad);
  270         if (r)
  271             goto out;
  272 
  273         /* copy known parameters from existing device */
  274         params.skip = crypt_get_iv_offset(cd1);
  275         params.offset = crypt_get_data_offset(cd1);
  276         params.size = cad.size;
  277         params.sector_size = crypt_get_sector_size(cd1);
  278         key_size = crypt_get_volume_key_size(cd1);
  279 
  280         if ((r = crypt_init(&cd, crypt_get_device_name(cd1))))
  281             goto out;
  282 
  283         activate_flags |= CRYPT_ACTIVATE_REFRESH;
  284 
  285         pcipher = crypt_get_cipher(cd1);
  286         pmode = crypt_get_cipher_mode(cd1);
  287     } else {
  288         activated_name = action_argv[1];
  289         if ((r = crypt_init(&cd, action_argv[0])))
  290             goto out;
  291 
  292         /* Skip blkid scan when activating plain device with offset */
  293         if (!ARG_UINT64(OPT_OFFSET_ID)) {
  294             /* Print all present signatures in read-only mode */
  295             r = tools_detect_signatures(action_argv[0], 0, &signatures, ARG_SET(OPT_BATCH_MODE_ID));
  296             if (r < 0)
  297                 goto out;
  298         }
  299 
  300         if (signatures && !ARG_SET(OPT_BATCH_MODE_ID)) {
  301             r = asprintf(&msg, _("Detected device signature(s) on %s. Proceeding further may damage existing data."), action_argv[0]);
  302             if (r == -1) {
  303                 r = -ENOMEM;
  304                 goto out;
  305             }
  306 
  307             r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
  308             free(msg);
  309             if (r < 0)
  310                 goto out;
  311         }
  312 
  313         pcipher = cipher;
  314         pmode = cipher_mode;
  315     }
  316 
  317     r = crypt_format(cd, CRYPT_PLAIN,
  318              pcipher, pmode,
  319              NULL, NULL,
  320              key_size,
  321              &params);
  322     check_signal(&r);
  323     if (r < 0)
  324         goto out;
  325 
  326     if (ARG_SET(OPT_SHARED_ID))
  327         activate_flags |= CRYPT_ACTIVATE_SHARED;
  328 
  329     _set_activation_flags(&activate_flags);
  330 
  331     if (!tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID))) {
  332         /* If no hash, key is read directly, read size is always key_size
  333          * (possible --keyfile_size is ignored.
  334          * If hash is specified, --keyfile_size is applied.
  335          * The --keyfile_offset is applied always.
  336          */
  337         key_size_max = params.hash ? ARG_UINT32(OPT_KEYFILE_SIZE_ID) : key_size;
  338         r = crypt_activate_by_keyfile_device_offset(cd, action_argv[1],
  339             CRYPT_ANY_SLOT, ARG_STR(OPT_KEY_FILE_ID), key_size_max,
  340             ARG_UINT64(OPT_KEYFILE_OFFSET_ID), activate_flags);
  341     } else {
  342         key_size_max = (ARG_SET(OPT_KEY_FILE_ID) && !params.hash) ? key_size : ARG_UINT32(OPT_KEYFILE_SIZE_ID);
  343         r = tools_get_key(NULL, &password, &passwordLen,
  344                   ARG_UINT64(OPT_KEYFILE_OFFSET_ID), key_size_max,
  345                   ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID),
  346                   _verify_passphrase(0), 0, cd);
  347         if (r < 0)
  348             goto out;
  349 
  350         r = crypt_activate_by_passphrase(cd, activated_name,
  351             CRYPT_ANY_SLOT, password, passwordLen, activate_flags);
  352     }
  353 out:
  354     crypt_free(cd);
  355     crypt_free(cd1);
  356     crypt_safe_free(password);
  357 
  358     return r;
  359 }
  360 
  361 static int action_open_loopaes(void)
  362 {
  363     struct crypt_device *cd = NULL;
  364     struct crypt_params_loopaes params = {
  365         .hash = ARG_STR(OPT_HASH_ID),
  366         .offset = ARG_UINT64(OPT_OFFSET_ID),
  367         .skip = ARG_SET(OPT_SKIP_ID) ? ARG_UINT64(OPT_SKIP_ID) : ARG_UINT64(OPT_OFFSET_ID)
  368     };
  369     unsigned int key_size = (ARG_UINT32(OPT_KEY_SIZE_ID) ?: DEFAULT_LOOPAES_KEYBITS) / 8;
  370     uint32_t activate_flags = 0;
  371     const char *activated_name = NULL;
  372     int r;
  373 
  374     if (!ARG_SET(OPT_KEY_FILE_ID)) {
  375         log_err(_("Option --key-file is required."));
  376         return -EINVAL;
  377     }
  378 
  379     if (ARG_SET(OPT_REFRESH_ID)) {
  380         activated_name = action_argc > 1 ? action_argv[1] : action_argv[0];
  381         if ((r = crypt_init_by_name(&cd, activated_name)))
  382             goto out;
  383         activate_flags |= CRYPT_ACTIVATE_REFRESH;
  384     } else {
  385         activated_name = action_argv[1];
  386         if ((r = crypt_init(&cd, action_argv[0])))
  387             goto out;
  388 
  389         r = crypt_format(cd, CRYPT_LOOPAES, ARG_STR(OPT_CIPHER_ID) ?: DEFAULT_LOOPAES_CIPHER,
  390                  NULL, NULL, NULL, key_size, &params);
  391         check_signal(&r);
  392         if (r < 0)
  393             goto out;
  394     }
  395 
  396     _set_activation_flags(&activate_flags);
  397 
  398     r = crypt_activate_by_keyfile_device_offset(cd, activated_name, CRYPT_ANY_SLOT,
  399         tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID)) ? "/dev/stdin" : ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID),
  400         ARG_UINT64(OPT_KEYFILE_OFFSET_ID), activate_flags);
  401 out:
  402     crypt_free(cd);
  403 
  404     return r;
  405 }
  406 
  407 static int tcrypt_load(struct crypt_device *cd, struct crypt_params_tcrypt *params)
  408 {
  409     int r, tries, eperm = 0;
  410 
  411     tries = _set_tries_tty();
  412     do {
  413         /* TCRYPT header is encrypted, get passphrase now */
  414         r = tools_get_key(NULL, CONST_CAST(char**)&params->passphrase,
  415                   &params->passphrase_size, 0, 0, keyfile_stdin, ARG_UINT32(OPT_TIMEOUT_ID),
  416                  _verify_passphrase(0), 0, cd);
  417         if (r < 0)
  418             continue;
  419 
  420         if (ARG_SET(OPT_VERACRYPT_QUERY_PIM_ID)) {
  421             char *tmp_pim_nptr = NULL;
  422             char *tmp_pim_end = NULL;
  423             size_t tmp_pim_size = 0;
  424             unsigned long long tmp_pim_ull = 0;
  425 
  426             r = tools_get_key(_("Enter VeraCrypt PIM: "),
  427                     &tmp_pim_nptr,
  428                     &tmp_pim_size, 0, 0, keyfile_stdin, ARG_UINT32(OPT_TIMEOUT_ID),
  429                     _verify_passphrase(0), 0, cd);
  430             if (r < 0)
  431                 continue;
  432 
  433             tmp_pim_ull = strtoull(tmp_pim_nptr, &tmp_pim_end, 10);
  434             if (*tmp_pim_nptr == '\0' || !tmp_pim_end || *tmp_pim_end != '\0') {
  435                 log_err(_("Invalid PIM value: parse error."));
  436                 r = -EINVAL;
  437             } else if (tmp_pim_ull == 0) {
  438                 log_err(_("Invalid PIM value: 0."));
  439                 r = -EINVAL;
  440             } else if (tmp_pim_ull > UINT32_MAX) {
  441                 log_err(_("Invalid PIM value: outside of range."));
  442                 r = -ERANGE;
  443             }
  444             crypt_safe_free(tmp_pim_nptr);
  445             if (r < 0)
  446                 continue;
  447 
  448             params->veracrypt_pim = (uint32_t)tmp_pim_ull;
  449             crypt_safe_memzero(&tmp_pim_ull, sizeof(tmp_pim_ull));
  450         }
  451 
  452         if (ARG_SET(OPT_TCRYPT_HIDDEN_ID))
  453             params->flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
  454 
  455         if (ARG_SET(OPT_TCRYPT_SYSTEM_ID))
  456             params->flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
  457 
  458         if (ARG_SET(OPT_TCRYPT_BACKUP_ID))
  459             params->flags |= CRYPT_TCRYPT_BACKUP_HEADER;
  460 
  461         r = crypt_load(cd, CRYPT_TCRYPT, params);
  462 
  463         if (r == -EPERM) {
  464             log_err(_("No device header detected with this passphrase."));
  465             eperm = 1;
  466         }
  467 
  468         if (r < 0) {
  469             crypt_safe_free(CONST_CAST(char*)params->passphrase);
  470             params->passphrase = NULL;
  471             params->passphrase_size = 0;
  472         }
  473         check_signal(&r);
  474     } while ((r == -EPERM || r == -ERANGE) && (--tries > 0));
  475 
  476     /* Report wrong passphrase if at least one try failed */
  477     if (eperm && r == -EPIPE)
  478         r = -EPERM;
  479 
  480     return r;
  481 }
  482 
  483 static int action_open_tcrypt(void)
  484 {
  485     struct crypt_device *cd = NULL;
  486     struct crypt_params_tcrypt params = {
  487         .keyfiles = CONST_CAST(const char **)keyfiles,
  488         .keyfiles_count = keyfiles_count,
  489         .flags = CRYPT_TCRYPT_LEGACY_MODES |
  490              (ARG_SET(OPT_DISABLE_VERACRYPT_ID) ? 0 : CRYPT_TCRYPT_VERA_MODES),
  491         .veracrypt_pim = ARG_UINT32(OPT_VERACRYPT_PIM_ID),
  492         .hash_name = ARG_STR(OPT_HASH_ID),
  493         .cipher = ARG_STR(OPT_CIPHER_ID),
  494     };
  495     const char *activated_name;
  496     uint32_t activate_flags = 0;
  497     int r;
  498 
  499     activated_name = ARG_SET(OPT_TEST_PASSPHRASE_ID) ? NULL : action_argv[1];
  500 
  501     r = crypt_init_data_device(&cd, ARG_STR(OPT_HEADER_ID) ?: action_argv[0], action_argv[0]);
  502     if (r < 0)
  503         goto out;
  504 
  505     r = tcrypt_load(cd, &params);
  506     if (r < 0)
  507         goto out;
  508 
  509     _set_activation_flags(&activate_flags);
  510 
  511     if (activated_name)
  512         r = crypt_activate_by_volume_key(cd, activated_name, NULL, 0, activate_flags);
  513 out:
  514     crypt_free(cd);
  515     crypt_safe_free(CONST_CAST(char*)params.passphrase);
  516     crypt_safe_memzero(&params.veracrypt_pim, sizeof(params.veracrypt_pim));
  517     return r;
  518 }
  519 
  520 static int action_open_bitlk(void)
  521 {
  522     struct crypt_device *cd = NULL;
  523     const char *activated_name;
  524     uint32_t activate_flags = 0;
  525     int r, tries, keysize;
  526     char *password = NULL;
  527     char *key = NULL;
  528     size_t passwordLen;
  529 
  530     activated_name = ARG_SET(OPT_TEST_PASSPHRASE_ID) ? NULL : action_argv[1];
  531 
  532     if ((r = crypt_init(&cd, action_argv[0])))
  533         goto out;
  534 
  535     r = crypt_load(cd, CRYPT_BITLK, NULL);
  536     if (r < 0) {
  537         log_err(_("Device %s is not a valid BITLK device."), action_argv[0]);
  538         goto out;
  539     }
  540     _set_activation_flags(&activate_flags);
  541 
  542     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
  543         keysize = crypt_get_volume_key_size(cd);
  544         if (!keysize && !ARG_SET(OPT_KEY_SIZE_ID)) {
  545             log_err(_("Cannot determine volume key size for BITLK, please use --key-size option."));
  546             r = -EINVAL;
  547             goto out;
  548         } else if (!keysize)
  549             keysize = ARG_UINT32(OPT_KEY_SIZE_ID) / 8;
  550 
  551         r = tools_read_mk(ARG_STR(OPT_MASTER_KEY_FILE_ID), &key, keysize);
  552         if (r < 0)
  553             goto out;
  554         r = crypt_activate_by_volume_key(cd, activated_name,
  555                          key, keysize, activate_flags);
  556     } else {
  557         tries = _set_tries_tty();
  558         do {
  559             r = tools_get_key(NULL, &password, &passwordLen,
  560                     ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
  561                     ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(0), 0, cd);
  562             if (r < 0)
  563                 goto out;
  564 
  565             r = crypt_activate_by_passphrase(cd, activated_name, CRYPT_ANY_SLOT,
  566                             password, passwordLen, activate_flags);
  567             tools_passphrase_msg(r);
  568             check_signal(&r);
  569             crypt_safe_free(password);
  570             password = NULL;
  571         } while ((r == -EPERM || r == -ERANGE) && (--tries > 0));
  572     }
  573 out:
  574     crypt_safe_free(password);
  575     crypt_safe_free(key);
  576     crypt_free(cd);
  577     return r;
  578 }
  579 
  580 static int tcryptDump_with_volume_key(struct crypt_device *cd)
  581 {
  582     char *vk = NULL;
  583     size_t vk_size;
  584     unsigned i;
  585     int r;
  586 
  587     if (!ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog(
  588         _("Header dump with volume key is sensitive information\n"
  589           "which allows access to encrypted partition without passphrase.\n"
  590           "This dump should be always stored encrypted on safe place."),
  591           NULL))
  592         return -EPERM;
  593 
  594     vk_size = crypt_get_volume_key_size(cd);
  595     vk = crypt_safe_alloc(vk_size);
  596     if (!vk)
  597         return -ENOMEM;
  598 
  599     r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size, NULL, 0);
  600     if (r < 0)
  601         goto out;
  602 
  603     log_std("TCRYPT header information for %s\n", crypt_get_device_name(cd));
  604     log_std("Cipher chain:  \t%s\n", crypt_get_cipher(cd));
  605     log_std("Cipher mode:   \t%s\n", crypt_get_cipher_mode(cd));
  606     log_std("Payload offset:\t%d\n", (int)crypt_get_data_offset(cd));
  607     log_std("MK bits:       \t%d\n", (int)vk_size * 8);
  608     log_std("MK dump:\t");
  609 
  610     for(i = 0; i < vk_size; i++) {
  611         if (i && !(i % 16))
  612             log_std("\n\t\t");
  613         log_std("%02hhx ", (char)vk[i]);
  614     }
  615     log_std("\n");
  616 out:
  617     crypt_safe_free(vk);
  618     return r;
  619 }
  620 
  621 static int action_tcryptDump(void)
  622 {
  623     struct crypt_device *cd = NULL;
  624     struct crypt_params_tcrypt params = {
  625         .keyfiles = CONST_CAST(const char **)keyfiles,
  626         .keyfiles_count = keyfiles_count,
  627         .flags = CRYPT_TCRYPT_LEGACY_MODES |
  628              (ARG_SET(OPT_DISABLE_VERACRYPT_ID) ? 0: CRYPT_TCRYPT_VERA_MODES),
  629         .veracrypt_pim = ARG_UINT32(OPT_VERACRYPT_PIM_ID),
  630         .hash_name = ARG_STR(OPT_HASH_ID),
  631         .cipher = ARG_STR(OPT_CIPHER_ID),
  632     };
  633     int r;
  634     r = crypt_init_data_device(&cd, ARG_STR(OPT_HEADER_ID) ?: action_argv[0], action_argv[0]);
  635     if (r < 0)
  636         goto out;
  637 
  638     r = tcrypt_load(cd, &params);
  639     if (r < 0)
  640         goto out;
  641 
  642     if (ARG_SET(OPT_DUMP_MASTER_KEY_ID))
  643         r = tcryptDump_with_volume_key(cd);
  644     else
  645         r = crypt_dump(cd);
  646 out:
  647     crypt_free(cd);
  648     crypt_safe_free(CONST_CAST(char*)params.passphrase);
  649     return r;
  650 }
  651 
  652 static int bitlkDump_with_volume_key(struct crypt_device *cd)
  653 {
  654     char *vk = NULL, *password = NULL;
  655     size_t passwordLen = 0;
  656     size_t vk_size;
  657     unsigned i;
  658     int r;
  659 
  660     if (!yesDialog(
  661         _("The header dump with volume key is sensitive information\n"
  662           "that allows access to encrypted partition without a passphrase.\n"
  663           "This dump should be stored encrypted in a safe place."),
  664           NULL))
  665         return -EPERM;
  666 
  667     vk_size = crypt_get_volume_key_size(cd);
  668     vk = crypt_safe_alloc(vk_size);
  669     if (!vk)
  670         return -ENOMEM;
  671 
  672     r = tools_get_key(NULL, &password, &passwordLen,
  673               ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
  674               ARG_UINT32(OPT_TIMEOUT_ID), 0, 0, cd);
  675     if (r < 0)
  676         goto out;
  677 
  678     r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size,
  679                  password, passwordLen);
  680     tools_passphrase_msg(r);
  681     check_signal(&r);
  682     if (r < 0)
  683         goto out;
  684     tools_keyslot_msg(r, UNLOCKED);
  685 
  686     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
  687         r = tools_write_mk(ARG_STR(OPT_MASTER_KEY_FILE_ID), vk, vk_size);
  688         if (r < 0)
  689             goto out;
  690     }
  691 
  692     log_std("BITLK header information for %s\n", crypt_get_device_name(cd));
  693     log_std("Cipher name:   \t%s\n", crypt_get_cipher(cd));
  694     log_std("Cipher mode:   \t%s\n", crypt_get_cipher_mode(cd));
  695     log_std("UUID:          \t%s\n", crypt_get_uuid(cd));
  696     log_std("MK bits:       \t%d\n", (int)vk_size * 8);
  697     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
  698         log_std("Key stored to file %s.\n", ARG_STR(OPT_MASTER_KEY_FILE_ID));
  699         goto out;
  700     }
  701     log_std("MK dump:\t");
  702 
  703     for(i = 0; i < vk_size; i++) {
  704         if (i && !(i % 16))
  705             log_std("\n\t\t");
  706         log_std("%02hhx ", (char)vk[i]);
  707     }
  708     log_std("\n");
  709 
  710 out:
  711     crypt_safe_free(password);
  712     crypt_safe_free(vk);
  713     return r;
  714 }
  715 
  716 static int action_bitlkDump(void)
  717 {
  718     struct crypt_device *cd = NULL;
  719     int r;
  720 
  721     if ((r = crypt_init(&cd, action_argv[0])))
  722         goto out;
  723 
  724     r = crypt_load(cd, CRYPT_BITLK, NULL);
  725     if (r < 0)
  726         goto out;
  727 
  728     if (ARG_SET(OPT_DUMP_MASTER_KEY_ID))
  729         r = bitlkDump_with_volume_key(cd);
  730     else
  731         r = crypt_dump(cd);
  732 out:
  733     crypt_free(cd);
  734     return r;
  735 }
  736 
  737 static int action_close(void)
  738 {
  739     struct crypt_device *cd = NULL;
  740     crypt_status_info ci;
  741     uint32_t flags = 0;
  742     int r;
  743 
  744     if (ARG_SET(OPT_DEFERRED_ID))
  745         flags |= CRYPT_DEACTIVATE_DEFERRED;
  746     if (ARG_SET(OPT_CANCEL_DEFERRED_ID))
  747         flags |= CRYPT_DEACTIVATE_DEFERRED_CANCEL;
  748 
  749     r = crypt_init_by_name(&cd, action_argv[0]);
  750     if (r == 0)
  751         r = crypt_deactivate_by_name(cd, action_argv[0], flags);
  752 
  753     if (!r && ARG_SET(OPT_DEFERRED_ID)) {
  754         ci = crypt_status(cd, action_argv[0]);
  755         if (ci == CRYPT_ACTIVE || ci == CRYPT_BUSY)
  756             log_std(_("Device %s is still active and scheduled for deferred removal.\n"),
  757                   action_argv[0]);
  758     }
  759 
  760     crypt_free(cd);
  761     return r;
  762 }
  763 
  764 static int action_resize(void)
  765 {
  766     int r;
  767     size_t passwordLen;
  768     struct crypt_active_device cad;
  769     uint64_t dev_size = 0;
  770     char *password = NULL;
  771     struct crypt_device *cd = NULL;
  772 
  773     r = crypt_init_by_name_and_header(&cd, action_argv[0], ARG_STR(OPT_HEADER_ID));
  774     if (r)
  775         goto out;
  776 
  777     /* FIXME: LUKS2 may enforce fixed size and it must not be changed */
  778     r = crypt_get_active_device(cd, action_argv[0], &cad);
  779     if (r)
  780         goto out;
  781 
  782     if (ARG_SET(OPT_DEVICE_SIZE_ID))
  783         dev_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE;
  784     else if (ARG_SET(OPT_SIZE_ID))
  785         dev_size = ARG_UINT64(OPT_SIZE_ID);
  786 
  787     if (cad.flags & CRYPT_ACTIVATE_KEYRING_KEY) {
  788         if (ARG_SET(OPT_DISABLE_KEYRING_ID)) {
  789             r = -EINVAL;
  790             log_err(_("Resize of active device requires volume key "
  791                   "in keyring but --disable-keyring option is set."));
  792                 goto out;
  793         }
  794 
  795         /* try load VK in kernel keyring using token */
  796         r = crypt_activate_by_token_pin(cd, NULL, ARG_STR(OPT_TOKEN_TYPE_ID),
  797                         ARG_INT32(OPT_TOKEN_ID_ID), NULL, 0, NULL,
  798                         CRYPT_ACTIVATE_KEYRING_KEY);
  799         tools_keyslot_msg(r, UNLOCKED);
  800         tools_token_error_msg(r, ARG_STR(OPT_TOKEN_TYPE_ID), ARG_INT32(OPT_TOKEN_ID_ID), false);
  801 
  802         /* Token requires PIN, but ask only if there is no password query later */
  803         if (ARG_SET(OPT_TOKEN_ONLY_ID) && r == -ENOANO)
  804             r = _try_token_pin_unlock(cd, ARG_INT32(OPT_TOKEN_ID_ID), NULL, ARG_STR(OPT_TOKEN_TYPE_ID), CRYPT_ACTIVATE_KEYRING_KEY, 1);
  805 
  806         if (r >= 0 || ARG_SET(OPT_TOKEN_ONLY_ID))
  807             goto out;
  808 
  809         r = tools_get_key(NULL, &password, &passwordLen,
  810                   ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
  811                   ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(0), 0, cd);
  812         if (r < 0)
  813             goto out;
  814 
  815         r = crypt_activate_by_passphrase(cd, NULL, ARG_INT32(OPT_KEY_SLOT_ID),
  816                          password, passwordLen,
  817                          CRYPT_ACTIVATE_KEYRING_KEY);
  818         tools_passphrase_msg(r);
  819         tools_keyslot_msg(r, UNLOCKED);
  820     }
  821 
  822 out:
  823     if (r >= 0)
  824         r = crypt_resize(cd, action_argv[0], dev_size);
  825 
  826     crypt_safe_free(password);
  827     crypt_free(cd);
  828     return r;
  829 }
  830 
  831 static int action_status(void)
  832 {
  833     crypt_status_info ci;
  834     crypt_reencrypt_info ri;
  835     struct crypt_active_device cad;
  836     struct crypt_params_integrity ip = {};
  837     struct crypt_device *cd = NULL;
  838     char *backing_file;
  839     const char *device;
  840     int path = 0, r = 0;
  841 
  842     /* perhaps a path, not a dm device name */
  843     if (strchr(action_argv[0], '/'))
  844         path = 1;
  845 
  846     ci = crypt_status(NULL, action_argv[0]);
  847     switch (ci) {
  848     case CRYPT_INVALID:
  849         r = -EINVAL;
  850         break;
  851     case CRYPT_INACTIVE:
  852         if (path)
  853             log_std("%s is inactive.\n", action_argv[0]);
  854         else
  855             log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]);
  856         r = -ENODEV;
  857         break;
  858     case CRYPT_ACTIVE:
  859     case CRYPT_BUSY:
  860         if (path)
  861             log_std("%s is active%s.\n", action_argv[0],
  862                 ci == CRYPT_BUSY ? " and is in use" : "");
  863         else
  864             log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0],
  865                 ci == CRYPT_BUSY ? " and is in use" : "");
  866 
  867         r = crypt_init_by_name_and_header(&cd, action_argv[0], ARG_STR(OPT_HEADER_ID));
  868         if (r < 0)
  869             goto out;
  870 
  871         log_std("  type:    %s\n", crypt_get_type(cd) ?: "n/a");
  872 
  873         /* Print only CRYPT type devices */
  874         if (!crypt_get_cipher(cd))
  875             goto out;
  876 
  877         ri = crypt_reencrypt_status(cd, NULL);
  878         if (ri > CRYPT_REENCRYPT_NONE && ri < CRYPT_REENCRYPT_INVALID)
  879             log_std("  reencryption:  in-progress\n");
  880 
  881         r = crypt_get_active_device(cd, action_argv[0], &cad);
  882         if (r < 0)
  883             goto out;
  884 
  885         r = crypt_get_integrity_info(cd, &ip);
  886         if (r < 0 && r != -ENOTSUP)
  887             goto out;
  888 
  889         log_std("  cipher:  %s-%s\n", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
  890         log_std("  keysize: %d bits\n", crypt_get_volume_key_size(cd) * 8);
  891         log_std("  key location: %s\n", (cad.flags & CRYPT_ACTIVATE_KEYRING_KEY) ? "keyring" : "dm-crypt");
  892         if (ip.integrity)
  893             log_std("  integrity: %s\n", ip.integrity);
  894         if (ip.integrity_key_size)
  895             log_std("  integrity keysize: %d bits\n", ip.integrity_key_size * 8);
  896         device = crypt_get_device_name(cd);
  897         log_std("  device:  %s\n", device);
  898         if ((backing_file = crypt_loop_backing_file(device))) {
  899             log_std("  loop:    %s\n", backing_file);
  900             free(backing_file);
  901         }
  902         log_std("  sector size:  %d\n", crypt_get_sector_size(cd));
  903         log_std("  offset:  %" PRIu64 " sectors\n", cad.offset);
  904         log_std("  size:    %" PRIu64 " sectors\n", cad.size);
  905         if (cad.iv_offset)
  906             log_std("  skipped: %" PRIu64 " sectors\n", cad.iv_offset);
  907         log_std("  mode:    %s%s\n", cad.flags & CRYPT_ACTIVATE_READONLY ?
  908                        "readonly" : "read/write",
  909                        (cad.flags & CRYPT_ACTIVATE_SUSPENDED) ? " (suspended)" : "");
  910         if (cad.flags & (CRYPT_ACTIVATE_ALLOW_DISCARDS|
  911                  CRYPT_ACTIVATE_SAME_CPU_CRYPT|
  912                  CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS|
  913                  CRYPT_ACTIVATE_NO_READ_WORKQUEUE|
  914                  CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE))
  915             log_std("  flags:   %s%s%s%s%s\n",
  916                 (cad.flags & CRYPT_ACTIVATE_ALLOW_DISCARDS) ? "discards " : "",
  917                 (cad.flags & CRYPT_ACTIVATE_SAME_CPU_CRYPT) ? "same_cpu_crypt " : "",
  918                 (cad.flags & CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS) ? "submit_from_crypt_cpus " : "",
  919                 (cad.flags & CRYPT_ACTIVATE_NO_READ_WORKQUEUE) ? "no_read_workqueue " : "",
  920                 (cad.flags & CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE) ? "no_write_workqueue" : "");
  921     }
  922 out:
  923     crypt_free(cd);
  924     if (r == -ENOTSUP)
  925         r = 0;
  926     return r;
  927 }
  928 
  929 static int benchmark_callback(uint32_t time_ms, void *usrptr)
  930 {
  931     struct crypt_pbkdf_type *pbkdf = usrptr;
  932     int r = 0;
  933 
  934     check_signal(&r);
  935     if (r)
  936         log_err(_("Benchmark interrupted."));
  937     else
  938         log_dbg("PBKDF benchmark: memory cost = %u, iterations = %u, "
  939             "threads = %u (took %u ms)", pbkdf->max_memory_kb,
  940             pbkdf->iterations, pbkdf->parallel_threads, time_ms);
  941     return r;
  942 }
  943 
  944 static int action_benchmark_kdf(const char *kdf, const char *hash, size_t key_size)
  945 {
  946     int r;
  947     if (!strcmp(kdf, CRYPT_KDF_PBKDF2)) {
  948         struct crypt_pbkdf_type pbkdf = {
  949             .type = CRYPT_KDF_PBKDF2,
  950             .hash = hash,
  951             .time_ms = 1000,
  952         };
  953 
  954         r = crypt_benchmark_pbkdf(NULL, &pbkdf, "foo", 3, "bar", 3, key_size,
  955                     &benchmark_callback, &pbkdf);
  956         if (r < 0)
  957             log_std(_("PBKDF2-%-9s     N/A\n"), hash);
  958         else
  959             log_std(_("PBKDF2-%-9s %7u iterations per second for %zu-bit key\n"),
  960                 hash, pbkdf.iterations, key_size * 8);
  961     } else {
  962         struct crypt_pbkdf_type pbkdf = {
  963             .type = kdf,
  964             .time_ms = ARG_UINT32(OPT_ITER_TIME_ID) ?: DEFAULT_LUKS2_ITER_TIME,
  965             .max_memory_kb = ARG_UINT32(OPT_PBKDF_MEMORY_ID),
  966             .parallel_threads = ARG_UINT32(OPT_PBKDF_PARALLEL_ID)
  967         };
  968 
  969         r = crypt_benchmark_pbkdf(NULL, &pbkdf, "foo", 3,
  970             "0123456789abcdef0123456789abcdef", 32,
  971             key_size, &benchmark_callback, &pbkdf);
  972         if (r < 0)
  973             log_std(_("%-10s N/A\n"), kdf);
  974         else
  975             log_std(_("%-10s %4u iterations, %5u memory, "
  976                 "%1u parallel threads (CPUs) for "
  977                 "%zu-bit key (requested %u ms time)\n"), kdf,
  978                 pbkdf.iterations, pbkdf.max_memory_kb, pbkdf.parallel_threads,
  979                 key_size * 8, pbkdf.time_ms);
  980     }
  981 
  982     return r;
  983 }
  984 
  985 static int benchmark_cipher_loop(const char *cipher, const char *cipher_mode,
  986                  size_t volume_key_size,
  987                  double *encryption_mbs, double *decryption_mbs)
  988 {
  989     int r, buffer_size = 1024 * 1024;
  990 
  991     do {
  992         r = crypt_benchmark(NULL, cipher, cipher_mode,
  993                     volume_key_size, 0, buffer_size,
  994                     encryption_mbs, decryption_mbs);
  995         if (r == -ERANGE) {
  996             if (buffer_size < 1024 * 1024 * 65)
  997                 buffer_size *= 2;
  998             else {
  999                 log_err(_("Result of benchmark is not reliable."));
 1000                 r = -ENOENT;
 1001             }
 1002         }
 1003     } while (r == -ERANGE);
 1004 
 1005     return r;
 1006 }
 1007 
 1008 static int action_benchmark(void)
 1009 {
 1010     static struct {
 1011         const char *cipher;
 1012         const char *mode;
 1013         size_t key_size;
 1014     } bciphers[] = {
 1015         { "aes",     "cbc", 16 },
 1016         { "serpent", "cbc", 16 },
 1017         { "twofish", "cbc", 16 },
 1018         { "aes",     "cbc", 32 },
 1019         { "serpent", "cbc", 32 },
 1020         { "twofish", "cbc", 32 },
 1021         { "aes",     "xts", 32 },
 1022         { "serpent", "xts", 32 },
 1023         { "twofish", "xts", 32 },
 1024         { "aes",     "xts", 64 },
 1025         { "serpent", "xts", 64 },
 1026         { "twofish", "xts", 64 },
 1027         {  NULL, NULL, 0 }
 1028     };
 1029     static struct {
 1030         const char *type;
 1031         const char *hash;
 1032     } bkdfs[] = {
 1033         { CRYPT_KDF_PBKDF2,   "sha1" },
 1034         { CRYPT_KDF_PBKDF2,   "sha256" },
 1035         { CRYPT_KDF_PBKDF2,   "sha512" },
 1036         { CRYPT_KDF_PBKDF2,   "ripemd160" },
 1037         { CRYPT_KDF_PBKDF2,   "whirlpool" },
 1038         { CRYPT_KDF_ARGON2I,  NULL },
 1039         { CRYPT_KDF_ARGON2ID, NULL },
 1040         { NULL, NULL }
 1041     };
 1042     char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
 1043     double enc_mbr = 0, dec_mbr = 0;
 1044     int key_size = (ARG_UINT32(OPT_KEY_SIZE_ID) ?: DEFAULT_PLAIN_KEYBITS) / 8;
 1045     int skipped = 0, width;
 1046     char *c;
 1047     int i, r;
 1048 
 1049     log_std(_("# Tests are approximate using memory only (no storage IO).\n"));
 1050     if (set_pbkdf || ARG_SET(OPT_HASH_ID)) {
 1051         if (!set_pbkdf && ARG_SET(OPT_HASH_ID))
 1052             set_pbkdf = CRYPT_KDF_PBKDF2;
 1053         r = action_benchmark_kdf(set_pbkdf, ARG_STR(OPT_HASH_ID), key_size);
 1054     } else if (ARG_SET(OPT_CIPHER_ID)) {
 1055         r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID), cipher, NULL, cipher_mode);
 1056         if (r < 0) {
 1057             log_err(_("No known cipher specification pattern detected."));
 1058             return r;
 1059         }
 1060         if ((c  = strchr(cipher_mode, '-')))
 1061             *c = '\0';
 1062 
 1063         r = benchmark_cipher_loop(cipher, cipher_mode, key_size, &enc_mbr, &dec_mbr);
 1064         if (!r) {
 1065             width = strlen(cipher) + strlen(cipher_mode) + 1;
 1066             if (width < 11)
 1067                 width = 11;
 1068             /* TRANSLATORS: The string is header of a table and must be exactly (right side) aligned. */
 1069             log_std(_("#%*s Algorithm |       Key |      Encryption |      Decryption\n"), width - 11, "");
 1070             log_std("%*s-%s  %9db  %10.1f MiB/s  %10.1f MiB/s\n", width - (int)strlen(cipher_mode) - 1,
 1071                 cipher, cipher_mode, key_size*8, enc_mbr, dec_mbr);
 1072         } else if (r < 0)
 1073             log_err(_("Cipher %s (with %i bits key) is not available."), ARG_STR(OPT_CIPHER_ID), key_size * 8);
 1074     } else {
 1075         for (i = 0; bkdfs[i].type; i++) {
 1076             r = action_benchmark_kdf(bkdfs[i].type, bkdfs[i].hash, key_size);
 1077             check_signal(&r);
 1078             if (r == -EINTR)
 1079                 break;
 1080         }
 1081 
 1082         for (i = 0; bciphers[i].cipher; i++) {
 1083             r = benchmark_cipher_loop(bciphers[i].cipher, bciphers[i].mode,
 1084                           bciphers[i].key_size, &enc_mbr, &dec_mbr);
 1085             check_signal(&r);
 1086             if (r == -ENOTSUP || r == -EINTR)
 1087                 break;
 1088             if (r == -ENOENT)
 1089                 skipped++;
 1090             if (i == 0)
 1091                 /* TRANSLATORS: The string is header of a table and must be exactly (right side) aligned. */
 1092                 log_std(_("#     Algorithm |       Key |      Encryption |      Decryption\n"));
 1093 
 1094             if (snprintf(cipher, MAX_CIPHER_LEN, "%s-%s",
 1095                      bciphers[i].cipher, bciphers[i].mode) < 0)
 1096                 r = -EINVAL;
 1097 
 1098             if (!r)
 1099                 log_std("%15s  %9zub  %10.1f MiB/s  %10.1f MiB/s\n",
 1100                     cipher, bciphers[i].key_size*8, enc_mbr, dec_mbr);
 1101             else
 1102                 log_std("%15s  %9zub %17s %17s\n", cipher,
 1103                     bciphers[i].key_size*8, _("N/A"), _("N/A"));
 1104         }
 1105         if (skipped && skipped == i)
 1106             r = -ENOTSUP;
 1107     }
 1108 
 1109     if (r == -ENOTSUP) {
 1110         log_err(_("Required kernel crypto interface not available."));
 1111 #ifdef ENABLE_AF_ALG
 1112         log_err( _("Ensure you have algif_skcipher kernel module loaded."));
 1113 #endif
 1114     }
 1115     return r;
 1116 }
 1117 
 1118 static int set_pbkdf_params(struct crypt_device *cd, const char *dev_type)
 1119 {
 1120     const struct crypt_pbkdf_type *pbkdf_default;
 1121     struct crypt_pbkdf_type pbkdf = {};
 1122 
 1123     pbkdf_default = crypt_get_pbkdf_default(dev_type);
 1124     if (!pbkdf_default)
 1125         return -EINVAL;
 1126 
 1127     pbkdf.type = set_pbkdf ?: pbkdf_default->type;
 1128     pbkdf.hash = ARG_STR(OPT_HASH_ID) ?: pbkdf_default->hash;
 1129     pbkdf.time_ms = ARG_UINT32(OPT_ITER_TIME_ID) ?: pbkdf_default->time_ms;
 1130     if (strcmp(pbkdf.type, CRYPT_KDF_PBKDF2)) {
 1131         pbkdf.max_memory_kb = ARG_UINT32(OPT_PBKDF_MEMORY_ID) ?: pbkdf_default->max_memory_kb;
 1132         pbkdf.parallel_threads = ARG_UINT32(OPT_PBKDF_PARALLEL_ID) ?: pbkdf_default->parallel_threads;
 1133     }
 1134 
 1135     if (ARG_SET(OPT_PBKDF_FORCE_ITERATIONS_ID)) {
 1136         pbkdf.iterations = ARG_UINT32(OPT_PBKDF_FORCE_ITERATIONS_ID);
 1137         pbkdf.time_ms = 0;
 1138         pbkdf.flags |= CRYPT_PBKDF_NO_BENCHMARK;
 1139     }
 1140 
 1141     return crypt_set_pbkdf_type(cd, &pbkdf);
 1142 }
 1143 
 1144 static int set_keyslot_params(struct crypt_device *cd, int keyslot)
 1145 {
 1146     const char *cipher;
 1147     struct crypt_pbkdf_type pbkdf;
 1148     size_t key_size;
 1149 
 1150     cipher = crypt_keyslot_get_encryption(cd, keyslot, &key_size);
 1151     if (!cipher)
 1152         return -EINVAL;
 1153 
 1154     if (crypt_is_cipher_null(cipher)) {
 1155         log_dbg("Keyslot %d uses cipher_null. Replacing with default encryption in new keyslot.", keyslot);
 1156         cipher = DEFAULT_LUKS2_KEYSLOT_CIPHER;
 1157         key_size = DEFAULT_LUKS2_KEYSLOT_KEYBITS / 8;
 1158     }
 1159 
 1160     if (crypt_keyslot_set_encryption(cd, cipher, key_size))
 1161         return -EINVAL;
 1162 
 1163     /* if requested any of those just reinitialize context pbkdf */
 1164     if (set_pbkdf || ARG_SET(OPT_HASH_ID) || ARG_SET(OPT_PBKDF_FORCE_ITERATIONS_ID) || ARG_SET(OPT_ITER_TIME_ID))
 1165         return set_pbkdf_params(cd, CRYPT_LUKS2);
 1166 
 1167     if (crypt_keyslot_get_pbkdf(cd, keyslot, &pbkdf))
 1168         return -EINVAL;
 1169 
 1170     pbkdf.flags |= CRYPT_PBKDF_NO_BENCHMARK;
 1171 
 1172     return crypt_set_pbkdf_type(cd, &pbkdf);
 1173 }
 1174 
 1175 static int reencrypt_metadata_repair(struct crypt_device *cd)
 1176 {
 1177     char *password;
 1178     size_t passwordLen;
 1179     int r;
 1180     struct crypt_params_reencrypt params = {
 1181         .flags = CRYPT_REENCRYPT_REPAIR_NEEDED
 1182     };
 1183 
 1184     if (!ARG_SET(OPT_BATCH_MODE_ID) &&
 1185         !yesDialog(_("Unprotected LUKS2 reencryption metadata detected. "
 1186              "Please verify the reencryption operation is desirable (see luksDump output)\n"
 1187              "and continue (upgrade metadata) only if you acknowledge the operation as genuine."),
 1188                _("Operation aborted.\n")))
 1189         return -EINVAL;
 1190 
 1191     r = tools_get_key(_("Enter passphrase to protect and uppgrade reencryption metadata: "),
 1192               &password, &passwordLen, ARG_UINT64(OPT_KEYFILE_OFFSET_ID),
 1193               ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID),
 1194               _verify_passphrase(0), 0, cd);
 1195     if (r < 0)
 1196         return r;
 1197 
 1198     r = crypt_reencrypt_init_by_passphrase(cd, NULL, password, passwordLen,
 1199             ARG_INT32(OPT_KEY_SLOT_ID), ARG_INT32(OPT_KEY_SLOT_ID), NULL, NULL, &params);
 1200     tools_passphrase_msg(r);
 1201     if (r < 0)
 1202         goto out;
 1203 
 1204     r = crypt_activate_by_passphrase(cd, NULL, ARG_INT32(OPT_KEY_SLOT_ID),
 1205                      password, passwordLen, 0);
 1206     tools_passphrase_msg(r);
 1207     if (r >= 0)
 1208         r = 0;
 1209 
 1210 out:
 1211     crypt_safe_free(password);
 1212     return r;
 1213 }
 1214 
 1215 static int luks2_reencrypt_repair(struct crypt_device *cd)
 1216 {
 1217     int r;
 1218     size_t passwordLen;
 1219     const char *msg;
 1220     char *password = NULL;
 1221     struct crypt_params_reencrypt params = {};
 1222 
 1223     crypt_reencrypt_info ri = crypt_reencrypt_status(cd, &params);
 1224 
 1225     if (params.flags & CRYPT_REENCRYPT_REPAIR_NEEDED)
 1226         return reencrypt_metadata_repair(cd);
 1227 
 1228     switch (ri) {
 1229     case CRYPT_REENCRYPT_NONE:
 1230         return 0;
 1231     case CRYPT_REENCRYPT_CLEAN:
 1232         break;
 1233     case CRYPT_REENCRYPT_CRASH:
 1234         if (!ARG_SET(OPT_BATCH_MODE_ID) &&
 1235             !yesDialog(_("Really proceed with LUKS2 reencryption recovery?"),
 1236                    _("Operation aborted.\n")))
 1237             return -EINVAL;
 1238         break;
 1239     default:
 1240         return -EINVAL;
 1241     }
 1242 
 1243     if (ri == CRYPT_REENCRYPT_CLEAN)
 1244         msg = _("Enter passphrase to verify reencryption metadata digest: ");
 1245     else
 1246         msg = _("Enter passphrase for reencryption recovery: ");
 1247 
 1248     r = tools_get_key(msg, &password, &passwordLen, ARG_UINT64(OPT_KEYFILE_OFFSET_ID),
 1249               ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID),
 1250               _verify_passphrase(0), 0, cd);
 1251     if (r < 0)
 1252         return r;
 1253 
 1254     r = crypt_activate_by_passphrase(cd, NULL, ARG_INT32(OPT_KEY_SLOT_ID),
 1255                      password, passwordLen, 0);
 1256     if (r < 0)
 1257         goto out;
 1258 
 1259     if (ri == CRYPT_REENCRYPT_CLEAN) {
 1260         r = 0;
 1261         goto out;
 1262     }
 1263 
 1264     r = crypt_reencrypt_init_by_passphrase(cd, NULL, password, passwordLen,
 1265             ARG_INT32(OPT_KEY_SLOT_ID), ARG_INT32(OPT_KEY_SLOT_ID), NULL, NULL,
 1266             &(struct crypt_params_reencrypt){ .flags = CRYPT_REENCRYPT_RECOVERY });
 1267     if (r > 0)
 1268         r = 0;
 1269 out:
 1270     crypt_safe_free(password);
 1271 
 1272     return r;
 1273 }
 1274 
 1275 static int action_luksRepair(void)
 1276 {
 1277     struct crypt_device *cd = NULL;
 1278     int r;
 1279 
 1280     if ((r = crypt_init_data_device(&cd, ARG_STR(OPT_HEADER_ID) ?: action_argv[0],
 1281                     action_argv[0])))
 1282         goto out;
 1283 
 1284     crypt_set_log_callback(cd, quiet_log, &log_parms);
 1285     r = crypt_load(cd, luksType(device_type), NULL);
 1286     crypt_set_log_callback(cd, tool_log, &log_parms);
 1287     if (r == 0 && isLUKS2(crypt_get_type(cd))) {
 1288         /*
 1289          * LUKS2 triggers autorepair in crypt_load() above
 1290          * LUKS1 need to call crypt_repair() even if crypt_load() is ok
 1291          */
 1292         log_verbose(_("No known problems detected for LUKS header."));
 1293         goto out;
 1294     }
 1295 
 1296     r = tools_detect_signatures(action_argv[0], 1, NULL, ARG_SET(OPT_BATCH_MODE_ID));
 1297     if (r < 0)
 1298         goto out;
 1299 
 1300     if (!ARG_SET(OPT_BATCH_MODE_ID) &&
 1301         !yesDialog(_("Really try to repair LUKS device header?"),
 1302                _("Operation aborted.\n")))
 1303         r = -EINVAL;
 1304     else
 1305         r = crypt_repair(cd, luksType(device_type), NULL);
 1306 out:
 1307     /* Header is ok, check if reencryption metadata needs repair/recovery. */
 1308     if (!r && isLUKS2(crypt_get_type(cd)))
 1309         r = luks2_reencrypt_repair(cd);
 1310 
 1311     crypt_free(cd);
 1312     return r;
 1313 }
 1314 
 1315 static int _wipe_data_device(struct crypt_device *cd)
 1316 {
 1317     char tmp_name[64], tmp_path[128], tmp_uuid[40];
 1318     uuid_t tmp_uuid_bin;
 1319     int r;
 1320     struct tools_progress_params prog_parms = {
 1321         .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID),
 1322         .batch_mode = ARG_SET(OPT_BATCH_MODE_ID)
 1323     };
 1324 
 1325     if (!ARG_SET(OPT_BATCH_MODE_ID))
 1326         log_std(_("Wiping device to initialize integrity checksum.\n"
 1327             "You can interrupt this by pressing CTRL+c "
 1328             "(rest of not wiped device will contain invalid checksum).\n"));
 1329 
 1330     /* Activate the device a temporary one */
 1331     uuid_generate(tmp_uuid_bin);
 1332     uuid_unparse(tmp_uuid_bin, tmp_uuid);
 1333     if (snprintf(tmp_name, sizeof(tmp_name), "temporary-cryptsetup-%s", tmp_uuid) < 0)
 1334         return -EINVAL;
 1335     if (snprintf(tmp_path, sizeof(tmp_path), "%s/%s", crypt_get_dir(), tmp_name) < 0)
 1336         return -EINVAL;
 1337 
 1338     r = crypt_activate_by_volume_key(cd, tmp_name, NULL, 0,
 1339         CRYPT_ACTIVATE_PRIVATE | CRYPT_ACTIVATE_NO_JOURNAL);
 1340     if (r < 0)
 1341         return r;
 1342 
 1343     /* Wipe the device */
 1344     set_int_handler(0);
 1345     r = crypt_wipe(cd, tmp_path, CRYPT_WIPE_ZERO, 0, 0, DEFAULT_WIPE_BLOCK,
 1346                0, &tools_wipe_progress, &prog_parms);
 1347     if (crypt_deactivate(cd, tmp_name))
 1348         log_err(_("Cannot deactivate temporary device %s."), tmp_path);
 1349     set_int_block(0);
 1350 
 1351     return r;
 1352 }
 1353 
 1354 static int strcmp_or_null(const char *str, const char *expected)
 1355 {
 1356     return !str ? 0 : strcmp(str, expected);
 1357 }
 1358 
 1359 static int get_adjusted_key_size(const char *cipher_mode, uint32_t default_size_bits, int integrity_keysize)
 1360 {
 1361     uint32_t keysize_bits = ARG_UINT32(OPT_KEY_SIZE_ID);
 1362 
 1363 #ifdef ENABLE_LUKS_ADJUST_XTS_KEYSIZE
 1364     if (!ARG_SET(OPT_KEY_SIZE_ID) && !strncmp(cipher_mode, "xts-", 4)) {
 1365         if (default_size_bits == 128)
 1366             keysize_bits = 256;
 1367         else if (default_size_bits == 256)
 1368             keysize_bits = 512;
 1369     }
 1370 #endif
 1371     return (keysize_bits ?: default_size_bits) / 8 + integrity_keysize;
 1372 }
 1373 
 1374 static int _luksFormat(struct crypt_device **r_cd, char **r_password, size_t *r_passwordLen)
 1375 {
 1376     int r = -EINVAL, keysize, integrity_keysize = 0, fd, created = 0;
 1377     struct stat st;
 1378     const char *header_device, *type;
 1379     char *msg = NULL, *key = NULL, *password = NULL;
 1380     char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN], integrity[MAX_CIPHER_LEN];
 1381     size_t passwordLen, signatures;
 1382     struct crypt_device *cd = NULL;
 1383     struct crypt_params_luks1 params1 = {
 1384         .hash = ARG_STR(OPT_HASH_ID) ?: DEFAULT_LUKS1_HASH,
 1385         .data_alignment = ARG_UINT32(OPT_ALIGN_PAYLOAD_ID),
 1386         .data_device = ARG_SET(OPT_HEADER_ID) ? action_argv[0] : NULL,
 1387     };
 1388     struct crypt_params_luks2 params2 = {
 1389         .data_alignment = params1.data_alignment,
 1390         .data_device = params1.data_device,
 1391         .sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID),
 1392         .label = ARG_STR(OPT_LABEL_ID),
 1393         .subsystem = ARG_STR(OPT_SUBSYSTEM_ID)
 1394     };
 1395     void *params;
 1396 
 1397     type = luksType(device_type);
 1398     if (!type)
 1399         type = crypt_get_default_type();
 1400 
 1401     if (isLUKS2(type)) {
 1402         params = &params2;
 1403     } else if (isLUKS1(type)) {
 1404         params = &params1;
 1405 
 1406         if (ARG_UINT32(OPT_SECTOR_SIZE_ID) > SECTOR_SIZE) {
 1407             log_err(_("Unsupported encryption sector size."));
 1408             return -EINVAL;
 1409         }
 1410 
 1411         if (ARG_SET(OPT_INTEGRITY_ID)) {
 1412             log_err(_("Integrity option can be used only for LUKS2 format."));
 1413             return -EINVAL;
 1414         }
 1415 
 1416         if (ARG_SET(OPT_LUKS2_KEYSLOTS_SIZE_ID) || ARG_SET(OPT_LUKS2_METADATA_SIZE_ID)) {
 1417             log_err(_("Unsupported LUKS2 metadata size options."));
 1418             return -EINVAL;
 1419         }
 1420     } else
 1421         return -EINVAL;
 1422 
 1423     /* Create header file (must contain at least one sector)? */
 1424     if (ARG_SET(OPT_HEADER_ID) && stat(ARG_STR(OPT_HEADER_ID), &st) < 0 && errno == ENOENT) {
 1425         if (!ARG_SET(OPT_BATCH_MODE_ID) &&
 1426             !yesDialog(_("Header file does not exist, do you want to create it?"),
 1427                    _("Operation aborted.\n")))
 1428             return -EPERM;
 1429 
 1430         log_dbg("Creating header file.");
 1431         /* coverity[toctou] */
 1432         fd = open(ARG_STR(OPT_HEADER_ID), O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR);
 1433         if (fd == -1 || posix_fallocate(fd, 0, 4096))
 1434             log_err(_("Cannot create header file %s."), ARG_STR(OPT_HEADER_ID));
 1435         else {
 1436             r = 0;
 1437             created = 1;
 1438         }
 1439         if (fd != -1)
 1440             close(fd);
 1441         if (r < 0)
 1442             return r;
 1443     }
 1444 
 1445     header_device = ARG_STR(OPT_HEADER_ID) ?: action_argv[0];
 1446 
 1447     r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID) ?: DEFAULT_CIPHER(LUKS1),
 1448                       cipher, NULL, cipher_mode);
 1449     if (r < 0) {
 1450         log_err(_("No known cipher specification pattern detected."));
 1451         goto out;
 1452     }
 1453 
 1454     if (ARG_SET(OPT_INTEGRITY_ID)) {
 1455         r = crypt_parse_integrity_mode(ARG_STR(OPT_INTEGRITY_ID), integrity, &integrity_keysize);
 1456         if (r < 0) {
 1457             log_err(_("No known integrity specification pattern detected."));
 1458             goto out;
 1459         }
 1460         params2.integrity = integrity;
 1461         /* FIXME: we use default integrity_params (set to NULL) */
 1462     }
 1463 
 1464     /* Never call pwquality if using null cipher */
 1465     if (crypt_is_cipher_null(cipher))
 1466         ARG_SET_TRUE(OPT_FORCE_PASSWORD_ID);
 1467 
 1468     if ((r = crypt_init(&cd, header_device))) {
 1469         if (ARG_SET(OPT_HEADER_ID))
 1470             log_err(_("Cannot use %s as on-disk header."), header_device);
 1471         return r;
 1472     }
 1473 
 1474     if (ARG_SET(OPT_LUKS2_KEYSLOTS_SIZE_ID) || ARG_SET(OPT_LUKS2_METADATA_SIZE_ID)) {
 1475         r = crypt_set_metadata_size(cd, ARG_UINT64(OPT_LUKS2_METADATA_SIZE_ID), ARG_UINT64(OPT_LUKS2_KEYSLOTS_SIZE_ID));
 1476         if (r < 0) {
 1477             log_err(_("Unsupported LUKS2 metadata size options."));
 1478             goto out;
 1479         }
 1480     }
 1481 
 1482     if (ARG_SET(OPT_OFFSET_ID)) {
 1483         r = crypt_set_data_offset(cd, ARG_UINT64(OPT_OFFSET_ID));
 1484         if (r < 0)
 1485             goto out;
 1486     }
 1487 
 1488     /* Print all present signatures in read-only mode */
 1489     r = tools_detect_signatures(header_device, 0, &signatures, ARG_SET(OPT_BATCH_MODE_ID));
 1490     if (r < 0)
 1491         goto out;
 1492 
 1493     if (!created && !ARG_SET(OPT_BATCH_MODE_ID)) {
 1494         r = asprintf(&msg, _("This will overwrite data on %s irrevocably."), header_device);
 1495         if (r == -1) {
 1496             r = -ENOMEM;
 1497             goto out;
 1498         }
 1499 
 1500         r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
 1501         free(msg);
 1502         if (r < 0)
 1503             goto out;
 1504     }
 1505 
 1506     keysize = get_adjusted_key_size(cipher_mode, DEFAULT_LUKS1_KEYBITS, integrity_keysize);
 1507 
 1508     if (ARG_SET(OPT_USE_RANDOM_ID))
 1509         crypt_set_rng_type(cd, CRYPT_RNG_RANDOM);
 1510     else if (ARG_SET(OPT_USE_URANDOM_ID))
 1511         crypt_set_rng_type(cd, CRYPT_RNG_URANDOM);
 1512 
 1513     r = tools_get_key(NULL, &password, &passwordLen,
 1514               ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 1515               ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(1), !ARG_SET(OPT_FORCE_PASSWORD_ID), cd);
 1516     if (r < 0)
 1517         goto out;
 1518 
 1519     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
 1520         r = tools_read_mk(ARG_STR(OPT_MASTER_KEY_FILE_ID), &key, keysize);
 1521         if (r < 0)
 1522             goto out;
 1523     }
 1524 
 1525     r = set_pbkdf_params(cd, type);
 1526     if (r) {
 1527         log_err(_("Failed to set pbkdf parameters."));
 1528         goto out;
 1529     }
 1530 
 1531     /* Signature candidates found */
 1532     if (signatures && ((r = tools_wipe_all_signatures(header_device)) < 0))
 1533         goto out;
 1534 
 1535     if (ARG_SET(OPT_INTEGRITY_LEGACY_PADDING_ID))
 1536         crypt_set_compatibility(cd, CRYPT_COMPAT_LEGACY_INTEGRITY_PADDING);
 1537 
 1538     r = crypt_format(cd, type, cipher, cipher_mode,
 1539              ARG_STR(OPT_UUID_ID), key, keysize, params);
 1540     check_signal(&r);
 1541     if (r < 0)
 1542         goto out;
 1543 
 1544     r = _set_keyslot_encryption_params(cd);
 1545     if (r < 0)
 1546         goto out;
 1547 
 1548     r = crypt_keyslot_add_by_volume_key(cd, ARG_INT32(OPT_KEY_SLOT_ID),
 1549                         key, keysize,
 1550                         password, passwordLen);
 1551     if (r < 0) {
 1552         (void) tools_wipe_all_signatures(header_device);
 1553         goto out;
 1554     }
 1555     tools_keyslot_msg(r, CREATED);
 1556 
 1557     if (ARG_SET(OPT_INTEGRITY_ID) && !ARG_SET(OPT_INTEGRITY_NO_WIPE_ID) &&
 1558         strcmp_or_null(params2.integrity, "none"))
 1559         r = _wipe_data_device(cd);
 1560 out:
 1561     if (r >= 0 && r_cd && r_password && r_passwordLen) {
 1562         *r_cd = cd;
 1563         *r_password = password;
 1564         *r_passwordLen = passwordLen;
 1565     } else {
 1566         crypt_free(cd);
 1567         crypt_safe_free(password);
 1568     }
 1569 
 1570     crypt_safe_free(key);
 1571 
 1572     return r;
 1573 }
 1574 
 1575 static int action_luksFormat(void)
 1576 {
 1577     return _luksFormat(NULL, NULL, NULL);
 1578 }
 1579 
 1580 static int action_open_luks(void)
 1581 {
 1582     struct crypt_active_device cad;
 1583     struct crypt_device *cd = NULL;
 1584     const char *data_device, *header_device, *activated_name;
 1585     char *key = NULL;
 1586     uint32_t activate_flags = 0;
 1587     int r, keysize, tries;
 1588     char *password = NULL;
 1589     size_t passwordLen;
 1590 
 1591     if (ARG_SET(OPT_REFRESH_ID)) {
 1592         activated_name = action_argc > 1 ? action_argv[1] : action_argv[0];
 1593         r = crypt_init_by_name_and_header(&cd, activated_name, ARG_STR(OPT_HEADER_ID));
 1594         if (r)
 1595             goto out;
 1596         activate_flags |= CRYPT_ACTIVATE_REFRESH;
 1597     } else {
 1598         header_device = uuid_or_device_header(&data_device);
 1599 
 1600         activated_name = ARG_SET(OPT_TEST_PASSPHRASE_ID) ? NULL : action_argv[1];
 1601 
 1602         if ((r = crypt_init_data_device(&cd, header_device, data_device)))
 1603             goto out;
 1604 
 1605         if ((r = crypt_load(cd, luksType(device_type), NULL))) {
 1606             log_err(_("Device %s is not a valid LUKS device."),
 1607                 header_device);
 1608             goto out;
 1609         }
 1610 
 1611         if (!data_device && (crypt_get_data_offset(cd) < 8) && !ARG_SET(OPT_TEST_PASSPHRASE_ID)) {
 1612             log_err(_("Reduced data offset is allowed only for detached LUKS header."));
 1613             r = -EINVAL;
 1614             goto out;
 1615         }
 1616     }
 1617 
 1618     _set_activation_flags(&activate_flags);
 1619 
 1620     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
 1621         keysize = crypt_get_volume_key_size(cd);
 1622         if (!keysize && !ARG_SET(OPT_KEY_SIZE_ID)) {
 1623             log_err(_("Cannot determine volume key size for LUKS without keyslots, please use --key-size option."));
 1624             r = -EINVAL;
 1625             goto out;
 1626         } else if (!keysize)
 1627             keysize = ARG_UINT32(OPT_KEY_SIZE_ID) / 8;
 1628 
 1629         r = tools_read_mk(ARG_STR(OPT_MASTER_KEY_FILE_ID), &key, keysize);
 1630         if (r < 0)
 1631             goto out;
 1632         r = crypt_activate_by_volume_key(cd, activated_name,
 1633                          key, keysize, activate_flags);
 1634     } else {
 1635         r = crypt_activate_by_token_pin(cd, activated_name, ARG_STR(OPT_TOKEN_TYPE_ID),
 1636                         ARG_INT32(OPT_TOKEN_ID_ID), NULL, 0, NULL, activate_flags);
 1637         tools_keyslot_msg(r, UNLOCKED);
 1638         tools_token_error_msg(r, ARG_STR(OPT_TOKEN_TYPE_ID), ARG_INT32(OPT_TOKEN_ID_ID), false);
 1639 
 1640         /* Token requires PIN, but ask only if there is no password query later */
 1641         if (ARG_SET(OPT_TOKEN_ONLY_ID) && r == -ENOANO)
 1642             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());
 1643 
 1644         if (r >= 0 || r == -EEXIST || ARG_SET(OPT_TOKEN_ONLY_ID))
 1645             goto out;
 1646 
 1647         tries = _set_tries_tty();
 1648         do {
 1649             r = tools_get_key(NULL, &password, &passwordLen,
 1650                     ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 1651                     ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(0), 0, cd);
 1652             if (r < 0)
 1653                 goto out;
 1654 
 1655             r = crypt_activate_by_passphrase(cd, activated_name,
 1656                 ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen, activate_flags);
 1657             tools_keyslot_msg(r, UNLOCKED);
 1658             tools_passphrase_msg(r);
 1659             check_signal(&r);
 1660             crypt_safe_free(password);
 1661             password = NULL;
 1662         } while ((r == -EPERM || r == -ERANGE) && (--tries > 0));
 1663     }
 1664 out:
 1665     if (r >= 0 && ARG_SET(OPT_PERSISTENT_ID) &&
 1666         (crypt_get_active_device(cd, activated_name, &cad) ||
 1667          crypt_persistent_flags_set(cd, CRYPT_FLAGS_ACTIVATION, cad.flags & activate_flags)))
 1668         log_err(_("Device activated but cannot make flags persistent."));
 1669 
 1670     crypt_safe_free(key);
 1671     crypt_safe_free(password);
 1672     crypt_free(cd);
 1673     return r;
 1674 }
 1675 
 1676 static int verify_keyslot(struct crypt_device *cd, int key_slot, crypt_keyslot_info ki,
 1677               char *msg_last, char *msg_pass, char *msg_fail,
 1678               const char *key_file, uint64_t keyfile_offset,
 1679               int keyfile_size)
 1680 {
 1681     char *password = NULL;
 1682     size_t passwordLen;
 1683     int i, max, r;
 1684 
 1685     if (ki == CRYPT_SLOT_ACTIVE_LAST && !ARG_SET(OPT_BATCH_MODE_ID) && !key_file &&
 1686         msg_last && !ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog(msg_last, msg_fail))
 1687         return -EPERM;
 1688 
 1689     r = tools_get_key(msg_pass, &password, &passwordLen,
 1690               keyfile_offset, keyfile_size, key_file, ARG_UINT32(OPT_TIMEOUT_ID),
 1691               _verify_passphrase(0), 0, cd);
 1692     if (r < 0)
 1693         goto out;
 1694 
 1695     if (ki == CRYPT_SLOT_ACTIVE_LAST) {
 1696         /* check the last keyslot */
 1697         r = crypt_activate_by_passphrase(cd, NULL, key_slot,
 1698                          password, passwordLen, 0);
 1699     } else {
 1700         /* try all other keyslots */
 1701         r = crypt_keyslot_max(crypt_get_type(cd));
 1702         if (r < 0)
 1703             goto out;
 1704         max = r;
 1705 
 1706         for (i = 0; i < max ; i++) {
 1707             if (i == key_slot)
 1708                 continue;
 1709             ki = crypt_keyslot_status(cd, i);
 1710             if (ki == CRYPT_SLOT_ACTIVE || ki == CRYPT_SLOT_ACTIVE_LAST)
 1711                 r = crypt_activate_by_passphrase(cd, NULL, i,
 1712                          password, passwordLen, 0);
 1713             if (r == i)
 1714                 break;
 1715         }
 1716     }
 1717 
 1718     /* Handle inactive keyslots the same as bad password here */
 1719     if (r == -ENOENT)
 1720         r = -EPERM;
 1721     tools_passphrase_msg(r);
 1722 out:
 1723     crypt_safe_free(password);
 1724     return r;
 1725 }
 1726 
 1727 static int action_luksKillSlot(void)
 1728 {
 1729     struct crypt_device *cd = NULL;
 1730     crypt_keyslot_info ki;
 1731     int r;
 1732 
 1733     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 1734         goto out;
 1735 
 1736     if ((r = crypt_load(cd, luksType(device_type), NULL))) {
 1737         log_err(_("Device %s is not a valid LUKS device."),
 1738             uuid_or_device_header(NULL));
 1739         goto out;
 1740     }
 1741 
 1742     ki = crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID));
 1743     switch (ki) {
 1744     case CRYPT_SLOT_ACTIVE_LAST:
 1745     case CRYPT_SLOT_ACTIVE:
 1746     case CRYPT_SLOT_UNBOUND:
 1747         log_verbose(_("Keyslot %d is selected for deletion."), ARG_INT32(OPT_KEY_SLOT_ID));
 1748         break;
 1749     case CRYPT_SLOT_INACTIVE:
 1750         log_err(_("Keyslot %d is not active."), ARG_INT32(OPT_KEY_SLOT_ID));
 1751         /* fall through */
 1752     case CRYPT_SLOT_INVALID:
 1753         r = -EINVAL;
 1754         goto out;
 1755     }
 1756 
 1757     if (!ARG_SET(OPT_BATCH_MODE_ID) || ARG_SET(OPT_KEY_FILE_ID) || !isatty(STDIN_FILENO)) {
 1758         r = verify_keyslot(cd, ARG_INT32(OPT_KEY_SLOT_ID), ki,
 1759             _("This is the last keyslot. Device will become unusable after purging this key."),
 1760             _("Enter any remaining passphrase: "),
 1761             _("Operation aborted, the keyslot was NOT wiped.\n"),
 1762             ARG_STR(OPT_KEY_FILE_ID), ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID));
 1763         tools_keyslot_msg(r, UNLOCKED);
 1764 
 1765         if (r == -EPIPE && (!ARG_SET(OPT_KEY_FILE_ID) || tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID)))) {
 1766             log_dbg("Failed read from input, ignoring passphrase.");
 1767             r = 0;
 1768         }
 1769 
 1770         if (r < 0)
 1771             goto out;
 1772     }
 1773 
 1774     r = crypt_keyslot_destroy(cd, ARG_INT32(OPT_KEY_SLOT_ID));
 1775     tools_keyslot_msg(ARG_INT32(OPT_KEY_SLOT_ID), REMOVED);
 1776 out:
 1777     crypt_free(cd);
 1778     return r;
 1779 }
 1780 
 1781 static int action_luksRemoveKey(void)
 1782 {
 1783     struct crypt_device *cd = NULL;
 1784     char *password = NULL;
 1785     size_t passwordLen;
 1786     int r;
 1787 
 1788     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 1789         goto out;
 1790 
 1791     if ((r = crypt_load(cd, luksType(device_type), NULL))) {
 1792         log_err(_("Device %s is not a valid LUKS device."),
 1793             uuid_or_device_header(NULL));
 1794         goto out;
 1795     }
 1796 
 1797     r = tools_get_key(_("Enter passphrase to be deleted: "),
 1798               &password, &passwordLen,
 1799               ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 1800               ARG_UINT32(OPT_TIMEOUT_ID),
 1801               _verify_passphrase(0), 0,
 1802               cd);
 1803     if(r < 0)
 1804         goto out;
 1805 
 1806     r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT,
 1807                      password, passwordLen, 0);
 1808     tools_passphrase_msg(r);
 1809     check_signal(&r);
 1810     if (r < 0)
 1811         goto out;
 1812     tools_keyslot_msg(r, UNLOCKED);
 1813 
 1814     ARG_SET_INT32(OPT_KEY_SLOT_ID, r);
 1815     log_verbose(_("Keyslot %d is selected for deletion."), ARG_INT32(OPT_KEY_SLOT_ID));
 1816 
 1817     if (crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)) == CRYPT_SLOT_ACTIVE_LAST &&
 1818         !ARG_SET(OPT_BATCH_MODE_ID) &&
 1819         !yesDialog(_("This is the last keyslot. "
 1820              "Device will become unusable after purging this key."),
 1821                _("Operation aborted, the keyslot was NOT wiped.\n"))) {
 1822         r = -EPERM;
 1823         goto out;
 1824     }
 1825 
 1826     r = crypt_keyslot_destroy(cd, ARG_INT32(OPT_KEY_SLOT_ID));
 1827     tools_keyslot_msg(ARG_INT32(OPT_KEY_SLOT_ID), REMOVED);
 1828 out:
 1829     crypt_safe_free(password);
 1830     crypt_free(cd);
 1831     return r;
 1832 }
 1833 
 1834 static int luksAddUnboundKey(void)
 1835 {
 1836     int r = -EINVAL, keysize = 0;
 1837     char *key = NULL;
 1838     const char *new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
 1839     char *password_new = NULL;
 1840     size_t password_new_size = 0;
 1841     struct crypt_device *cd = NULL;
 1842 
 1843     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 1844         goto out;
 1845 
 1846     if ((r = crypt_load(cd, CRYPT_LUKS2, NULL))) {
 1847         log_err(_("Device %s is not a valid LUKS device."),
 1848             uuid_or_device_header(NULL));
 1849         goto out;
 1850     }
 1851 
 1852     r = _set_keyslot_encryption_params(cd);
 1853     if (r < 0)
 1854         goto out;
 1855 
 1856     /* Never call pwquality if using null cipher */
 1857     if (crypt_is_cipher_null(crypt_get_cipher(cd)))
 1858         ARG_SET_TRUE(OPT_FORCE_PASSWORD_ID);
 1859 
 1860     keysize = ARG_UINT32(OPT_KEY_SIZE_ID) / 8;
 1861     r = set_pbkdf_params(cd, crypt_get_type(cd));
 1862     if (r) {
 1863         log_err(_("Failed to set pbkdf parameters."));
 1864         goto out;
 1865     }
 1866 
 1867     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
 1868         r = tools_read_mk(ARG_STR(OPT_MASTER_KEY_FILE_ID), &key, keysize);
 1869         if (r < 0)
 1870             goto out;
 1871 
 1872         check_signal(&r);
 1873         if (r < 0)
 1874             goto out;
 1875     }
 1876 
 1877     r = tools_get_key(_("Enter new passphrase for key slot: "),
 1878               &password_new, &password_new_size,
 1879               ARG_UINT64(OPT_NEW_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_NEW_KEYFILE_SIZE_ID),
 1880               new_key_file, ARG_UINT32(OPT_TIMEOUT_ID),
 1881               _verify_passphrase(1), !ARG_SET(OPT_FORCE_PASSWORD_ID), cd);
 1882     if (r < 0)
 1883         goto out;
 1884 
 1885     r = crypt_keyslot_add_by_key(cd, ARG_INT32(OPT_KEY_SLOT_ID), key, keysize,
 1886             password_new, password_new_size, CRYPT_VOLUME_KEY_NO_SEGMENT);
 1887     tools_keyslot_msg(r, CREATED);
 1888 out:
 1889     crypt_safe_free(password_new);
 1890     crypt_safe_free(key);
 1891     crypt_free(cd);
 1892     return r;
 1893 }
 1894 
 1895 static int action_luksAddKey(void)
 1896 {
 1897     int r = -EINVAL, keysize = 0;
 1898     char *key = NULL;
 1899     const char *new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
 1900     char *password = NULL, *password_new = NULL;
 1901     size_t password_size = 0, password_new_size = 0;
 1902     struct crypt_device *cd = NULL;
 1903 
 1904     /* Unbound keyslot (no assigned data segment) is special case */
 1905     if (ARG_SET(OPT_UNBOUND_ID))
 1906         return luksAddUnboundKey();
 1907 
 1908     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 1909         goto out;
 1910 
 1911     if ((r = crypt_load(cd, luksType(device_type), NULL))) {
 1912         log_err(_("Device %s is not a valid LUKS device."),
 1913             uuid_or_device_header(NULL));
 1914         goto out;
 1915     }
 1916 
 1917     r = _set_keyslot_encryption_params(cd);
 1918     if (r < 0)
 1919         goto out;
 1920 
 1921     /* Never call pwquality if using null cipher */
 1922     if (crypt_is_cipher_null(crypt_get_cipher(cd)))
 1923         ARG_SET_TRUE(OPT_FORCE_PASSWORD_ID);
 1924 
 1925     keysize = crypt_get_volume_key_size(cd);
 1926     r = set_pbkdf_params(cd, crypt_get_type(cd));
 1927     if (r) {
 1928         log_err(_("Failed to set pbkdf parameters."));
 1929         goto out;
 1930     }
 1931 
 1932     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
 1933         if (!keysize && !ARG_SET(OPT_KEY_SIZE_ID)) {
 1934             log_err(_("Cannot determine volume key size for LUKS without keyslots, please use --key-size option."));
 1935             r = -EINVAL;
 1936             goto out;
 1937         } else if (!keysize)
 1938             keysize = ARG_UINT32(OPT_KEY_SIZE_ID) / 8;
 1939 
 1940         r = tools_read_mk(ARG_STR(OPT_MASTER_KEY_FILE_ID), &key, keysize);
 1941         if (r < 0)
 1942             goto out;
 1943 
 1944         r = crypt_volume_key_verify(cd, key, keysize);
 1945         check_signal(&r);
 1946         if (r < 0)
 1947             goto out;
 1948 
 1949         r = tools_get_key(_("Enter new passphrase for key slot: "),
 1950                   &password_new, &password_new_size,
 1951                   ARG_UINT64(OPT_NEW_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_NEW_KEYFILE_SIZE_ID),
 1952                   new_key_file, ARG_UINT32(OPT_TIMEOUT_ID),
 1953                   _verify_passphrase(1), !ARG_SET(OPT_FORCE_PASSWORD_ID), cd);
 1954         if (r < 0)
 1955             goto out;
 1956 
 1957         r = crypt_keyslot_add_by_volume_key(cd, ARG_INT32(OPT_KEY_SLOT_ID), key, keysize,
 1958                             password_new, password_new_size);
 1959     } else if (ARG_SET(OPT_KEY_FILE_ID) && !tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID)) &&
 1960            new_key_file && !tools_is_stdin(new_key_file)) {
 1961         r = crypt_keyslot_add_by_keyfile_device_offset(cd, ARG_INT32(OPT_KEY_SLOT_ID),
 1962             ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_UINT64(OPT_KEYFILE_OFFSET_ID),
 1963             new_key_file, ARG_UINT32(OPT_NEW_KEYFILE_SIZE_ID), ARG_UINT64(OPT_NEW_KEYFILE_OFFSET_ID));
 1964         tools_passphrase_msg(r);
 1965     } else {
 1966         r = tools_get_key(_("Enter any existing passphrase: "),
 1967                   &password, &password_size,
 1968                   ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 1969                   ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(0), 0, cd);
 1970 
 1971         if (r < 0)
 1972             goto out;
 1973 
 1974         /* Check password before asking for new one */
 1975         r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT,
 1976                          password, password_size, 0);
 1977         check_signal(&r);
 1978         tools_passphrase_msg(r);
 1979         if (r < 0)
 1980             goto out;
 1981         tools_keyslot_msg(r, UNLOCKED);
 1982 
 1983         r = tools_get_key(_("Enter new passphrase for key slot: "),
 1984                   &password_new, &password_new_size,
 1985                   ARG_UINT64(OPT_NEW_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_NEW_KEYFILE_SIZE_ID), new_key_file,
 1986                   ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(1), !ARG_SET(OPT_FORCE_PASSWORD_ID), cd);
 1987         if (r < 0)
 1988             goto out;
 1989 
 1990         r = crypt_keyslot_add_by_passphrase(cd, ARG_INT32(OPT_KEY_SLOT_ID),
 1991                             password, password_size,
 1992                             password_new, password_new_size);
 1993     }
 1994 out:
 1995     tools_keyslot_msg(r, CREATED);
 1996     crypt_safe_free(password);
 1997     crypt_safe_free(password_new);
 1998     crypt_safe_free(key);
 1999     crypt_free(cd);
 2000     return r;
 2001 }
 2002 
 2003 static int action_luksChangeKey(void)
 2004 {
 2005     const char *new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
 2006     struct crypt_device *cd = NULL;
 2007     char *password = NULL, *password_new = NULL;
 2008     size_t password_size = 0, password_new_size = 0;
 2009     int r;
 2010 
 2011     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 2012         goto out;
 2013 
 2014     if ((r = crypt_load(cd, luksType(device_type), NULL))) {
 2015         log_err(_("Device %s is not a valid LUKS device."),
 2016             uuid_or_device_header(NULL));
 2017         goto out;
 2018     }
 2019 
 2020     r = _set_keyslot_encryption_params(cd);
 2021     if (r < 0)
 2022         goto out;
 2023 
 2024     /* Never call pwquality if using null cipher */
 2025     if (crypt_is_cipher_null(crypt_get_cipher(cd)))
 2026         ARG_SET_TRUE(OPT_FORCE_PASSWORD_ID);
 2027 
 2028     r = set_pbkdf_params(cd, crypt_get_type(cd));
 2029     if (r) {
 2030         log_err(_("Failed to set pbkdf parameters."));
 2031         goto out;
 2032     }
 2033 
 2034     r = tools_get_key(_("Enter passphrase to be changed: "),
 2035               &password, &password_size,
 2036               ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 2037               ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(0), 0, cd);
 2038     if (r < 0)
 2039         goto out;
 2040 
 2041     /* Check password before asking for new one */
 2042     r = crypt_activate_by_passphrase(cd, NULL, ARG_INT32(OPT_KEY_SLOT_ID),
 2043                      password, password_size, CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY);
 2044     tools_passphrase_msg(r);
 2045     check_signal(&r);
 2046     if (r < 0)
 2047         goto out;
 2048     tools_keyslot_msg(r, UNLOCKED);
 2049 
 2050     r = tools_get_key(_("Enter new passphrase: "),
 2051               &password_new, &password_new_size,
 2052               ARG_UINT64(OPT_NEW_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_NEW_KEYFILE_SIZE_ID),
 2053               new_key_file,
 2054               ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(1), !ARG_SET(OPT_FORCE_PASSWORD_ID), cd);
 2055     if (r < 0)
 2056         goto out;
 2057 
 2058     r = crypt_keyslot_change_by_passphrase(cd, ARG_INT32(OPT_KEY_SLOT_ID), ARG_INT32(OPT_KEY_SLOT_ID),
 2059         password, password_size, password_new, password_new_size);
 2060     tools_keyslot_msg(r, CREATED);
 2061 out:
 2062     crypt_safe_free(password);
 2063     crypt_safe_free(password_new);
 2064     crypt_free(cd);
 2065     return r;
 2066 }
 2067 
 2068 static int action_luksConvertKey(void)
 2069 {
 2070     struct crypt_device *cd = NULL;
 2071     char *password = NULL;
 2072     size_t password_size = 0;
 2073     int r;
 2074 
 2075     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 2076         goto out;
 2077 
 2078     if ((r = crypt_load(cd, CRYPT_LUKS2, NULL))) {
 2079         log_err(_("Device %s is not a valid LUKS device."),
 2080             uuid_or_device_header(NULL));
 2081         goto out;
 2082     }
 2083 
 2084     r = _set_keyslot_encryption_params(cd);
 2085     if (r < 0)
 2086         goto out;
 2087 
 2088     if (crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)) == CRYPT_SLOT_INACTIVE) {
 2089         r = -EINVAL;
 2090         log_err(_("Keyslot %d is not active."), ARG_INT32(OPT_KEY_SLOT_ID));
 2091         goto out;
 2092     }
 2093 
 2094     r = set_pbkdf_params(cd, crypt_get_type(cd));
 2095     if (r) {
 2096         log_err(_("Failed to set pbkdf parameters."));
 2097         goto out;
 2098     }
 2099 
 2100     r = tools_get_key(_("Enter passphrase for keyslot to be converted: "),
 2101               &password, &password_size,
 2102               ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 2103               ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(0), 0, cd);
 2104     if (r < 0)
 2105         goto out;
 2106 
 2107     r = crypt_keyslot_change_by_passphrase(cd, ARG_INT32(OPT_KEY_SLOT_ID), ARG_INT32(OPT_KEY_SLOT_ID),
 2108             password, password_size, password, password_size);
 2109     tools_passphrase_msg(r);
 2110     tools_keyslot_msg(r, CREATED);
 2111 out:
 2112     crypt_safe_free(password);
 2113     crypt_free(cd);
 2114     return r;
 2115 }
 2116 
 2117 static int action_isLuks(void)
 2118 {
 2119     struct crypt_device *cd = NULL;
 2120     int r;
 2121 
 2122     /* FIXME: argc > max should be checked for other operations as well */
 2123     if (action_argc > 1) {
 2124         log_err(_("Only one device argument for isLuks operation is supported."));
 2125         return -ENODEV;
 2126     }
 2127 
 2128     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 2129         goto out;
 2130 
 2131     crypt_set_log_callback(cd, quiet_log, &log_parms);
 2132     r = crypt_load(cd, luksType(device_type), NULL);
 2133 out:
 2134     crypt_free(cd);
 2135     return r;
 2136 }
 2137 
 2138 static int action_luksUUID(void)
 2139 {
 2140     struct crypt_device *cd = NULL;
 2141     const char *existing_uuid = NULL;
 2142     int r;
 2143 
 2144     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 2145         goto out;
 2146 
 2147     if (!ARG_SET(OPT_BATCH_MODE_ID))
 2148         crypt_set_confirm_callback(cd, yesDialog, _("Operation aborted.\n"));
 2149 
 2150     if ((r = crypt_load(cd, luksType(device_type), NULL)))
 2151         goto out;
 2152 
 2153     if (ARG_SET(OPT_UUID_ID))
 2154         r = crypt_set_uuid(cd, ARG_STR(OPT_UUID_ID));
 2155     else {
 2156         existing_uuid = crypt_get_uuid(cd);
 2157         log_std("%s\n", existing_uuid ?: "");
 2158         r = existing_uuid ? 0 : 1;
 2159     }
 2160 out:
 2161     crypt_free(cd);
 2162     return r;
 2163 }
 2164 
 2165 static int luksDump_with_volume_key(struct crypt_device *cd)
 2166 {
 2167     char *vk = NULL, *password = NULL;
 2168     size_t passwordLen = 0;
 2169     size_t vk_size;
 2170     unsigned i;
 2171     int r;
 2172 
 2173     if (!ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog(
 2174         _("The header dump with volume key is sensitive information\n"
 2175           "that allows access to encrypted partition without a passphrase.\n"
 2176           "This dump should be stored encrypted in a safe place."),
 2177           NULL))
 2178         return -EPERM;
 2179 
 2180     vk_size = crypt_get_volume_key_size(cd);
 2181     vk = crypt_safe_alloc(vk_size);
 2182     if (!vk)
 2183         return -ENOMEM;
 2184 
 2185     r = tools_get_key(NULL, &password, &passwordLen,
 2186               ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 2187               ARG_UINT32(OPT_TIMEOUT_ID), 0, 0, cd);
 2188     if (r < 0)
 2189         goto out;
 2190 
 2191     r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size,
 2192                  password, passwordLen);
 2193     tools_passphrase_msg(r);
 2194     check_signal(&r);
 2195     if (r < 0)
 2196         goto out;
 2197     tools_keyslot_msg(r, UNLOCKED);
 2198 
 2199     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
 2200         r = tools_write_mk(ARG_STR(OPT_MASTER_KEY_FILE_ID), vk, vk_size);
 2201         if (r < 0)
 2202             goto out;
 2203     }
 2204 
 2205     log_std("LUKS header information for %s\n", crypt_get_device_name(cd));
 2206     log_std("Cipher name:   \t%s\n", crypt_get_cipher(cd));
 2207     log_std("Cipher mode:   \t%s\n", crypt_get_cipher_mode(cd));
 2208     log_std("Payload offset:\t%d\n", (int)crypt_get_data_offset(cd));
 2209     log_std("UUID:          \t%s\n", crypt_get_uuid(cd));
 2210     log_std("MK bits:       \t%d\n", (int)vk_size * 8);
 2211     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
 2212         log_std("Key stored to file %s.\n", ARG_STR(OPT_MASTER_KEY_FILE_ID));
 2213         goto out;
 2214     }
 2215     log_std("MK dump:\t");
 2216 
 2217     for(i = 0; i < vk_size; i++) {
 2218         if (i && !(i % 16))
 2219             log_std("\n\t\t");
 2220         log_std("%02hhx ", (char)vk[i]);
 2221     }
 2222     log_std("\n");
 2223 
 2224 out:
 2225     crypt_safe_free(password);
 2226     crypt_safe_free(vk);
 2227     return r;
 2228 }
 2229 
 2230 static int luksDump_with_unbound_key(struct crypt_device *cd)
 2231 {
 2232     crypt_keyslot_info ki;
 2233     char *uk = NULL, *password = NULL;
 2234     size_t uk_size, passwordLen = 0;
 2235     int i, r;
 2236 
 2237     ki = crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID));
 2238     if (ki != CRYPT_SLOT_UNBOUND) {
 2239         log_err(_("Keyslot %d does not contain unbound key."), ARG_INT32(OPT_KEY_SLOT_ID));
 2240         return -EINVAL;
 2241     }
 2242 
 2243     if (!ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog(
 2244         _("The header dump with unbound key is sensitive information.\n"
 2245           "This dump should be stored encrypted in a safe place."),
 2246           NULL))
 2247         return -EPERM;
 2248 
 2249     r = crypt_keyslot_get_key_size(cd, ARG_INT32(OPT_KEY_SLOT_ID));
 2250     if (r < 0)
 2251         return -EINVAL;
 2252     uk_size = r;
 2253     uk = crypt_safe_alloc(uk_size);
 2254     if (!uk)
 2255         return -ENOMEM;
 2256 
 2257     r = tools_get_key(NULL, &password, &passwordLen,
 2258               ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 2259               ARG_UINT32(OPT_TIMEOUT_ID), 0, 0, cd);
 2260     if (r < 0)
 2261         goto out;
 2262 
 2263     r = crypt_volume_key_get(cd, ARG_INT32(OPT_KEY_SLOT_ID), uk, &uk_size,
 2264                  password, passwordLen);
 2265     tools_passphrase_msg(r);
 2266     check_signal(&r);
 2267     if (r < 0)
 2268         goto out;
 2269     tools_keyslot_msg(r, UNLOCKED);
 2270 
 2271     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
 2272         r = tools_write_mk(ARG_STR(OPT_MASTER_KEY_FILE_ID), uk, uk_size);
 2273         if (r < 0)
 2274             goto out;
 2275     }
 2276 
 2277     log_std("LUKS header information for %s\n", crypt_get_device_name(cd));
 2278     log_std("UUID:    \t%s\n", crypt_get_uuid(cd));
 2279     log_std("Keyslot: \t%d\n", ARG_INT32(OPT_KEY_SLOT_ID));
 2280     log_std("Key bits:\t%d\n", (int)uk_size * 8);
 2281     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
 2282         log_std("Key stored to file %s.\n", ARG_STR(OPT_MASTER_KEY_FILE_ID));
 2283         goto out;
 2284     }
 2285     log_std("Unbound Key:\t");
 2286 
 2287     for(i = 0; i < (int)uk_size; i++) {
 2288         if (i && !(i % 16))
 2289             log_std("\n\t\t");
 2290         log_std("%02hhx ", (char)uk[i]);
 2291     }
 2292     log_std("\n");
 2293 out:
 2294     crypt_safe_free(password);
 2295     crypt_safe_free(uk);
 2296     return r;
 2297 }
 2298 
 2299 static int action_luksDump(void)
 2300 {
 2301     struct crypt_device *cd = NULL;
 2302     int r;
 2303 
 2304     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 2305         goto out;
 2306 
 2307     if ((r = crypt_load(cd, luksType(device_type), NULL))) {
 2308         log_err(_("Device %s is not a valid LUKS device."),
 2309             uuid_or_device_header(NULL));
 2310         goto out;
 2311     }
 2312 
 2313     if (ARG_SET(OPT_DUMP_MASTER_KEY_ID))
 2314         r = luksDump_with_volume_key(cd);
 2315     else if (ARG_SET(OPT_UNBOUND_ID))
 2316         r = luksDump_with_unbound_key(cd);
 2317     else if (ARG_SET(OPT_DUMP_JSON_ID))
 2318         r = crypt_dump_json(cd, NULL, 0);
 2319     else
 2320         r = crypt_dump(cd);
 2321 out:
 2322     crypt_free(cd);
 2323     return r;
 2324 }
 2325 
 2326 static int action_luksSuspend(void)
 2327 {
 2328     struct crypt_device *cd = NULL;
 2329     int r;
 2330 
 2331     r = crypt_init_by_name_and_header(&cd, action_argv[0], uuid_or_device(ARG_STR(OPT_HEADER_ID)));
 2332     if (!r) {
 2333         r = crypt_suspend(cd, action_argv[0]);
 2334         if (r == -ENODEV)
 2335             log_err(_("%s is not active %s device name."), action_argv[0], "LUKS");
 2336     }
 2337 
 2338     crypt_free(cd);
 2339     return r;
 2340 }
 2341 
 2342 static int action_luksResume(void)
 2343 {
 2344     struct crypt_device *cd = NULL;
 2345     char *password = NULL;
 2346     size_t passwordLen;
 2347     int r, tries;
 2348     const char *req_type = luksType(device_type);
 2349 
 2350     if (req_type && !isLUKS(req_type))
 2351         return -EINVAL;
 2352 
 2353     if ((r = crypt_init_by_name_and_header(&cd, action_argv[0], uuid_or_device(ARG_STR(OPT_HEADER_ID)))))
 2354         return r;
 2355 
 2356     r = -EINVAL;
 2357     if (!isLUKS(crypt_get_type(cd))) {
 2358         log_err(_("%s is not active LUKS device name or header is missing."), action_argv[0]);
 2359         goto out;
 2360     }
 2361 
 2362     if (req_type && strcmp(req_type, crypt_get_type(cd))) {
 2363         log_err(_("%s is not active %s device name."), action_argv[0], req_type);
 2364         goto out;
 2365     }
 2366 
 2367     tries = _set_tries_tty();
 2368     do {
 2369         r = tools_get_key(NULL, &password, &passwordLen,
 2370             ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 2371             ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(0), 0, cd);
 2372         if (r < 0)
 2373             goto out;
 2374 
 2375         r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
 2376                            password, passwordLen);
 2377         tools_passphrase_msg(r);
 2378         check_signal(&r);
 2379         tools_keyslot_msg(r, UNLOCKED);
 2380 
 2381         crypt_safe_free(password);
 2382         password = NULL;
 2383     } while ((r == -EPERM || r == -ERANGE) && (--tries > 0));
 2384 out:
 2385     crypt_safe_free(password);
 2386     crypt_free(cd);
 2387     return r;
 2388 }
 2389 
 2390 static int action_luksBackup(void)
 2391 {
 2392     struct crypt_device *cd = NULL;
 2393     int r;
 2394 
 2395     if (!ARG_SET(OPT_HEADER_BACKUP_FILE_ID)) {
 2396         log_err(_("Option --header-backup-file is required."));
 2397         return -EINVAL;
 2398     }
 2399 
 2400     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 2401         goto out;
 2402 
 2403     r = crypt_header_backup(cd, NULL, ARG_STR(OPT_HEADER_BACKUP_FILE_ID));
 2404 out:
 2405     crypt_free(cd);
 2406     return r;
 2407 }
 2408 
 2409 static int action_luksRestore(void)
 2410 {
 2411     struct crypt_device *cd = NULL;
 2412     int r = 0;
 2413 
 2414     if (!ARG_SET(OPT_HEADER_BACKUP_FILE_ID)) {
 2415         log_err(_("Option --header-backup-file is required."));
 2416         return -EINVAL;
 2417     }
 2418 
 2419     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 2420         goto out;
 2421 
 2422     if (!ARG_SET(OPT_BATCH_MODE_ID))
 2423         crypt_set_confirm_callback(cd, yesDialog, NULL);
 2424     r = crypt_header_restore(cd, NULL, ARG_STR(OPT_HEADER_BACKUP_FILE_ID));
 2425 out:
 2426     crypt_free(cd);
 2427     return r;
 2428 }
 2429 
 2430 static const char *_get_device_type(void)
 2431 {
 2432     const char *type, *name = NULL;
 2433     struct crypt_device *cd = NULL;
 2434 
 2435     if (action_argc > 1)
 2436         name = action_argv[1];
 2437     else if (action_argc == 1)
 2438         name = action_argv[0];
 2439 
 2440     if (crypt_init_by_name_and_header(&cd, name, ARG_STR(OPT_HEADER_ID)))
 2441         return NULL;
 2442 
 2443     type = crypt_get_type(cd);
 2444     if (!type) {
 2445         crypt_free(cd);
 2446         log_err(_("%s is not cryptsetup managed device."), name);
 2447         return NULL;
 2448     }
 2449 
 2450     if (!strncmp(type, "LUKS", 4))
 2451         type = "luks";
 2452     else if (!strcmp(type, CRYPT_PLAIN))
 2453         type = "plain";
 2454     else if (!strcmp(type, CRYPT_LOOPAES))
 2455         type = "loopaes";
 2456     else {
 2457         log_err(_("Refresh is not supported for device type %s"), type);
 2458         type = NULL;
 2459     }
 2460 
 2461     crypt_free(cd);
 2462 
 2463     return type;
 2464 }
 2465 
 2466 static int action_open(void)
 2467 {
 2468     int r = -EINVAL;
 2469 
 2470     if (ARG_SET(OPT_REFRESH_ID) && !device_type)
 2471         /* read device type from active mapping */
 2472         device_type = _get_device_type();
 2473 
 2474     if (!device_type)
 2475         return -EINVAL;
 2476 
 2477     if (!strcmp(device_type, "luks") ||
 2478         !strcmp(device_type, "luks1") ||
 2479         !strcmp(device_type, "luks2")) {
 2480         if (action_argc < 2 && (!ARG_SET(OPT_TEST_PASSPHRASE_ID) && !ARG_SET(OPT_REFRESH_ID)))
 2481             goto out;
 2482         return action_open_luks();
 2483     } else if (!strcmp(device_type, "plain")) {
 2484         if (action_argc < 2 && !ARG_SET(OPT_REFRESH_ID))
 2485             goto out;
 2486         return action_open_plain();
 2487     } else if (!strcmp(device_type, "loopaes")) {
 2488         if (action_argc < 2 && !ARG_SET(OPT_REFRESH_ID))
 2489             goto out;
 2490         return action_open_loopaes();
 2491     } else if (!strcmp(device_type, "tcrypt")) {
 2492         if (action_argc < 2 && !ARG_SET(OPT_TEST_PASSPHRASE_ID))
 2493             goto out;
 2494         return action_open_tcrypt();
 2495     } else if (!strcmp(device_type, "bitlk")) {
 2496         if (action_argc < 2 && !ARG_SET(OPT_TEST_PASSPHRASE_ID))
 2497             goto out;
 2498         return action_open_bitlk();
 2499     } else
 2500         r = -ENOENT;
 2501 out:
 2502     if (r == -ENOENT)
 2503         log_err(_("Unrecognized metadata device type %s."), device_type);
 2504     else
 2505         log_err(_("Command requires device and mapped name as arguments."));
 2506 
 2507     return r;
 2508 }
 2509 
 2510 static int action_luksErase(void)
 2511 {
 2512     struct crypt_device *cd = NULL;
 2513     crypt_keyslot_info ki;
 2514     char *msg = NULL;
 2515     int i, max, r;
 2516 
 2517     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 2518         goto out;
 2519 
 2520     if ((r = crypt_load(cd, luksType(device_type), NULL))) {
 2521         log_err(_("Device %s is not a valid LUKS device."),
 2522             uuid_or_device_header(NULL));
 2523         goto out;
 2524     }
 2525 
 2526     if(asprintf(&msg, _("This operation will erase all keyslots on device %s.\n"
 2527                 "Device will become unusable after this operation."),
 2528                 uuid_or_device_header(NULL)) == -1) {
 2529         r = -ENOMEM;
 2530         goto out;
 2531     }
 2532 
 2533     if (!ARG_SET(OPT_BATCH_MODE_ID) && !yesDialog(msg, _("Operation aborted, keyslots were NOT wiped.\n"))) {
 2534         r = -EPERM;
 2535         goto out;
 2536     }
 2537 
 2538     /* Safety check */
 2539     max = crypt_keyslot_max(crypt_get_type(cd));
 2540     if (max <= 0) {
 2541         r = -EINVAL;
 2542         goto out;
 2543     }
 2544 
 2545     for (i = 0; i < max; i++) {
 2546         ki = crypt_keyslot_status(cd, i);
 2547         if (ki == CRYPT_SLOT_ACTIVE || ki == CRYPT_SLOT_ACTIVE_LAST) {
 2548             r = crypt_keyslot_destroy(cd, i);
 2549             if (r < 0)
 2550                 goto out;
 2551             tools_keyslot_msg(i, REMOVED);
 2552         }
 2553     }
 2554 out:
 2555     free(msg);
 2556     crypt_free(cd);
 2557     return r;
 2558 }
 2559 
 2560 static int action_luksConvert(void)
 2561 {
 2562     struct crypt_device *cd = NULL;
 2563     char *msg = NULL;
 2564     const char *to_type, *from_type;
 2565     int r;
 2566 
 2567     if (!strcmp(device_type, "luks2")) {
 2568         to_type = CRYPT_LUKS2;
 2569     } else if (!strcmp(device_type, "luks1")) {
 2570         to_type = CRYPT_LUKS1;
 2571     } else {
 2572         log_err(_("Invalid LUKS type, only luks1 and luks2 are supported."));
 2573         return -EINVAL;
 2574     }
 2575 
 2576     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 2577         return r;
 2578 
 2579     if ((r = crypt_load(cd, CRYPT_LUKS, NULL)) ||
 2580         !(from_type = crypt_get_type(cd))) {
 2581         log_err(_("Device %s is not a valid LUKS device."),
 2582             uuid_or_device_header(NULL));
 2583         crypt_free(cd);
 2584         return r;
 2585     }
 2586 
 2587     if (!strcmp(from_type, to_type)) {
 2588         log_err(_("Device is already %s type."), to_type);
 2589         crypt_free(cd);
 2590         return -EINVAL;
 2591     }
 2592 
 2593     r = 0;
 2594     if (!ARG_SET(OPT_BATCH_MODE_ID)) {
 2595         if (asprintf(&msg, _("This operation will convert %s to %s format.\n"),
 2596                     uuid_or_device_header(NULL), to_type) == -1)
 2597             r = -ENOMEM;
 2598         else if (!yesDialog(msg, _("Operation aborted, device was NOT converted.\n")))
 2599             r = -EPERM;
 2600     }
 2601 
 2602     r = r ?: crypt_convert(cd, to_type, NULL);
 2603 
 2604     free(msg);
 2605     crypt_free(cd);
 2606     return r;
 2607 }
 2608 
 2609 static int _config_priority(struct crypt_device *cd)
 2610 {
 2611     crypt_keyslot_info cs;
 2612     crypt_keyslot_priority priority = CRYPT_SLOT_PRIORITY_INVALID;
 2613 
 2614     if (!strcmp("normal", ARG_STR(OPT_PRIORITY_ID)))
 2615         priority = CRYPT_SLOT_PRIORITY_NORMAL;
 2616     else if (!strcmp("prefer", ARG_STR(OPT_PRIORITY_ID)))
 2617         priority = CRYPT_SLOT_PRIORITY_PREFER;
 2618     else if (!strcmp("ignore", ARG_STR(OPT_PRIORITY_ID)))
 2619         priority = CRYPT_SLOT_PRIORITY_IGNORE;
 2620 
 2621     cs = crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID));
 2622     if (cs != CRYPT_SLOT_INVALID)
 2623         return crypt_keyslot_set_priority(cd, ARG_INT32(OPT_KEY_SLOT_ID), priority);
 2624     return -EINVAL;
 2625 }
 2626 
 2627 static int _config_labels(struct crypt_device *cd)
 2628 {
 2629     return crypt_set_label(cd, ARG_STR(OPT_LABEL_ID), ARG_STR(OPT_SUBSYSTEM_ID));
 2630 }
 2631 
 2632 static int action_luksConfig(void)
 2633 {
 2634     struct crypt_device *cd = NULL;
 2635     int r;
 2636 
 2637     if (!ARG_SET(OPT_PRIORITY_ID) && !ARG_SET(OPT_LABEL_ID) && !ARG_SET(OPT_SUBSYSTEM_ID)) {
 2638         log_err(_("Option --priority, --label or --subsystem is missing."));
 2639         return -EINVAL;
 2640     }
 2641 
 2642     if ((r = crypt_init(&cd, uuid_or_device_header(NULL))))
 2643         return r;
 2644 
 2645     if ((r = crypt_load(cd, CRYPT_LUKS2, NULL))) {
 2646         log_err(_("Device %s is not a valid LUKS device."),
 2647             uuid_or_device_header(NULL));
 2648         goto out;
 2649     }
 2650 
 2651     if (ARG_SET(OPT_PRIORITY_ID) && (r = _config_priority(cd)))
 2652         goto out;
 2653 
 2654     if ((ARG_SET(OPT_LABEL_ID) || ARG_SET(OPT_SUBSYSTEM_ID)) && (r = _config_labels(cd)))
 2655         goto out;
 2656 out:
 2657     crypt_free(cd);
 2658     return r;
 2659 }
 2660 
 2661 static int _token_add(struct crypt_device *cd)
 2662 {
 2663     int r, token;
 2664     crypt_token_info token_info;
 2665     const struct crypt_token_params_luks2_keyring params = {
 2666         .key_description = ARG_STR(OPT_KEY_DESCRIPTION_ID)
 2667     };
 2668 
 2669     if (ARG_INT32(OPT_TOKEN_ID_ID) != CRYPT_ANY_TOKEN) {
 2670         token_info = crypt_token_status(cd, ARG_INT32(OPT_TOKEN_ID_ID), NULL);
 2671         if (token_info < CRYPT_TOKEN_INACTIVE) {
 2672             log_err(_("Token %d is invalid."), ARG_INT32(OPT_TOKEN_ID_ID));
 2673             return -EINVAL;
 2674         } else if (token_info > CRYPT_TOKEN_INACTIVE) {
 2675             log_err(_("Token %d in use."), ARG_INT32(OPT_TOKEN_ID_ID));
 2676             return -EINVAL;
 2677         }
 2678     }
 2679 
 2680     if (crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)) == CRYPT_SLOT_INACTIVE) {
 2681         log_err(_("Keyslot %d is not active."), ARG_INT32(OPT_KEY_SLOT_ID));
 2682         return -EINVAL;
 2683     }
 2684 
 2685     r = crypt_token_luks2_keyring_set(cd, ARG_INT32(OPT_TOKEN_ID_ID), &params);
 2686     if (r < 0) {
 2687         log_err(_("Failed to add luks2-keyring token %d."), ARG_INT32(OPT_TOKEN_ID_ID));
 2688         return r;
 2689     }
 2690 
 2691     token = r;
 2692 
 2693     r = crypt_token_assign_keyslot(cd, token, ARG_INT32(OPT_KEY_SLOT_ID));
 2694     if (r < 0) {
 2695         log_err(_("Failed to assign token %d to keyslot %d."), token, ARG_INT32(OPT_KEY_SLOT_ID));
 2696         (void) crypt_token_json_set(cd, token, NULL);
 2697         return r;
 2698     }
 2699 
 2700     return token;
 2701 }
 2702 
 2703 static int _token_remove(struct crypt_device *cd)
 2704 {
 2705     crypt_token_info token_info;
 2706 
 2707     token_info = crypt_token_status(cd, ARG_INT32(OPT_TOKEN_ID_ID), NULL);
 2708     if (token_info < CRYPT_TOKEN_INACTIVE) {
 2709         log_err(_("Token %d is invalid."), ARG_INT32(OPT_TOKEN_ID_ID));
 2710         return -EINVAL;
 2711     } else if (token_info == CRYPT_TOKEN_INACTIVE) {
 2712         log_err(_("Token %d is not in use."), ARG_INT32(OPT_TOKEN_ID_ID));
 2713         return -EINVAL;
 2714     }
 2715 
 2716     return crypt_token_json_set(cd, ARG_INT32(OPT_TOKEN_ID_ID), NULL);
 2717 }
 2718 
 2719 static int _token_import(struct crypt_device *cd)
 2720 {
 2721     char *json;
 2722     size_t json_length;
 2723     crypt_token_info token_info;
 2724     int r, token;
 2725 
 2726     if (ARG_INT32(OPT_TOKEN_ID_ID) != CRYPT_ANY_TOKEN) {
 2727         token_info = crypt_token_status(cd, ARG_INT32(OPT_TOKEN_ID_ID), NULL);
 2728         if (token_info < CRYPT_TOKEN_INACTIVE) {
 2729             log_err(_("Token %d is invalid."), ARG_INT32(OPT_TOKEN_ID_ID));
 2730             return -EINVAL;
 2731         } else if (token_info > CRYPT_TOKEN_INACTIVE) {
 2732             log_err(_("Token %d in use."), ARG_INT32(OPT_TOKEN_ID_ID));
 2733             return -EINVAL;
 2734         }
 2735     }
 2736 
 2737     if (crypt_keyslot_status(cd, ARG_INT32(OPT_KEY_SLOT_ID)) == CRYPT_SLOT_INACTIVE) {
 2738         log_err(_("Keyslot %d is not active."), ARG_INT32(OPT_KEY_SLOT_ID));
 2739         return -EINVAL;
 2740     }
 2741 
 2742     r = tools_read_json_file(ARG_STR(OPT_JSON_FILE_ID), &json, &json_length, ARG_SET(OPT_BATCH_MODE_ID));
 2743     if (r)
 2744         return r;
 2745 
 2746     r = crypt_token_json_set(cd, ARG_INT32(OPT_TOKEN_ID_ID), json);
 2747     free(json);
 2748     if (r < 0) {
 2749         log_err(_("Failed to import token from file."));
 2750         return r;
 2751     }
 2752 
 2753     token = r;
 2754 
 2755     if (ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT) {
 2756         r = crypt_token_assign_keyslot(cd, token, ARG_INT32(OPT_KEY_SLOT_ID));
 2757         if (r < 0) {
 2758             log_err(_("Failed to assign token %d to keyslot %d."), token, ARG_INT32(OPT_KEY_SLOT_ID));
 2759             (void) crypt_token_json_set(cd, token, NULL);
 2760             return r;
 2761         }
 2762     }
 2763 
 2764     return token;
 2765 }
 2766 
 2767 static int _token_export(struct crypt_device *cd)
 2768 {
 2769     const char *json;
 2770     int r;
 2771 
 2772     r = crypt_token_json_get(cd, ARG_INT32(OPT_TOKEN_ID_ID), &json);
 2773     if (r < 0) {
 2774         log_err(_("Failed to get token %d for export."), ARG_INT32(OPT_TOKEN_ID_ID));
 2775         return r;
 2776     }
 2777 
 2778     return tools_write_json_file(ARG_STR(OPT_JSON_FILE_ID), json);
 2779 }
 2780 
 2781 static int action_token(void)
 2782 {
 2783     int r;
 2784     struct crypt_device *cd = NULL;
 2785 
 2786     if ((r = crypt_init(&cd, uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[1]))))
 2787         return r;
 2788 
 2789     if ((r = crypt_load(cd, CRYPT_LUKS2, NULL))) {
 2790         log_err(_("Device %s is not a valid LUKS device."),
 2791             uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[1]));
 2792         crypt_free(cd);
 2793         return r;
 2794     }
 2795 
 2796     r = -EINVAL;
 2797 
 2798     if (!strcmp(action_argv[0], "add")) {
 2799         r = _token_add(cd); /* adds only luks2-keyring type */
 2800         tools_token_msg(r, CREATED);
 2801     } else if (!strcmp(action_argv[0], "remove")) {
 2802         r = _token_remove(cd);
 2803         tools_token_msg(r, REMOVED);
 2804     } else if (!strcmp(action_argv[0], "import")) {
 2805         r = _token_import(cd);
 2806         tools_token_msg(r, CREATED);
 2807     } else if (!strcmp(action_argv[0], "export"))
 2808         r = _token_export(cd);
 2809 
 2810     crypt_free(cd);
 2811 
 2812     return r;
 2813 }
 2814 
 2815 static int auto_detect_active_name(struct crypt_device *cd, const char *data_device, char *dm_name, size_t dm_name_len)
 2816 {
 2817     int r;
 2818 
 2819     r = tools_lookup_crypt_device(cd, crypt_get_type(cd), data_device, dm_name, dm_name_len);
 2820     if (r > 0)
 2821         log_dbg("Device %s has %d active holders.", data_device, r);
 2822 
 2823     return r;
 2824 }
 2825 
 2826 static int _get_device_active_name(struct crypt_device *cd, const char *data_device, char *buffer, size_t buffer_size)
 2827 {
 2828     char *msg;
 2829     int r;
 2830 
 2831     r = auto_detect_active_name(cd, action_argv[0], buffer, buffer_size);
 2832     if (r > 0) {
 2833         if (*buffer == '\0') {
 2834             log_err(_("Device %s is still in use."), data_device);
 2835             return -EINVAL;
 2836         }
 2837         if (!ARG_SET(OPT_BATCH_MODE_ID))
 2838             log_std(_("Auto-detected active dm device '%s' for data device %s.\n"), buffer, data_device);
 2839     }
 2840     if (r < 0) {
 2841         if (r == -ENOTBLK)
 2842             log_std(_("Device %s is not a block device.\n"), data_device);
 2843         else
 2844             log_err(_("Failed to auto-detect device %s holders."), data_device);
 2845 
 2846         r = -EINVAL;
 2847         if (!ARG_SET(OPT_BATCH_MODE_ID)) {
 2848             r = asprintf(&msg, _("Unable to decide if device %s is activated or not.\n"
 2849                          "Are you sure you want to proceed with reencryption in offline mode?\n"
 2850                          "It may lead to data corruption if the device is actually activated.\n"
 2851                          "To run reencryption in online mode, use --active-name parameter instead.\n"), data_device);
 2852             if (r < 0)
 2853                 return -ENOMEM;
 2854             r = noDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
 2855             free(msg);
 2856         }
 2857     }
 2858 
 2859     return r;
 2860 }
 2861 
 2862 static int action_reencrypt_load(struct crypt_device *cd)
 2863 {
 2864     int r;
 2865     size_t passwordLen;
 2866     char dm_name[PATH_MAX] = {}, *password = NULL;
 2867     const char *active_name = NULL;
 2868     struct crypt_params_reencrypt params = {
 2869         .resilience = ARG_STR(OPT_RESILIENCE_ID) ?: "checksum",
 2870         .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
 2871         .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
 2872         .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
 2873         .flags = CRYPT_REENCRYPT_RESUME_ONLY
 2874     };
 2875 
 2876     r = tools_get_key(NULL, &password, &passwordLen,
 2877             ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 2878             ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(0), 0, cd);
 2879     if (r < 0)
 2880         return r;
 2881 
 2882     if (!ARG_SET(OPT_ACTIVE_NAME_ID)) {
 2883         r = _get_device_active_name(cd, action_argv[0], dm_name, sizeof(dm_name));
 2884         if (r > 0)
 2885             active_name = dm_name;
 2886         if (r < 0) {
 2887             crypt_safe_free(password);
 2888             return -EINVAL;
 2889         }
 2890     } else
 2891         active_name = ARG_STR(OPT_ACTIVE_NAME_ID);
 2892 
 2893     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, &params);
 2894 
 2895     crypt_safe_free(password);
 2896 
 2897     return r;
 2898 }
 2899 
 2900 static int action_encrypt_luks2(struct crypt_device **cd)
 2901 {
 2902     char *tmp;
 2903     const char *type, *activated_name = NULL;
 2904     int keyslot, r, fd;
 2905     uuid_t uuid;
 2906     size_t passwordLen;
 2907     char *msg, uuid_str[37], header_file[PATH_MAX] = { 0 }, *password = NULL;
 2908     uint32_t activate_flags = 0;
 2909     const struct crypt_params_luks2 luks2_params = {
 2910         .sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID) ?: SECTOR_SIZE
 2911     };
 2912     struct crypt_params_reencrypt params = {
 2913         .mode = CRYPT_REENCRYPT_ENCRYPT,
 2914         .direction = data_shift < 0 ? CRYPT_REENCRYPT_BACKWARD : CRYPT_REENCRYPT_FORWARD,
 2915         .resilience = ARG_STR(OPT_RESILIENCE_ID) ?: "checksum",
 2916         .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
 2917         .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
 2918         .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
 2919         .luks2 = &luks2_params,
 2920         .flags = CRYPT_REENCRYPT_INITIALIZE_ONLY
 2921     };
 2922 
 2923     _set_reencryption_flags(&params.flags);
 2924 
 2925     type = luksType(device_type);
 2926     if (!type)
 2927         type = crypt_get_default_type();
 2928 
 2929     if (!isLUKS2(type)) {
 2930         log_err(_("Encryption is supported only for LUKS2 format."));
 2931         return -EINVAL;
 2932     }
 2933 
 2934     if (!data_shift && !ARG_SET(OPT_HEADER_ID)) {
 2935         log_err(_("Encryption without detached header (--header) is not possible without data device size reduction (--reduce-device-size)."));
 2936         return -ENOTSUP;
 2937     }
 2938 
 2939     if (!ARG_SET(OPT_HEADER_ID) && ARG_UINT64(OPT_OFFSET_ID) && data_shift && (ARG_UINT64(OPT_OFFSET_ID) > (imaxabs(data_shift) / (2 * SECTOR_SIZE)))) {
 2940         log_err(_("Requested data offset must be less than or equal to half of --reduce-device-size parameter."));
 2941         return -EINVAL;
 2942     }
 2943 
 2944     /* TODO: ask user to confirm. It's useless to do data device reduction and than use smaller value */
 2945     if (!ARG_SET(OPT_HEADER_ID) && ARG_UINT64(OPT_OFFSET_ID) && data_shift && (ARG_UINT64(OPT_OFFSET_ID) < (imaxabs(data_shift) / (2 * SECTOR_SIZE)))) {
 2946         data_shift = -(ARG_UINT64(OPT_OFFSET_ID) * 2 * SECTOR_SIZE);
 2947         if (data_shift >= 0)
 2948             return -EINVAL;
 2949         log_std(_("Adjusting --reduce-device-size value to twice the --offset %" PRIu64 " (sectors).\n"), ARG_UINT64(OPT_OFFSET_ID) * 2);
 2950     }
 2951 
 2952     if (ARG_SET(OPT_UUID_ID) && uuid_parse(ARG_STR(OPT_UUID_ID), uuid) == -1) {
 2953         log_err(_("Wrong LUKS UUID format provided."));
 2954         return -EINVAL;
 2955     }
 2956 
 2957     if (!ARG_SET(OPT_UUID_ID)) {
 2958         uuid_generate(uuid);
 2959         uuid_unparse(uuid, uuid_str);
 2960         if (!(tmp = strdup(uuid_str)))
 2961             return -ENOMEM;
 2962         ARG_SET_STR(OPT_UUID_ID, tmp);
 2963     }
 2964 
 2965     /* Check the data device is not LUKS device already */
 2966     if ((r = crypt_init(cd, action_argv[0])))
 2967         return r;
 2968     r = crypt_load(*cd, CRYPT_LUKS, NULL);
 2969     crypt_free(*cd);
 2970     *cd = NULL;
 2971     if (!r && !ARG_SET(OPT_BATCH_MODE_ID)) {
 2972         r = asprintf(&msg, _("Detected LUKS device on %s. Do you want to encrypt that LUKS device again?"), action_argv[0]);
 2973         if (r == -1)
 2974             return -ENOMEM;
 2975 
 2976         r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
 2977         free(msg);
 2978         if (r < 0)
 2979             return r;
 2980     }
 2981 
 2982     if (!ARG_SET(OPT_HEADER_ID)) {
 2983         r = snprintf(header_file, sizeof(header_file), "LUKS2-temp-%s.new", ARG_STR(OPT_UUID_ID));
 2984         if (r < 0 || (size_t)r >= sizeof(header_file))
 2985             return -EINVAL;
 2986 
 2987         fd = open(header_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR);
 2988         if (fd == -1) {
 2989             if (errno == EEXIST)
 2990                 log_err(_("Temporary header file %s already exists. Aborting."), header_file);
 2991             else
 2992                 log_err(_("Cannot create temporary header file %s."), header_file);
 2993             return -EINVAL;
 2994         }
 2995 
 2996         r = posix_fallocate(fd, 0, 4096);
 2997         close(fd);
 2998         if (r) {
 2999             log_err(_("Cannot create temporary header file %s."), header_file);
 3000             r = -EINVAL;
 3001             goto out;
 3002         }
 3003 
 3004         if (!(tmp = strdup(header_file))) {
 3005             r = -ENOMEM;
 3006             goto out;
 3007         }
 3008         ARG_SET_STR(OPT_HEADER_ID, tmp);
 3009 
 3010         /*
 3011          * FIXME: just override offset here, but we should support both.
 3012          * offset and implicit offset via data shift (lvprepend?)
 3013          */
 3014         if (!ARG_UINT64(OPT_OFFSET_ID))
 3015             ARG_SET_UINT64(OPT_OFFSET_ID, imaxabs(data_shift) / (2 * SECTOR_SIZE));
 3016         data_shift >>= 1;
 3017         params.flags |= CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT;
 3018     } else if (data_shift < 0) {
 3019         if (!ARG_SET(OPT_LUKS2_METADATA_SIZE_ID))
 3020             ARG_SET_UINT64(OPT_LUKS2_METADATA_SIZE_ID, 0x4000); /* missing default here */
 3021         if (!ARG_SET(OPT_LUKS2_KEYSLOTS_SIZE_ID))
 3022             ARG_SET_UINT64(OPT_LUKS2_KEYSLOTS_SIZE_ID, -data_shift - 2 * ARG_UINT64(OPT_LUKS2_METADATA_SIZE_ID));
 3023         if (2 * ARG_UINT64(OPT_LUKS2_METADATA_SIZE_ID) + ARG_UINT64(OPT_LUKS2_KEYSLOTS_SIZE_ID) > (uint64_t)-data_shift) {
 3024             log_err(_("LUKS2 metadata size is larger than data shift value."));
 3025             return -EINVAL;
 3026         }
 3027     }
 3028 
 3029     r = _luksFormat(cd, &password, &passwordLen);
 3030     if (r < 0)
 3031         goto out;
 3032 
 3033     if (data_shift) {
 3034         params.data_shift = imaxabs(data_shift) / SECTOR_SIZE,
 3035         params.resilience = "datashift";
 3036     }
 3037     keyslot = !ARG_SET(OPT_KEY_SLOT_ID) ? 0 : ARG_INT32(OPT_KEY_SLOT_ID);
 3038     r = crypt_reencrypt_init_by_passphrase(*cd, NULL, password, passwordLen,
 3039             CRYPT_ANY_SLOT, keyslot, crypt_get_cipher(*cd),
 3040             crypt_get_cipher_mode(*cd), &params);
 3041     if (r < 0) {
 3042         crypt_keyslot_destroy(*cd, keyslot);
 3043         goto out;
 3044     }
 3045 
 3046     /* Restore temporary header in head of data device */
 3047     if (*header_file) {
 3048         crypt_free(*cd);
 3049         *cd = NULL;
 3050 
 3051         r = crypt_init(cd, action_argv[0]);
 3052         if (!r)
 3053             r = crypt_header_restore(*cd, CRYPT_LUKS2, header_file);
 3054 
 3055         if (r) {
 3056             log_err(_("Failed to place new header at head of device %s."), action_argv[0]);
 3057             goto out;
 3058         }
 3059     }
 3060 
 3061     /* activate device */
 3062     if (action_argc > 1) {
 3063         activated_name = action_argv[1];
 3064         _set_activation_flags(&activate_flags);
 3065         r = crypt_activate_by_passphrase(*cd, activated_name, ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen, activate_flags);
 3066         if (r >= 0)
 3067             log_std(_("%s/%s is now active and ready for online encryption.\n"), crypt_get_dir(), activated_name);
 3068     }
 3069 
 3070     if (r < 0)
 3071         goto out;
 3072 
 3073     /* just load reencryption context to continue reencryption */
 3074     if (!ARG_SET(OPT_INIT_ONLY_ID)) {
 3075         params.flags &= ~CRYPT_REENCRYPT_INITIALIZE_ONLY;
 3076         r = crypt_reencrypt_init_by_passphrase(*cd, activated_name, password, passwordLen,
 3077                 CRYPT_ANY_SLOT, keyslot, NULL, NULL, &params);
 3078     }
 3079 out:
 3080     crypt_safe_free(password);
 3081     if (*header_file)
 3082         unlink(header_file);
 3083     return r;
 3084 }
 3085 
 3086 static int action_decrypt_luks2(struct crypt_device *cd)
 3087 {
 3088     int r;
 3089     char dm_name[PATH_MAX], *password = NULL;
 3090     const char *active_name = NULL;
 3091     struct crypt_params_reencrypt params = {
 3092         .mode = CRYPT_REENCRYPT_DECRYPT,
 3093         .direction = data_shift > 0 ? CRYPT_REENCRYPT_FORWARD : CRYPT_REENCRYPT_BACKWARD,
 3094         .resilience = data_shift ? "datashift" : (ARG_STR(OPT_RESILIENCE_ID) ?: "checksum"),
 3095         .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
 3096         .data_shift = imaxabs(data_shift) / SECTOR_SIZE,
 3097         .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
 3098         .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
 3099     };
 3100     size_t passwordLen;
 3101 
 3102     if (!crypt_get_metadata_device_name(cd) || crypt_header_is_detached(cd) <= 0 ||
 3103         crypt_get_data_offset(cd) > 0) {
 3104         log_err(_("LUKS2 decryption is supported with detached header device only (with data offset set to 0)."));
 3105         return -ENOTSUP;
 3106     }
 3107 
 3108     _set_reencryption_flags(&params.flags);
 3109 
 3110     r = tools_get_key(NULL, &password, &passwordLen,
 3111             ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
 3112             ARG_UINT32(OPT_TIMEOUT_ID), _verify_passphrase(0), 0, cd);
 3113     if (r < 0)
 3114         return r;
 3115 
 3116     if (!ARG_SET(OPT_ACTIVE_NAME_ID)) {
 3117         r = _get_device_active_name(cd, action_argv[0], dm_name, sizeof(dm_name));
 3118         if (r > 0)
 3119             active_name = dm_name;
 3120         if (r < 0)
 3121             goto out;
 3122     } else
 3123         active_name = ARG_STR(OPT_ACTIVE_NAME_ID);
 3124 
 3125     if (!active_name)
 3126         log_dbg("Device %s seems unused. Proceeding with offline operation.", action_argv[0]);
 3127 
 3128     r = crypt_reencrypt_init_by_passphrase(cd, active_name, password,
 3129             passwordLen, ARG_INT32(OPT_KEY_SLOT_ID), CRYPT_ANY_SLOT, NULL, NULL, &params);
 3130 out:
 3131     crypt_safe_free(password);
 3132     return r;
 3133 }
 3134 
 3135 struct keyslot_passwords {
 3136     char *password;
 3137     size_t passwordLen;
 3138     int new;
 3139 };
 3140 
 3141 static struct keyslot_passwords *init_keyslot_passwords(size_t count)
 3142 {
 3143     size_t i;
 3144     struct keyslot_passwords *tmp = calloc(count, sizeof(struct keyslot_passwords));
 3145 
 3146     if (!tmp)
 3147         return tmp;
 3148 
 3149     for (i = 0; i < count; i++)
 3150         tmp[i].new = -1;
 3151 
 3152     return tmp;
 3153 }
 3154 
 3155 static int init_passphrase(struct keyslot_passwords *kp, size_t keyslot_passwords_length,
 3156                struct crypt_device *cd, const char *msg, int slot_to_check)
 3157 {
 3158     crypt_keyslot_info ki;
 3159     char *password;
 3160     int r = -EINVAL, retry_count;
 3161     size_t passwordLen;
 3162 
 3163     if (slot_to_check != CRYPT_ANY_SLOT) {
 3164         ki = crypt_keyslot_status(cd, slot_to_check);
 3165         if (ki < CRYPT_SLOT_ACTIVE || ki == CRYPT_SLOT_UNBOUND)
 3166             return -ENOENT;
 3167     }
 3168 
 3169     retry_count = _set_tries_tty();
 3170 
 3171     while (retry_count--) {
 3172         r = tools_get_key(msg,  &password, &passwordLen, 0, 0,
 3173                   ARG_STR(OPT_KEY_FILE_ID), 0, 0, 0 /*pwquality*/, cd);
 3174         if (r < 0)
 3175             return r;
 3176         if (quit) {
 3177             crypt_safe_free(password);
 3178             password = NULL;
 3179             passwordLen = 0;
 3180             return -EAGAIN;
 3181         }
 3182 
 3183         r = crypt_activate_by_passphrase(cd, NULL, slot_to_check,
 3184                          password, passwordLen, 0);
 3185         if (r < 0) {
 3186             crypt_safe_free(password);
 3187             password = NULL;
 3188             passwordLen = 0;
 3189         }
 3190         if (r < 0 && r != -EPERM)
 3191             return r;
 3192 
 3193         if (r >= 0) {
 3194             tools_keyslot_msg(r, UNLOCKED);
 3195             if ((size_t)r >= keyslot_passwords_length) {
 3196                 crypt_safe_free(password);
 3197                 return -EINVAL;
 3198             }
 3199             kp[r].password = password;
 3200             kp[r].passwordLen = passwordLen;
 3201             break;
 3202         }
 3203         tools_passphrase_msg(r);
 3204     }
 3205 
 3206     password = NULL;
 3207     passwordLen = 0;
 3208 
 3209     return r;
 3210 }
 3211 
 3212 static int _check_luks2_keyslots(struct crypt_device *cd)
 3213 {
 3214     int i, max = crypt_keyslot_max(CRYPT_LUKS2), active = 0, unbound = 0;
 3215 
 3216     if (max < 0)
 3217         return max;
 3218 
 3219     for (i = 0; i < max; i++) {
 3220         switch (crypt_keyslot_status(cd, i)) {
 3221         case CRYPT_SLOT_INVALID:
 3222             return -EINVAL;
 3223         case CRYPT_SLOT_ACTIVE:
 3224             /* fall-through */
 3225         case CRYPT_SLOT_ACTIVE_LAST:
 3226             active++;
 3227             break;
 3228         case CRYPT_SLOT_UNBOUND:
 3229             unbound++;
 3230             /* fall-through */
 3231         default:
 3232             break;
 3233         }
 3234     }
 3235 
 3236     /* at least one keyslot for reencryption plus new volume key */
 3237     if (active + unbound > max - 2) {
 3238         log_err(_("Not enough free keyslots for reencryption."));
 3239         return -EINVAL;
 3240     }
 3241 
 3242     if ((ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT) &&
 3243             (2 * active + unbound > max - 1)) {
 3244         log_err(_("Not enough free keyslots for reencryption."));
 3245         return -EINVAL;
 3246     }
 3247 
 3248     return 0;
 3249 }
 3250 
 3251 static int fill_keyslot_passwords(struct crypt_device *cd,
 3252         struct keyslot_passwords *kp, size_t kp_size)
 3253 {
 3254     char msg[128];
 3255     crypt_keyslot_info ki;
 3256     int i, r = 0;
 3257 
 3258     if (ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT && ARG_SET(OPT_KEY_FILE_ID)) {
 3259         for (i = 0; (size_t)i < kp_size; i++) {
 3260             ki = crypt_keyslot_status(cd, i);
 3261             if (ki == CRYPT_SLOT_INVALID)
 3262                 return -EINVAL;
 3263             if (ki == CRYPT_SLOT_ACTIVE) {
 3264                 log_err(_("Key file can be used only with --key-slot or with "
 3265                       "exactly one key slot active."));
 3266                 return -EINVAL;
 3267             }
 3268         }
 3269     }
 3270 
 3271     if (ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT) {
 3272         for (i = 0; (size_t)i < kp_size; i++) {
 3273             if (snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %d: "), i) < 0)
 3274                 return -EINVAL;
 3275             r = init_passphrase(kp, kp_size, cd, msg, i);
 3276             if (r == -ENOENT)
 3277                 r = 0;
 3278             if (r < 0)
 3279                 break;
 3280         }
 3281     } else {
 3282         if (snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %u: "), ARG_INT32(OPT_KEY_SLOT_ID)) < 0)
 3283             return -EINVAL;
 3284         r = init_passphrase(kp, kp_size, cd, msg, ARG_INT32(OPT_KEY_SLOT_ID));
 3285     }
 3286 
 3287     return r < 0 ? r : 0;
 3288 }
 3289 
 3290 static int assign_tokens(struct crypt_device *cd, int keyslot_old, int keyslot_new)
 3291 {
 3292     int token = 0, r = crypt_token_is_assigned(cd, token, keyslot_old);
 3293 
 3294     while (r != -EINVAL) {
 3295         if (!r && (token != crypt_token_assign_keyslot(cd, token, keyslot_new)))
 3296             return -EINVAL;
 3297         token++;
 3298         r = crypt_token_is_assigned(cd, token, keyslot_old);
 3299     }
 3300 
 3301     /* we reached max token number, exit */
 3302     return 0;
 3303 }
 3304 
 3305 static int action_reencrypt_luks2(struct crypt_device *cd)
 3306 {
 3307     size_t i, vk_size, kp_size;
 3308     int r, keyslot_old = CRYPT_ANY_SLOT, keyslot_new = CRYPT_ANY_SLOT, key_size;
 3309     char dm_name[PATH_MAX], cipher [MAX_CIPHER_LEN], mode[MAX_CIPHER_LEN], *vk = NULL;
 3310     const char *active_name = NULL;
 3311     struct keyslot_passwords *kp;
 3312     struct crypt_params_luks2 luks2_params = {};
 3313     struct crypt_params_reencrypt params = {
 3314         .mode = CRYPT_REENCRYPT_REENCRYPT,
 3315         .direction = data_shift < 0 ? CRYPT_REENCRYPT_BACKWARD : CRYPT_REENCRYPT_FORWARD,
 3316         .resilience = data_shift ? "datashift" : (ARG_STR(OPT_RESILIENCE_ID) ?: "checksum"),
 3317         .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
 3318         .data_shift = imaxabs(data_shift) / SECTOR_SIZE,
 3319         .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
 3320         .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
 3321         .luks2 = &luks2_params,
 3322     };
 3323 
 3324     _set_reencryption_flags(&params.flags);
 3325 
 3326     if (!ARG_SET(OPT_CIPHER_ID) && crypt_is_cipher_null(crypt_get_cipher(cd))) {
 3327         log_std(_("Switching data encryption cipher to %s.\n"), DEFAULT_CIPHER(LUKS1));
 3328         ARG_SET_STR(OPT_CIPHER_ID, strdup(DEFAULT_CIPHER(LUKS1)));
 3329     }
 3330 
 3331     if (!ARG_SET(OPT_CIPHER_ID)) {
 3332         strncpy(cipher, crypt_get_cipher(cd), MAX_CIPHER_LEN - 1);
 3333         strncpy(mode, crypt_get_cipher_mode(cd), MAX_CIPHER_LEN - 1);
 3334         cipher[MAX_CIPHER_LEN-1] = '\0';
 3335         mode[MAX_CIPHER_LEN-1] = '\0';
 3336     } else if ((r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID), cipher, NULL, mode))) {
 3337         log_err(_("No known cipher specification pattern detected."));
 3338         return r;
 3339     }
 3340 
 3341     luks2_params.sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID) ?: (uint32_t)crypt_get_sector_size(cd);
 3342 
 3343     r = _check_luks2_keyslots(cd);
 3344     if (r)
 3345         return r;
 3346 
 3347     if (ARG_SET(OPT_KEY_SIZE_ID) || ARG_SET(OPT_CIPHER_ID))
 3348         key_size = get_adjusted_key_size(mode, DEFAULT_LUKS1_KEYBITS, 0);
 3349     else
 3350         key_size = crypt_get_volume_key_size(cd);
 3351 
 3352     if (!key_size)
 3353         return -EINVAL;
 3354     vk_size = key_size;
 3355 
 3356     r = crypt_keyslot_max(CRYPT_LUKS2);
 3357     if (r < 0)
 3358         return r;
 3359     kp_size = r;
 3360     kp = init_keyslot_passwords(kp_size);
 3361 
 3362     if (!kp)
 3363         return -ENOMEM;
 3364 
 3365     r = fill_keyslot_passwords(cd, kp, kp_size);
 3366     if (r)
 3367         goto out;
 3368 
 3369     if (ARG_SET(OPT_MASTER_KEY_FILE_ID)) {
 3370         r = tools_read_mk(ARG_STR(OPT_MASTER_KEY_FILE_ID), &vk, key_size);
 3371         if (r < 0)
 3372             goto out;
 3373     }
 3374 
 3375     r = -ENOENT;
 3376 
 3377     for (i = 0; i < kp_size; i++) {
 3378         if (kp[i].password && keyslot_new < 0) {
 3379             r = set_keyslot_params(cd, i);
 3380             if (r < 0)
 3381                 break;
 3382             r = crypt_keyslot_add_by_key(cd, CRYPT_ANY_SLOT, vk, key_size,
 3383                     kp[i].password, kp[i].passwordLen, CRYPT_VOLUME_KEY_NO_SEGMENT);
 3384             tools_keyslot_msg(r, CREATED);
 3385             if (r < 0)
 3386                 break;
 3387 
 3388             kp[i].new = r;
 3389             keyslot_new = r;
 3390             keyslot_old = i;
 3391             if (!vk) {
 3392                 /* key generated in crypt_keyslot_add_by_key() call above */
 3393                 vk = crypt_safe_alloc(key_size);
 3394                 if (!vk) {
 3395                     r = -ENOMEM;
 3396                     break;
 3397                 }
 3398                 r = crypt_volume_key_get(cd, keyslot_new, vk, &vk_size, kp[i].password, kp[i].passwordLen);
 3399                 if (r < 0)
 3400                     break;
 3401             }
 3402             r = assign_tokens(cd, i, r);
 3403             if (r < 0)
 3404                 break;
 3405         } else if (kp[i].password) {
 3406             r = set_keyslot_params(cd, i);
 3407             if (r < 0)
 3408                 break;
 3409             r = crypt_keyslot_add_by_key(cd, CRYPT_ANY_SLOT, vk, key_size,
 3410                     kp[i].password, kp[i].passwordLen, CRYPT_VOLUME_KEY_NO_SEGMENT | CRYPT_VOLUME_KEY_DIGEST_REUSE);
 3411             tools_keyslot_msg(r, CREATED);
 3412             if (r < 0)
 3413                 break;
 3414             kp[i].new = r;
 3415             r = assign_tokens(cd, i, r);
 3416             if (r < 0)
 3417                 break;
 3418         }
 3419     }
 3420 
 3421     if (r < 0)
 3422         goto out;
 3423 
 3424     if (!ARG_SET(OPT_ACTIVE_NAME_ID) && !ARG_SET(OPT_INIT_ONLY_ID)) {
 3425         r = _get_device_active_name(cd, action_argv[0], dm_name, sizeof(dm_name));
 3426         if (r > 0)
 3427             active_name = dm_name;
 3428         if (r < 0)
 3429             goto out;
 3430     } else if (ARG_SET(OPT_ACTIVE_NAME_ID))
 3431         active_name = ARG_STR(OPT_ACTIVE_NAME_ID);
 3432 
 3433     if (!active_name && !ARG_SET(OPT_INIT_ONLY_ID))
 3434         log_dbg("Device %s seems unused. Proceeding with offline operation.", action_argv[0]);
 3435 
 3436     r = crypt_reencrypt_init_by_passphrase(cd, active_name, kp[keyslot_old].password,
 3437             kp[keyslot_old].passwordLen, keyslot_old, kp[keyslot_old].new,
 3438             cipher, mode, &params);
 3439 out:
 3440     crypt_safe_free(vk);
 3441     for (i = 0; i < kp_size; i++) {
 3442         crypt_safe_free(kp[i].password);
 3443         if (r < 0 && kp[i].new >= 0 &&
 3444             crypt_reencrypt_status(cd, NULL) == CRYPT_REENCRYPT_NONE &&
 3445             crypt_keyslot_destroy(cd, kp[i].new))
 3446             log_dbg("Failed to remove keyslot %d with unbound key.", kp[i].new);
 3447     }
 3448     free(kp);
 3449     return r;
 3450 }
 3451 
 3452 static int action_reencrypt(void)
 3453 {
 3454     uint32_t flags;
 3455     struct crypt_device *cd = NULL;
 3456     struct crypt_params_integrity ip = { 0 };
 3457     int r = 0;
 3458     struct tools_progress_params prog_parms = {
 3459         .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID),
 3460         .batch_mode = ARG_SET(OPT_BATCH_MODE_ID)
 3461     };
 3462 
 3463     if (action_argc < 1 && (!ARG_SET(OPT_ACTIVE_NAME_ID) || ARG_SET(OPT_ENCRYPT_ID))) {
 3464         log_err(_("Command requires device as argument."));
 3465         return -EINVAL;
 3466     }
 3467 
 3468     if (!ARG_SET(OPT_ENCRYPT_ID) || ARG_SET(OPT_RESUME_ONLY_ID)) {
 3469         if (ARG_SET(OPT_ACTIVE_NAME_ID)) {
 3470             r = crypt_init_by_name_and_header(&cd, ARG_STR(OPT_ACTIVE_NAME_ID), ARG_STR(OPT_HEADER_ID));
 3471             if (r || !isLUKS2(crypt_get_type(cd))) {
 3472                 log_err(_("Device %s is not a valid LUKS device."), ARG_STR(OPT_ACTIVE_NAME_ID));
 3473                 r = -EINVAL;
 3474                 goto out;
 3475             }
 3476         } else {
 3477             if ((r = crypt_init_data_device(&cd, uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]), action_argv[0])))
 3478                 return r;
 3479 
 3480             if ((r = crypt_load(cd, CRYPT_LUKS, NULL))) {
 3481                 log_err(_("Device %s is not a valid LUKS device."),
 3482                     uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
 3483                 goto out;
 3484             }
 3485             if (strcmp(crypt_get_type(cd), CRYPT_LUKS2)) {
 3486                 log_err(_("Only LUKS2 format is currently supported. Please use cryptsetup-reencrypt tool for LUKS1."));
 3487                 r = -EINVAL;
 3488                 goto out;
 3489             }
 3490         }
 3491 
 3492         if (crypt_persistent_flags_get(cd, CRYPT_FLAGS_REQUIREMENTS, &flags)) {
 3493             r = -EINVAL;
 3494             goto out;
 3495         }
 3496 
 3497         if (flags & CRYPT_REQUIREMENT_OFFLINE_REENCRYPT) {
 3498             log_err(_("Legacy offline reencryption already in-progress. Use cryptsetup-reencrypt utility."));
 3499             r = -EINVAL;
 3500             goto out;
 3501         }
 3502 
 3503         if (flags & CRYPT_REQUIREMENT_ONLINE_REENCRYPT)
 3504             r = -EBUSY;
 3505 
 3506         /* raw integrity info is available since 2.0 */
 3507         if (crypt_get_integrity_info(cd, &ip) || ip.tag_size) {
 3508             log_err(_("Reencryption of device with integrity profile is not supported."));
 3509             r = -ENOTSUP;
 3510             goto out;
 3511         }
 3512     }
 3513 
 3514     if (r == -EBUSY) {
 3515         if (ARG_SET(OPT_INIT_ONLY_ID))
 3516             log_err(_("LUKS2 reencryption already initialized. Aborting operation."));
 3517         else
 3518             r = action_reencrypt_load(cd);
 3519     } else if (!r && ARG_SET(OPT_RESUME_ONLY_ID)) {
 3520         log_err(_("LUKS2 device is not in reencryption."));
 3521         r = -EINVAL;
 3522     } else if (ARG_SET(OPT_DECRYPT_ID))
 3523         r = action_decrypt_luks2(cd);
 3524     else if (ARG_SET(OPT_ENCRYPT_ID) && !ARG_SET(OPT_RESUME_ONLY_ID))
 3525         r = action_encrypt_luks2(&cd);
 3526     else
 3527         r = action_reencrypt_luks2(cd);
 3528 
 3529     if (r >= 0 && !ARG_SET(OPT_INIT_ONLY_ID)) {
 3530         set_int_handler(0);
 3531         r = crypt_reencrypt_run(cd, tools_reencrypt_progress, &prog_parms);
 3532     }
 3533 out:
 3534     crypt_free(cd);
 3535 
 3536     return r;
 3537 }
 3538 
 3539 static struct action_type {
 3540     const char *type;
 3541     int (*handler)(void);
 3542     int required_action_argc;
 3543     int required_memlock;
 3544     const char *arg_desc;
 3545     const char *desc;
 3546 } action_types[] = {
 3547     { OPEN_ACTION,      action_open,        1, 1, N_("<device> [--type <type>] [<name>]"),N_("open device as <name>") },
 3548     { CLOSE_ACTION,     action_close,       1, 1, N_("<name>"), N_("close device (remove mapping)") },
 3549     { RESIZE_ACTION,    action_resize,      1, 1, N_("<name>"), N_("resize active device") },
 3550     { STATUS_ACTION,    action_status,      1, 0, N_("<name>"), N_("show device status") },
 3551     { BENCHMARK_ACTION, action_benchmark,   0, 0, N_("[--cipher <cipher>]"), N_("benchmark cipher") },
 3552     { REPAIR_ACTION,    action_luksRepair,  1, 1, N_("<device>"), N_("try to repair on-disk metadata") },
 3553     { REENCRYPT_ACTION, action_reencrypt,   0, 0, N_("<device>"), N_("reencrypt LUKS2 device") },
 3554     { ERASE_ACTION,     action_luksErase,   1, 1, N_("<device>"), N_("erase all keyslots (remove encryption key)") },
 3555     { CONVERT_ACTION,   action_luksConvert, 1, 1, N_("<device>"), N_("convert LUKS from/to LUKS2 format") },
 3556     { CONFIG_ACTION,    action_luksConfig,  1, 1, N_("<device>"), N_("set permanent configuration options for LUKS2") },
 3557     { FORMAT_ACTION,    action_luksFormat,  1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
 3558     { ADDKEY_ACTION,    action_luksAddKey,  1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
 3559     { REMOVEKEY_ACTION, action_luksRemoveKey,   1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
 3560     { CHANGEKEY_ACTION, action_luksChangeKey,   1, 1, N_("<device> [<key file>]"), N_("changes supplied key or key file of LUKS device") },
 3561     { CONVERTKEY_ACTION,    action_luksConvertKey,  1, 1, N_("<device> [<key file>]"), N_("converts a key to new pbkdf parameters") },
 3562     { KILLKEY_ACTION,   action_luksKillSlot,    2, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
 3563     { UUID_ACTION,      action_luksUUID,    1, 0, N_("<device>"), N_("print UUID of LUKS device") },
 3564     { ISLUKS_ACTION,    action_isLuks,      1, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
 3565     { LUKSDUMP_ACTION,  action_luksDump,    1, 1, N_("<device>"), N_("dump LUKS partition information") },
 3566     { TCRYPTDUMP_ACTION,    action_tcryptDump,  1, 1, N_("<device>"), N_("dump TCRYPT device information") },
 3567     { BITLKDUMP_ACTION, action_bitlkDump,   1, 1, N_("<device>"), N_("dump BITLK device information") },
 3568     { SUSPEND_ACTION,   action_luksSuspend, 1, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen)") },
 3569     { RESUME_ACTION,    action_luksResume,  1, 1, N_("<device>"), N_("Resume suspended LUKS device") },
 3570     { HEADERBACKUP_ACTION,  action_luksBackup,  1, 1, N_("<device>"), N_("Backup LUKS device header and keyslots") },
 3571     { HEADERRESTORE_ACTION, action_luksRestore, 1, 1, N_("<device>"), N_("Restore LUKS device header and keyslots") },
 3572     { TOKEN_ACTION,     action_token,       2, 0, N_("<add|remove|import|export> <device>"), N_("Manipulate LUKS2 tokens") },
 3573     {}
 3574 };
 3575 
 3576 static void help(poptContext popt_context,
 3577          enum poptCallbackReason reason __attribute__((unused)),
 3578          struct poptOption *key,
 3579          const char *arg __attribute__((unused)),
 3580          void *data __attribute__((unused)))
 3581 {
 3582     const char *path;
 3583 
 3584     if (key->shortName == '?') {
 3585         struct action_type *action;
 3586         const struct crypt_pbkdf_type *pbkdf_luks1, *pbkdf_luks2;
 3587 
 3588         log_std("%s\n",PACKAGE_STRING);
 3589 
 3590         poptPrintHelp(popt_context, stdout, 0);
 3591 
 3592         log_std(_("\n"
 3593              "<action> is one of:\n"));
 3594 
 3595         for(action = action_types; action->type; action++)
 3596             log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
 3597 
 3598         log_std(_("\n"
 3599               "You can also use old <action> syntax aliases:\n"
 3600               "\topen: create (plainOpen), luksOpen, loopaesOpen, tcryptOpen, bitlkOpen\n"
 3601               "\tclose: remove (plainClose), luksClose, loopaesClose, tcryptClose, bitlkClose\n"));
 3602         log_std(_("\n"
 3603              "<name> is the device to create under %s\n"
 3604              "<device> is the encrypted device\n"
 3605              "<key slot> is the LUKS key slot number to modify\n"
 3606              "<key file> optional key file for the new key for luksAddKey action\n"),
 3607             crypt_get_dir());
 3608 
 3609         log_std(_("\nDefault compiled-in metadata format is %s (for luksFormat action).\n"),
 3610               crypt_get_default_type());
 3611 
 3612         path = crypt_token_external_path();
 3613         if (path) {
 3614             log_std(_("\nLUKS2 external token plugin support is %s.\n"), _("compiled-in"));
 3615             log_std(_("LUKS2 external token plugin path: %s.\n"), path);
 3616         } else
 3617             log_std(_("\nLUKS2 external token plugin support is %s.\n"), _("disabled"));
 3618 
 3619         pbkdf_luks1 = crypt_get_pbkdf_default(CRYPT_LUKS1);
 3620         pbkdf_luks2 = crypt_get_pbkdf_default(CRYPT_LUKS2);
 3621         log_std(_("\nDefault compiled-in key and passphrase parameters:\n"
 3622              "\tMaximum keyfile size: %dkB, "
 3623              "Maximum interactive passphrase length %d (characters)\n"
 3624              "Default PBKDF for LUKS1: %s, iteration time: %d (ms)\n"
 3625              "Default PBKDF for LUKS2: %s\n"
 3626              "\tIteration time: %d, Memory required: %dkB, Parallel threads: %d\n"),
 3627              DEFAULT_KEYFILE_SIZE_MAXKB, DEFAULT_PASSPHRASE_SIZE_MAX,
 3628              pbkdf_luks1->type,  pbkdf_luks1->time_ms,
 3629              pbkdf_luks2->type, pbkdf_luks2->time_ms, pbkdf_luks2->max_memory_kb,
 3630              pbkdf_luks2->parallel_threads);
 3631 
 3632         log_std(_("\nDefault compiled-in device cipher parameters:\n"
 3633              "\tloop-AES: %s, Key %d bits\n"
 3634              "\tplain: %s, Key: %d bits, Password hashing: %s\n"
 3635              "\tLUKS: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
 3636              DEFAULT_LOOPAES_CIPHER, DEFAULT_LOOPAES_KEYBITS,
 3637              DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
 3638              DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
 3639              DEFAULT_RNG);
 3640 #if defined(ENABLE_LUKS_ADJUST_XTS_KEYSIZE) && DEFAULT_LUKS1_KEYBITS != 512
 3641         log_std(_("\tLUKS: Default keysize with XTS mode (two internal keys) will be doubled.\n"));
 3642 #endif
 3643         tools_cleanup();
 3644         poptFreeContext(popt_context);
 3645         exit(EXIT_SUCCESS);
 3646     } else if (key->shortName == 'V') {
 3647         log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
 3648         tools_cleanup();
 3649         poptFreeContext(popt_context);
 3650         exit(EXIT_SUCCESS);
 3651     } else
 3652         usage(popt_context, EXIT_SUCCESS, NULL, NULL);
 3653 }
 3654 
 3655 static void help_args(struct action_type *action, poptContext popt_context)
 3656 {
 3657     char buf[128];
 3658 
 3659     snprintf(buf, sizeof(buf), _("%s: requires %s as arguments"), action->type, action->arg_desc);
 3660     usage(popt_context, EXIT_FAILURE, buf, poptGetInvocationName(popt_context));
 3661 }
 3662 
 3663 static int run_action(struct action_type *action)
 3664 {
 3665     int r;
 3666 
 3667     log_dbg("Running command %s.", action->type);
 3668 
 3669     if (action->required_memlock)
 3670         crypt_memory_lock(NULL, 1);
 3671 
 3672     set_int_handler(0);
 3673     r = action->handler();
 3674 
 3675     if (action->required_memlock)
 3676         crypt_memory_lock(NULL, 0);
 3677 
 3678     /* Some functions returns keyslot # */
 3679     if (r > 0)
 3680         r = 0;
 3681     check_signal(&r);
 3682 
 3683     show_status(r);
 3684     return translate_errno(r);
 3685 }
 3686 
 3687 static bool needs_size_conversion(unsigned arg_id)
 3688 {
 3689     return (arg_id == OPT_DEVICE_SIZE_ID || arg_id == OPT_HOTZONE_SIZE_ID ||
 3690         arg_id == OPT_LUKS2_KEYSLOTS_SIZE_ID || arg_id == OPT_LUKS2_METADATA_SIZE_ID ||
 3691         arg_id == OPT_REDUCE_DEVICE_SIZE_ID);
 3692 }
 3693 
 3694 static void check_key_slot_value(poptContext popt_context)
 3695 {
 3696     if (ARG_INT32(OPT_KEY_SLOT_ID) < 0)
 3697         usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
 3698               poptGetInvocationName(popt_context));
 3699 }
 3700 
 3701 static void basic_options_cb(poptContext popt_context,
 3702          enum poptCallbackReason reason __attribute__((unused)),
 3703          struct poptOption *key,
 3704          const char *arg,
 3705          void *data __attribute__((unused)))
 3706 {
 3707     tools_parse_arg_value(popt_context, tool_core_args[key->val].type, tool_core_args + key->val, arg, key->val, needs_size_conversion);
 3708 
 3709     /* special cases additional handling */
 3710     switch (key->val) {
 3711     case OPT_DEBUG_JSON_ID:
 3712         /* fall through */
 3713     case OPT_DEBUG_ID:
 3714         log_parms.debug = true;
 3715         /* fall through */
 3716     case OPT_VERBOSE_ID:
 3717         log_parms.verbose = true;
 3718         break;
 3719     case OPT_DEVICE_SIZE_ID:
 3720         if (ARG_UINT64(OPT_DEVICE_SIZE_ID) == 0)
 3721             usage(popt_context, EXIT_FAILURE, poptStrerror(POPT_ERROR_BADNUMBER),
 3722                   poptGetInvocationName(popt_context));
 3723         if (ARG_UINT64(OPT_DEVICE_SIZE_ID) % SECTOR_SIZE)
 3724             usage(popt_context, EXIT_FAILURE, _("Device size must be multiple of 512 bytes sector."),
 3725                   poptGetInvocationName(popt_context));
 3726         break;
 3727     case OPT_HOTZONE_SIZE_ID:
 3728         if (ARG_UINT64(OPT_HOTZONE_SIZE_ID) == 0)
 3729             usage(popt_context, EXIT_FAILURE, _("Invalid max reencryption hotzone size specification."),
 3730                   poptGetInvocationName(popt_context));
 3731         break;
 3732     case OPT_KEY_FILE_ID:
 3733         if (tools_is_stdin(ARG_STR(OPT_KEY_FILE_ID))) {
 3734             free(keyfile_stdin);
 3735             keyfile_stdin = strdup(ARG_STR(OPT_KEY_FILE_ID));
 3736         } else if (keyfiles_count < MAX_KEYFILES)
 3737             keyfiles[keyfiles_count++] = strdup(ARG_STR(OPT_KEY_FILE_ID));
 3738         total_keyfiles++;
 3739         break;
 3740     case OPT_KEY_SIZE_ID:
 3741         if (ARG_UINT32(OPT_KEY_SIZE_ID) % 8)
 3742             usage(popt_context, EXIT_FAILURE,
 3743                   _("Key size must be a multiple of 8 bits"),
 3744                   poptGetInvocationName(popt_context));
 3745         break;
 3746     case OPT_KEY_SLOT_ID:
 3747         check_key_slot_value(popt_context);
 3748         break;
 3749     case OPT_KEYSLOT_KEY_SIZE_ID:
 3750         if (ARG_UINT32(OPT_KEYSLOT_KEY_SIZE_ID) == 0)
 3751             usage(popt_context, EXIT_FAILURE, poptStrerror(POPT_ERROR_BADNUMBER),
 3752                   poptGetInvocationName(popt_context));
 3753         if (ARG_UINT32(OPT_KEYSLOT_KEY_SIZE_ID) % 8)
 3754             usage(popt_context, EXIT_FAILURE,
 3755                   _("Key size must be a multiple of 8 bits"),
 3756                   poptGetInvocationName(popt_context));
 3757         break;
 3758     case OPT_REDUCE_DEVICE_SIZE_ID:
 3759         if (ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID) > 1024 * 1024 * 1024)
 3760             usage(popt_context, EXIT_FAILURE, _("Maximum device reduce size is 1 GiB."),
 3761                   poptGetInvocationName(popt_context));
 3762         if (ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID) % SECTOR_SIZE)
 3763             usage(popt_context, EXIT_FAILURE, _("Reduce size must be multiple of 512 bytes sector."),
 3764                   poptGetInvocationName(popt_context));
 3765         data_shift = -(int64_t)ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID);
 3766         break;
 3767     case OPT_SECTOR_SIZE_ID:
 3768         if (ARG_UINT32(OPT_SECTOR_SIZE_ID) < SECTOR_SIZE ||
 3769             ARG_UINT32(OPT_SECTOR_SIZE_ID) > MAX_SECTOR_SIZE ||
 3770             (ARG_UINT32(OPT_SECTOR_SIZE_ID) & (ARG_UINT32(OPT_SECTOR_SIZE_ID) - 1)))
 3771             usage(popt_context, EXIT_FAILURE,
 3772                   _("Unsupported encryption sector size."),
 3773                   poptGetInvocationName(popt_context));
 3774         break;
 3775     case OPT_PRIORITY_ID:
 3776         if (strcmp(ARG_STR(OPT_PRIORITY_ID), "normal") &&
 3777             strcmp(ARG_STR(OPT_PRIORITY_ID), "prefer") &&
 3778             strcmp(ARG_STR(OPT_PRIORITY_ID), "ignore"))
 3779             usage(popt_context, EXIT_FAILURE,
 3780             _("Option --priority can be only ignore/normal/prefer."),
 3781             poptGetInvocationName(popt_context));
 3782         break;
 3783     }
 3784 }
 3785 
 3786 int main(int argc, const char **argv)
 3787 {
 3788     static struct poptOption popt_help_options[] = {
 3789         { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
 3790         { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
 3791         { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
 3792         { "version",'V', POPT_ARG_NONE,     NULL, 0, N_("Print package version"),  NULL },
 3793         POPT_TABLEEND
 3794     };
 3795     static struct poptOption popt_basic_options[] = {
 3796         { NULL,    '\0', POPT_ARG_CALLBACK, basic_options_cb, 0, NULL, NULL },
 3797 #define ARG(A, B, C, D, E, F, G, H) { A, B, C, NULL, A ## _ID, D, E },
 3798 #include "cryptsetup_arg_list.h"
 3799 #undef arg
 3800         POPT_TABLEEND
 3801     };
 3802     static struct poptOption popt_options[] = {
 3803         { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options,  0, N_("Help options:"), NULL },
 3804         { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_basic_options, 0, NULL, NULL },
 3805         POPT_TABLEEND
 3806     };
 3807     poptContext popt_context;
 3808     struct action_type *action;
 3809     const char *aname;
 3810     int r;
 3811 
 3812     crypt_set_log_callback(NULL, tool_log, &log_parms);
 3813 
 3814     setlocale(LC_ALL, "");
 3815     bindtextdomain(PACKAGE, LOCALEDIR);
 3816     textdomain(PACKAGE);
 3817 
 3818     popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
 3819     poptSetOtherOptionHelp(popt_context,
 3820                            _("[OPTION...] <action> <action-specific>"));
 3821 
 3822     while ((r = poptGetNextOpt(popt_context)) > 0) {}
 3823 
 3824     if (r < -1)
 3825         usage(popt_context, EXIT_FAILURE, poptStrerror(r),
 3826               poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
 3827 
 3828     if (!(aname = poptGetArg(popt_context)))
 3829         usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."),
 3830               poptGetInvocationName(popt_context));
 3831 
 3832     action_argc = 0;
 3833     action_argv = poptGetArgs(popt_context);
 3834     /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
 3835     if(!action_argv)
 3836         action_argv = null_action_argv;
 3837 
 3838     /* Count args, somewhat unnice, change? */
 3839     while(action_argv[action_argc] != NULL)
 3840         action_argc++;
 3841 
 3842     /* Handle aliases */
 3843     if (!strcmp(aname, "create")) {
 3844         /* create command had historically switched arguments */
 3845         if (action_argv[0] && action_argv[1]) {
 3846             const char *tmp = action_argv[0];
 3847             action_argv[0] = action_argv[1];
 3848             action_argv[1] = tmp;
 3849         }
 3850         aname = OPEN_ACTION;
 3851         device_type = "plain";
 3852     } else if (!strcmp(aname, "plainOpen")) {
 3853         aname = OPEN_ACTION;
 3854         device_type = "plain";
 3855     } else if (!strcmp(aname, "luksOpen")) {
 3856         aname = OPEN_ACTION;
 3857         device_type = "luks";
 3858     } else if (!strcmp(aname, "loopaesOpen")) {
 3859         aname = OPEN_ACTION;
 3860         device_type = "loopaes";
 3861     } else if (!strcmp(aname, "tcryptOpen")) {
 3862         aname = OPEN_ACTION;
 3863         device_type = "tcrypt";
 3864     } else if (!strcmp(aname, "bitlkOpen")) {
 3865         aname = OPEN_ACTION;
 3866         device_type = "bitlk";
 3867     } else if (!strcmp(aname, "tcryptDump")) {
 3868         device_type = "tcrypt";
 3869     } else if (!strcmp(aname, "bitlkDump")) {
 3870         device_type = "bitlk";
 3871     } else if (!strcmp(aname, "remove") ||
 3872            !strcmp(aname, "plainClose") ||
 3873            !strcmp(aname, "luksClose") ||
 3874            !strcmp(aname, "loopaesClose") ||
 3875            !strcmp(aname, "tcryptClose") ||
 3876            !strcmp(aname, "bitlkClose")) {
 3877         aname = CLOSE_ACTION;
 3878     } else if (!strcmp(aname, "luksErase")) {
 3879         aname = ERASE_ACTION;
 3880         device_type = "luks";
 3881     } else if (!strcmp(aname, "luksConfig")) {
 3882         aname = CONFIG_ACTION;
 3883         device_type = "luks2";
 3884     } else if (!strcmp(aname, "refresh")) {
 3885         aname = OPEN_ACTION;
 3886         ARG_SET_TRUE(OPT_REFRESH_ID);
 3887     } else if (ARG_SET(OPT_TYPE_ID))
 3888         device_type = ARG_STR(OPT_TYPE_ID);
 3889 
 3890     /* ignore user supplied type and query device type instead */
 3891     if (ARG_SET(OPT_REFRESH_ID))
 3892         device_type = NULL;
 3893 
 3894     for(action = action_types; action->type; action++)
 3895         if (strcmp(action->type, aname) == 0)
 3896             break;
 3897 
 3898     if (!action->type)
 3899         usage(popt_context, EXIT_FAILURE, _("Unknown action."),
 3900               poptGetInvocationName(popt_context));
 3901 
 3902     if (action_argc < action->required_action_argc)
 3903         help_args(action, popt_context);
 3904 
 3905     /* this routine short circuits to exit() on error */
 3906     tools_check_args(action->type, tool_core_args, ARRAY_SIZE(tool_core_args), popt_context);
 3907 
 3908     if (ARG_SET(OPT_REFRESH_ID) && ARG_SET(OPT_TEST_PASSPHRASE_ID))
 3909         usage(popt_context, EXIT_FAILURE,
 3910               _("Options --refresh and --test-passphrase are mutually exclusive."),
 3911               poptGetInvocationName(popt_context));
 3912 
 3913     if (ARG_SET(OPT_CANCEL_DEFERRED_ID) && ARG_SET(OPT_DEFERRED_ID))
 3914         usage(popt_context, EXIT_FAILURE,
 3915               _("Options --cancel-deferred and --deferred cannot be used at the same time."),
 3916               poptGetInvocationName(popt_context));
 3917 
 3918     /* open action specific check */
 3919     if (ARG_SET(OPT_SHARED_ID) && strcmp_or_null(device_type, "plain"))
 3920         usage(popt_context, EXIT_FAILURE,
 3921               _("Option --shared is allowed only for open of plain device."),
 3922               poptGetInvocationName(popt_context));
 3923 
 3924     if (ARG_SET(OPT_PERSISTENT_ID) && ARG_SET(OPT_TEST_PASSPHRASE_ID))
 3925         usage(popt_context, EXIT_FAILURE,
 3926               _("Option --persistent is not allowed with --test-passphrase."),
 3927               poptGetInvocationName(popt_context));
 3928 
 3929     if (ARG_SET(OPT_INTEGRITY_NO_WIPE_ID) && !ARG_SET(OPT_INTEGRITY_ID))
 3930         usage(popt_context, EXIT_FAILURE,
 3931               _("Option --integrity-no-wipe"
 3932                 " can be used only for format action with integrity extension."),
 3933               poptGetInvocationName(popt_context));
 3934 
 3935     if (ARG_SET(OPT_TEST_PASSPHRASE_ID) && (strcmp(aname, OPEN_ACTION) || !device_type ||
 3936         (strncmp(device_type, "luks", 4) && strcmp(device_type, "tcrypt") && strcmp(device_type, "bitlk"))))
 3937         usage(popt_context, EXIT_FAILURE,
 3938               _("Option --test-passphrase is allowed only for open of LUKS, TCRYPT and BITLK devices."),
 3939               poptGetInvocationName(popt_context));
 3940 
 3941     if (!strcmp(aname, KILLKEY_ACTION) && action_argc > 1) {
 3942         ARG_SET_INT32(OPT_KEY_SLOT_ID, atoi(action_argv[1]));
 3943         check_key_slot_value(popt_context);
 3944     }
 3945 
 3946     if ((!strcmp(aname, REMOVEKEY_ACTION) ||
 3947          !strcmp(aname, FORMAT_ACTION)) &&
 3948          action_argc > 1) {
 3949         if (ARG_SET(OPT_KEY_FILE_ID))
 3950             log_err(_("Option --key-file takes precedence over specified key file argument."));
 3951         else
 3952             ARG_SET_STR(OPT_KEY_FILE_ID, strdup(action_argv[1]));
 3953     }
 3954 
 3955     if (total_keyfiles > 1 && (strcmp_or_null(device_type, "tcrypt")))
 3956         usage(popt_context, EXIT_FAILURE, _("Only one --key-file argument is allowed."),
 3957               poptGetInvocationName(popt_context));
 3958 
 3959     if (ARG_SET(OPT_USE_RANDOM_ID) && ARG_SET(OPT_USE_URANDOM_ID))
 3960         usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
 3961               poptGetInvocationName(popt_context));
 3962 
 3963     if (ARG_SET(OPT_ALIGN_PAYLOAD_ID) && ARG_SET(OPT_OFFSET_ID))
 3964         usage(popt_context, EXIT_FAILURE, _("Options --align-payload and --offset cannot be combined."),
 3965               poptGetInvocationName(popt_context));
 3966 
 3967     /* open action specific check */
 3968     if (ARG_SET(OPT_SKIP_ID) && strcmp_or_null(device_type, "plain") && strcmp(device_type, "loopaes"))
 3969         usage(popt_context, EXIT_FAILURE,
 3970         _("Option --skip is supported only for open of plain and loopaes devices."),
 3971         poptGetInvocationName(popt_context));
 3972 
 3973     /* open action specific check */
 3974     if (ARG_SET(OPT_OFFSET_ID) && !strcmp(aname, OPEN_ACTION) && strcmp_or_null(device_type, "plain") && strcmp(device_type, "loopaes"))
 3975         usage(popt_context, EXIT_FAILURE,
 3976         _("Option --offset with open action is only supported for plain and loopaes devices."),
 3977         poptGetInvocationName(popt_context));
 3978 
 3979     /* open action specific check */
 3980     if ((ARG_SET(OPT_TCRYPT_HIDDEN_ID) || ARG_SET(OPT_TCRYPT_SYSTEM_ID) || ARG_SET(OPT_TCRYPT_BACKUP_ID)) && !strcmp(aname, OPEN_ACTION) && (!device_type || strcmp(device_type, "tcrypt")))
 3981         usage(popt_context, EXIT_FAILURE,
 3982         _("Option --tcrypt-hidden, --tcrypt-system or --tcrypt-backup is supported only for TCRYPT device."),
 3983         poptGetInvocationName(popt_context));
 3984 
 3985     if (ARG_SET(OPT_TCRYPT_HIDDEN_ID) && ARG_SET(OPT_ALLOW_DISCARDS_ID))
 3986         usage(popt_context, EXIT_FAILURE,
 3987         _("Option --tcrypt-hidden cannot be combined with --allow-discards."),
 3988         poptGetInvocationName(popt_context));
 3989 
 3990     if ((ARG_SET(OPT_VERACRYPT_ID) || ARG_SET(OPT_DISABLE_VERACRYPT_ID)) && (!device_type || strcmp(device_type, "tcrypt")))
 3991         usage(popt_context, EXIT_FAILURE,
 3992         _("Option --veracrypt or --disable-veracrypt is supported only for TCRYPT device type."),
 3993         poptGetInvocationName(popt_context));
 3994 
 3995     if (ARG_SET(OPT_VERACRYPT_PIM_ID) && ARG_SET(OPT_DISABLE_VERACRYPT_ID))
 3996         usage(popt_context, EXIT_FAILURE,
 3997         _("Option --veracrypt-pim is supported only for VeraCrypt compatible devices."),
 3998         poptGetInvocationName(popt_context));
 3999 
 4000     if (ARG_SET(OPT_VERACRYPT_QUERY_PIM_ID)) {
 4001         if (ARG_SET(OPT_DISABLE_VERACRYPT_ID)) {
 4002             usage(popt_context, EXIT_FAILURE,
 4003             _("Option --veracrypt-query-pim is supported only for VeraCrypt compatible devices."),
 4004             poptGetInvocationName(popt_context));
 4005         } else if (ARG_SET(OPT_VERACRYPT_PIM_ID)) {
 4006             usage(popt_context, EXIT_FAILURE,
 4007             _("The options --veracrypt-pim and --veracrypt-query-pim are mutually exclusive."),
 4008             poptGetInvocationName(popt_context));
 4009         }
 4010     }
 4011 
 4012     /* config action specific check */
 4013     if (!strcmp(aname, CONFIG_ACTION) && ARG_SET(OPT_PRIORITY_ID) && ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT)
 4014         usage(popt_context, EXIT_FAILURE,
 4015         _("Keyslot specification is required."),
 4016         poptGetInvocationName(popt_context));
 4017 
 4018     if (ARG_SET(OPT_PBKDF_ID) && crypt_parse_pbkdf(ARG_STR(OPT_PBKDF_ID), &set_pbkdf))
 4019         usage(popt_context, EXIT_FAILURE,
 4020         _("Password-based key derivation function (PBKDF) can be only pbkdf2 or argon2i/argon2id."),
 4021         poptGetInvocationName(popt_context));
 4022 
 4023     if (ARG_SET(OPT_PBKDF_FORCE_ITERATIONS_ID) && ARG_SET(OPT_ITER_TIME_ID))
 4024         usage(popt_context, EXIT_FAILURE,
 4025         _("PBKDF forced iterations cannot be combined with iteration time option."),
 4026         poptGetInvocationName(popt_context));
 4027 
 4028     /* open action specific check */
 4029     if (ARG_SET(OPT_SECTOR_SIZE_ID) && !strcmp(aname, OPEN_ACTION) &&
 4030         (!device_type || strcmp(device_type, "plain")))
 4031         usage(popt_context, EXIT_FAILURE,
 4032               _("Sector size option with open action is supported only for plain devices."),
 4033               poptGetInvocationName(popt_context));
 4034 
 4035     /* open action specific check */
 4036     if (ARG_SET(OPT_IV_LARGE_SECTORS_ID) && (!device_type || strcmp(device_type, "plain") ||
 4037         ARG_UINT32(OPT_SECTOR_SIZE_ID) <= SECTOR_SIZE))
 4038         usage(popt_context, EXIT_FAILURE,
 4039               _("Large IV sectors option is supported only for opening plain type device with sector size larger than 512 bytes."),
 4040               poptGetInvocationName(popt_context));
 4041 
 4042     /* luksAddKey action specific check */
 4043     if (ARG_SET(OPT_UNBOUND_ID) && !ARG_UINT32(OPT_KEY_SIZE_ID) && !strcmp(aname, ADDKEY_ACTION))
 4044         usage(popt_context, EXIT_FAILURE,
 4045               _("Key size is required with --unbound option."),
 4046               poptGetInvocationName(popt_context));
 4047 
 4048     /* luksDump action specific check */
 4049     if (ARG_SET(OPT_UNBOUND_ID) && ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT && !strcmp(aname, LUKSDUMP_ACTION))
 4050         usage(popt_context, EXIT_FAILURE,
 4051               _("Keyslot specification is required."),
 4052               poptGetInvocationName(popt_context));
 4053 
 4054     if (ARG_SET(OPT_DEBUG_ID) || ARG_SET(OPT_DEBUG_JSON_ID)) {
 4055         crypt_set_debug_level(ARG_SET(OPT_DEBUG_JSON_ID)? CRYPT_DEBUG_JSON : CRYPT_DEBUG_ALL);
 4056         dbg_version_and_cmd(argc, argv);
 4057     }
 4058 
 4059     /* reencrypt action specific check */
 4060     if (ARG_SET(OPT_DECRYPT_ID) && !ARG_SET(OPT_HEADER_ID))
 4061         usage(popt_context, EXIT_FAILURE, _("LUKS2 decryption requires option --header."),
 4062               poptGetInvocationName(popt_context));
 4063 
 4064     if (ARG_SET(OPT_REDUCE_DEVICE_SIZE_ID) && ARG_SET(OPT_DEVICE_SIZE_ID))
 4065         usage(popt_context, EXIT_FAILURE, _("Options --reduce-device-size and --data-size cannot be combined."),
 4066               poptGetInvocationName(popt_context));
 4067 
 4068     if (ARG_SET(OPT_DEVICE_SIZE_ID) && ARG_SET(OPT_SIZE_ID))
 4069         usage(popt_context, EXIT_FAILURE, _("Options --device-size and --size cannot be combined."),
 4070               poptGetInvocationName(popt_context));
 4071 
 4072     if (ARG_SET(OPT_KEYSLOT_CIPHER_ID) != ARG_SET(OPT_KEYSLOT_KEY_SIZE_ID))
 4073         usage(popt_context, EXIT_FAILURE, _("Options --keyslot-cipher and --keyslot-key-size must be used together."),
 4074               poptGetInvocationName(popt_context));
 4075 
 4076     if (ARG_SET(OPT_TEST_ARGS_ID)) {
 4077         log_std(_("No action taken. Invoked with --test-args option.\n"));
 4078         tools_cleanup();
 4079         poptFreeContext(popt_context);
 4080         return 0;
 4081     }
 4082 
 4083     /* token action specific check */
 4084     if (!strcmp(aname, TOKEN_ACTION)) {
 4085         if (strcmp(action_argv[0], "add") &&
 4086             strcmp(action_argv[0], "remove") &&
 4087             strcmp(action_argv[0], "import") &&
 4088             strcmp(action_argv[0], "export"))
 4089             usage(popt_context, EXIT_FAILURE, _("Invalid token action."),
 4090                   poptGetInvocationName(popt_context));
 4091 
 4092         if (!ARG_SET(OPT_KEY_DESCRIPTION_ID) && !strcmp(action_argv[0], "add"))
 4093             usage(popt_context, EXIT_FAILURE,
 4094                   _("--key-description parameter is mandatory for token add action."),
 4095                   poptGetInvocationName(popt_context));
 4096 
 4097         if (ARG_INT32(OPT_TOKEN_ID_ID) == CRYPT_ANY_TOKEN &&
 4098             (!strcmp(action_argv[0], "remove") || !strcmp(action_argv[0], "export")))
 4099             usage(popt_context, EXIT_FAILURE,
 4100                   _("Action requires specific token. Use --token-id parameter."),
 4101                   poptGetInvocationName(popt_context));
 4102     }
 4103 
 4104     if (ARG_SET(OPT_DISABLE_KEYRING_ID))
 4105         (void) crypt_volume_key_keyring(NULL, 0);
 4106 
 4107     if (ARG_SET(OPT_DISABLE_EXTERNAL_TOKENS_ID))
 4108         (void) crypt_token_external_disable();
 4109 
 4110     if (ARG_SET(OPT_DISABLE_LOCKS_ID) && crypt_metadata_locking(NULL, 0)) {
 4111         log_std(_("Cannot disable metadata locking."));
 4112         r = EXIT_FAILURE;
 4113     } else {
 4114         r = run_action(action);
 4115     }
 4116 
 4117     tools_cleanup();
 4118     poptFreeContext(popt_context);
 4119     return r;
 4120 }