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