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