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