summaryrefslogtreecommitdiffstats
path: root/src/utils_reencrypt.c
blob: a78557cb1d752964c0b51a41506a61c7d8eb9fd8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
/*
 * cryptsetup - action re-encryption utilities
 *
 * Copyright (C) 2009-2023 Red Hat, Inc. All rights reserved.
 * Copyright (C) 2009-2023 Milan Broz
 * Copyright (C) 2021-2023 Ondrej Kozina
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <uuid/uuid.h>

#include "cryptsetup.h"
#include "cryptsetup_args.h"
#include "utils_luks.h"

extern int64_t data_shift;
extern const char *device_type;
extern const char *set_pbkdf;

enum device_status_info {
	DEVICE_LUKS2 = 0,	/* LUKS2 device */
	DEVICE_LUKS2_REENCRYPT,	/* LUKS2 device in reencryption  */
	DEVICE_LUKS1,		/* LUKS1 device */
	DEVICE_LUKS1_UNUSABLE,	/* LUKS1 device in reencryption (legacy) */
	DEVICE_NOT_LUKS,	/* device is not LUKS type */
	DEVICE_INVALID		/* device is invalid */
};

static void _set_reencryption_flags(uint32_t *flags)
{
	if (ARG_SET(OPT_INIT_ONLY_ID))
		*flags |= CRYPT_REENCRYPT_INITIALIZE_ONLY;

	if (ARG_SET(OPT_RESUME_ONLY_ID))
		*flags |= CRYPT_REENCRYPT_RESUME_ONLY;
}

static int reencrypt_check_passphrase(struct crypt_device *cd,
	int keyslot,
	const char *passphrase,
	size_t passphrase_len)
{
	int r;

	assert(cd);

	r = crypt_activate_by_passphrase(cd, NULL, keyslot,
					 passphrase, passphrase_len, 0);
	check_signal(&r);
	tools_passphrase_msg(r);
	tools_keyslot_msg(r, UNLOCKED);

	return r;
}

static int set_keyslot_params(struct crypt_device *cd, int keyslot)
{
	const char *cipher;
	struct crypt_pbkdf_type pbkdf;
	size_t key_size;

	cipher = crypt_keyslot_get_encryption(cd, keyslot, &key_size);
	if (!cipher)
		return -EINVAL;

	if (crypt_is_cipher_null(cipher)) {
		log_dbg("Keyslot %d uses cipher_null. "
			"Replacing with default encryption in new keyslot.", keyslot);
		cipher = DEFAULT_LUKS2_KEYSLOT_CIPHER;
		key_size = DEFAULT_LUKS2_KEYSLOT_KEYBITS / 8;
	}

	if (crypt_keyslot_set_encryption(cd, cipher, key_size))
		return -EINVAL;

	/* if requested any of those just reinitialize context pbkdf */
	if (set_pbkdf || ARG_SET(OPT_HASH_ID) || ARG_SET(OPT_PBKDF_FORCE_ITERATIONS_ID) ||
	    ARG_SET(OPT_ITER_TIME_ID))
		return set_pbkdf_params(cd, CRYPT_LUKS2);

	if (crypt_keyslot_get_pbkdf(cd, keyslot, &pbkdf))
		return -EINVAL;

	pbkdf.flags |= CRYPT_PBKDF_NO_BENCHMARK;

	return crypt_set_pbkdf_type(cd, &pbkdf);
}

static int get_active_device_name(struct crypt_device *cd,
	const char *data_device,
	char **r_active_name)
{
	char *msg;
	int r;

	assert(data_device);

	r = tools_lookup_crypt_device(cd, crypt_get_type(cd), data_device, r_active_name);
	if (r > 0) {
		log_dbg("Device %s has %d active holders.", data_device, r);

		if (!*r_active_name) {
			log_err(_("Device %s is still in use."), data_device);
			return -EINVAL;
		}
		if (!ARG_SET(OPT_BATCH_MODE_ID))
			log_std(_("Auto-detected active dm device '%s' for data device %s.\n"),
				*r_active_name, data_device);
	} else if (r < 0) {
		if (r != -ENOTBLK) {
			log_err(_("Failed to auto-detect device %s holders."), data_device);
			return -EINVAL;
		}

		r = -EINVAL;
		if (!ARG_SET(OPT_BATCH_MODE_ID)) {
			log_std(_("Device %s is not a block device.\n"), data_device);

			r = asprintf(&msg, _("Unable to decide if device %s is activated or not.\n"
					     "Are you sure you want to proceed with reencryption in offline mode?\n"
					     "It may lead to data corruption if the device is actually activated.\n"
					     "To run reencryption in online mode, use --active-name parameter instead.\n"), data_device);
			if (r < 0)
				return -ENOMEM;
			r = noDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
			free(msg);
		} else {
			log_err(_("Device %s is not a block device. Can not auto-detect if it is active or not.\n"
				"Use --force-offline-reencrypt to bypass the check and run in offline mode (dangerous!)."), data_device);
		}
	} else {
		*r_active_name = NULL;
		log_dbg("Device %s is unused. Proceeding with offline reencryption.", data_device);
	}

	return r;
}

static int reencrypt_get_active_name(struct crypt_device *cd,
	const char *data_device,
	char **r_active_name)
{
	assert(cd);
	assert(r_active_name);

	if (ARG_SET(OPT_ACTIVE_NAME_ID))
		return (*r_active_name = strdup(ARG_STR(OPT_ACTIVE_NAME_ID))) ? 0 : -ENOMEM;

	return get_active_device_name(cd, data_device, r_active_name);
}

static int decrypt_verify_and_set_params(struct crypt_params_reencrypt *params)
{
	const char *resilience;

	assert(params);

	if (!ARG_SET(OPT_RESILIENCE_ID))
		return 0;

	resilience = ARG_STR(OPT_RESILIENCE_ID);

	if (!strcmp(resilience, "datashift") ||
	    !strcmp(resilience, "none")) {
		log_err(_("Requested --resilience option cannot be applied "
			  "to current reencryption operation."));
		return -EINVAL;
	} else if (!strcmp(resilience, "journal"))
		params->resilience = "datashift-journal";
	else if (!strcmp(resilience, "checksum"))
		params->resilience = "datashift-checksum";
	else if (!strcmp(resilience, "datashift-checksum") ||
		 !strcmp(resilience, "datashift-journal"))
		params->resilience = resilience;
	else {
		log_err(_("Unsupported resilience mode %s"), resilience);
		return -EINVAL;
	}

	return 0;
}

static int reencrypt_verify_and_update_params(struct crypt_params_reencrypt *params,
	char **r_hash)
{
	assert(params);
	assert(r_hash);

	if (ARG_SET(OPT_ENCRYPT_ID) && params->mode != CRYPT_REENCRYPT_ENCRYPT) {
		log_err(_("Device is not in LUKS2 encryption. Conflicting option --encrypt."));
		return -EINVAL;
	}

	if (ARG_SET(OPT_DECRYPT_ID) && params->mode != CRYPT_REENCRYPT_DECRYPT) {
		log_err(_("Device is not in LUKS2 decryption. Conflicting option --decrypt."));
		return -EINVAL;
	}

	if (ARG_SET(OPT_RESILIENCE_ID)) {
		if (!strcmp(params->resilience, "datashift") &&
		    strcmp(ARG_STR(OPT_RESILIENCE_ID), "datashift")) {
			log_err(_("Device is in reencryption using datashift resilience. "
				  "Requested --resilience option cannot be applied."));
			return -EINVAL;
		}
		if (strcmp(params->resilience, "datashift") &&
		    !strcmp(ARG_STR(OPT_RESILIENCE_ID), "datashift")) {
			log_err(_("Requested --resilience option cannot be applied "
				  "to current reencryption operation."));
			return -EINVAL;
		}

		if (!strncmp(params->resilience, "datashift-", 10)) {
			/* decryption with datashift in progress */
			if (decrypt_verify_and_set_params(params))
				return -EINVAL;
		} else if (!strncmp(ARG_STR(OPT_RESILIENCE_ID), "datashift-", 10)) {
			log_err(_("Requested --resilience option cannot be applied "
				  "to current reencryption operation."));
			return -EINVAL;
		} else
			params->resilience = ARG_STR(OPT_RESILIENCE_ID);

		/* we have to copy hash string returned by API */
		if (params->hash && !ARG_SET(OPT_RESILIENCE_HASH_ID)) {
			/* r_hash owns the memory. Freed by caller */
			*r_hash = strdup(params->hash);
			if (!*r_hash)
				return -ENOMEM;
			params->hash = *r_hash;
		}

		/* Add default hash when switching to checksum based resilience */
		if (!params->hash && !ARG_SET(OPT_RESILIENCE_HASH_ID) &&
		    (!strcmp(params->resilience, "checksum") ||
		    !strcmp(params->resilience, "datashift-checksum")))
			params->hash = "sha256";

		if (ARG_SET(OPT_RESILIENCE_HASH_ID))
			params->hash = ARG_STR(OPT_RESILIENCE_HASH_ID);
	} else
		params->resilience = NULL;

	params->max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE;
	params->device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE;
	params->flags = CRYPT_REENCRYPT_RESUME_ONLY;

	return 0;
}

static int reencrypt_hint_force_offline_reencrypt(const char *data_device)
{
	struct stat st;

	if (ARG_SET(OPT_ACTIVE_NAME_ID) ||
	    !ARG_SET(OPT_BATCH_MODE_ID) ||
	    ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID))
		return 0;

	if (stat(data_device, &st) == 0 && S_ISREG(st.st_mode)) {
		log_err(_("Device %s is not a block device. Can not auto-detect if it is active or not.\n"
			"Use --force-offline-reencrypt to bypass the check and run in offline mode (dangerous!)."), data_device);
		return -EINVAL;
	}

	return 0;
}

static int reencrypt_luks2_load(struct crypt_device *cd, const char *data_device)
{
	char *msg;
	crypt_reencrypt_info ri;
	int r;
	size_t passwordLen;
	char *active_name = NULL, *hash = NULL, *password = NULL;
	struct crypt_params_reencrypt params = {};

	ri = crypt_reencrypt_status(cd, &params);
	if (ri == CRYPT_REENCRYPT_CRASH)
		log_err(_("Device requires reencryption recovery. Run repair first."));

	if (ri != CRYPT_REENCRYPT_CLEAN)
		return -EINVAL;

	r = reencrypt_verify_and_update_params(&params, &hash);
	if (r < 0)
		return r;

	r = reencrypt_hint_force_offline_reencrypt(data_device);
	if (r < 0)
		goto out;

	if (!ARG_SET(OPT_BATCH_MODE_ID) && !ARG_SET(OPT_RESUME_ONLY_ID)) {
		r = asprintf(&msg, _("Device %s is already in LUKS2 reencryption. "
				     "Do you wish to resume previously initialised operation?"),
			     crypt_get_metadata_device_name(cd) ?: data_device);
		if (r < 0) {
			r = -ENOMEM;
			goto out;
		}
		r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
		free(msg);
		if (r < 0)
			goto out;
	}

	r = tools_get_key(NULL, &password, &passwordLen,
			ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID),
			ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID),
			verify_passphrase(0), 0, cd);
	if (r < 0)
		goto out;

	if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID))
		r = reencrypt_get_active_name(cd, data_device, &active_name);
	if (r >= 0)
		r = crypt_reencrypt_init_by_passphrase(cd, active_name, password,
				passwordLen, ARG_INT32(OPT_KEY_SLOT_ID),
				ARG_INT32(OPT_KEY_SLOT_ID), NULL, NULL, &params);
out:
	free(hash);
	crypt_safe_free(password);
	free(active_name);
	return r;
}

/*
 *   1: in-progress
 *   0: clean luks2 device
 * < 0: error
 */
static int luks2_reencrypt_in_progress(struct crypt_device *cd)
{
	uint32_t flags;

	if (crypt_persistent_flags_get(cd, CRYPT_FLAGS_REQUIREMENTS, &flags))
		return -EINVAL;

	if (flags & CRYPT_REQUIREMENT_OFFLINE_REENCRYPT) {
		log_err(_("Legacy LUKS2 reencryption is no longer supported."));
		return -EINVAL;
	}

	return flags & CRYPT_REQUIREMENT_ONLINE_REENCRYPT;
}

/*
 * Returns crypt context for:
 *   DEVICE_LUKS2
 *   DEVICE_LUKS2_REENCRYPT
 *   DEVICE_LUKS1
 */
static enum device_status_info load_luks(struct crypt_device **r_cd,
	const char *header_device,
	const char *data_device)
{
	int r;
	struct crypt_device *cd;
	struct stat st;

	assert(r_cd);
	assert(data_device);

	if (header_device && stat(header_device, &st) < 0 && errno == ENOENT)
		return DEVICE_NOT_LUKS;

	if (crypt_init_data_device(&cd, uuid_or_device(header_device ?: data_device), data_device))
		return DEVICE_INVALID;

	if ((r = crypt_load(cd, CRYPT_LUKS, NULL))) {
		crypt_free(cd);

		if (r == -EBUSY) /* luks2 locking error (message printed by libcryptsetup) */
			return DEVICE_INVALID;

		r = reencrypt_luks1_in_progress(uuid_or_device(header_device ?: data_device));
		if (!r)
			return DEVICE_LUKS1_UNUSABLE;

		return DEVICE_NOT_LUKS;
	}

	if (isLUKS2(crypt_get_type(cd))) {
		r = luks2_reencrypt_in_progress(cd);
		if (r < 0) {
			crypt_free(cd);
			return DEVICE_INVALID;
		}
	}

	*r_cd = cd;

	if (r > 0)
		return DEVICE_LUKS2_REENCRYPT;

	return isLUKS2(crypt_get_type(cd)) ? DEVICE_LUKS2 : DEVICE_LUKS1;
}

static bool luks2_reencrypt_eligible(struct crypt_device *cd)
{
	struct crypt_params_integrity ip = { 0 };

	/* raw integrity info is available since 2.0 */
	if (crypt_get_integrity_info(cd, &ip) || ip.tag_size) {
		log_err(_("Reencryption of device with integrity profile is not supported."));
		return false;
	}

	return true;
}

static enum device_status_info check_luks_device(const char *device)
{
	enum device_status_info dev_st;
	struct crypt_device *cd = NULL;

	dev_st = load_luks(&cd, NULL, device);
	crypt_free(cd);

	return dev_st;
}

static int reencrypt_check_data_sb_block_size(const char *data_device, uint32_t new_sector_size)
{
	int r;
	char sb_name[32];
	unsigned block_size;

	assert(data_device);

	r = tools_superblock_block_size(data_device, sb_name, sizeof(sb_name), &block_size);
	if (r <= 0)
		return r;

	if (new_sector_size > block_size) {
		log_err(_("Requested --sector-size %" PRIu32 " is incompatible with %s superblock\n"
			  "(block size: %" PRIu32 " bytes) detected on device %s."),
			new_sector_size, sb_name, block_size, data_device);
		return -EINVAL;
	}

	return 0;
}

static int reencrypt_check_active_device_sb_block_size(const char *active_device, uint32_t new_sector_size)
{
	int r;
	char dm_device[PATH_MAX];

	r = snprintf(dm_device, sizeof(dm_device), "%s/%s", crypt_get_dir(), active_device);
	if (r < 0 || (size_t)r >= sizeof(dm_device))
		return -EINVAL;

	return reencrypt_check_data_sb_block_size(dm_device, new_sector_size);
}

static int reencrypt_is_header_detached(const char *header_device, const char *data_device)
{
	int r;
	struct stat st;
	struct crypt_device *cd;

	if (!header_device)
		return 0;

	if (header_device && stat(header_device, &st) < 0 && errno == ENOENT)
		return 1;

	if ((r = crypt_init_data_device(&cd, header_device, data_device)))
		return r;

	r = crypt_header_is_detached(cd);
	crypt_free(cd);
	return r;
}

static int encrypt_luks2_init(struct crypt_device **cd, const char *data_device, const char *device_name)
{
	int keyslot, r, fd;
	uuid_t uuid;
	size_t passwordLen;
	char *tmp, uuid_str[37], header_file[PATH_MAX] = { 0 }, *password = NULL;
	uint32_t activate_flags = 0;
	const struct crypt_params_luks2 luks2_params = {
		.sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID) ?: SECTOR_SIZE
	};
	struct crypt_params_reencrypt params = {
		.mode = CRYPT_REENCRYPT_ENCRYPT,
		.direction = data_shift < 0 ? CRYPT_REENCRYPT_BACKWARD : CRYPT_REENCRYPT_FORWARD,
		.resilience = ARG_STR(OPT_RESILIENCE_ID) ?: "checksum",
		.hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
		.max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
		.device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
		.luks2 = &luks2_params,
		.flags = CRYPT_REENCRYPT_INITIALIZE_ONLY
	};

	_set_reencryption_flags(&params.flags);

	if (!data_shift) {
		r = reencrypt_is_header_detached(ARG_STR(OPT_HEADER_ID), data_device);
		if (r < 0)
			return r;
		if (!r) {
			log_err(_("Encryption without detached header (--header) is not possible without data device size reduction (--reduce-device-size)."));
			return -ENOTSUP;
		}
	}

	if (!ARG_SET(OPT_HEADER_ID) && ARG_UINT64(OPT_OFFSET_ID) &&
	    data_shift && (ARG_UINT64(OPT_OFFSET_ID) > (uint64_t)(imaxabs(data_shift) / (2 * SECTOR_SIZE)))) {
		log_err(_("Requested data offset must be less than or equal to half of --reduce-device-size parameter."));
		return -EINVAL;
	}

	/* TODO: ask user to confirm. It's useless to do data device reduction and than use smaller value */
	if (!ARG_SET(OPT_HEADER_ID) && ARG_UINT64(OPT_OFFSET_ID) &&
	    data_shift && (ARG_UINT64(OPT_OFFSET_ID) < (uint64_t)(imaxabs(data_shift) / (2 * SECTOR_SIZE)))) {
		data_shift = -(ARG_UINT64(OPT_OFFSET_ID) * 2 * SECTOR_SIZE);
		if (data_shift >= 0)
			return -EINVAL;
		log_std(_("Adjusting --reduce-device-size value to twice the --offset %" PRIu64 " (sectors).\n"), ARG_UINT64(OPT_OFFSET_ID) * 2);
	}

	if (ARG_SET(OPT_UUID_ID) && uuid_parse(ARG_STR(OPT_UUID_ID), uuid) == -1) {
		log_err(_("Wrong LUKS UUID format provided."));
		return -EINVAL;
	}

	if (ARG_SET(OPT_SECTOR_SIZE_ID)) {
		r = reencrypt_check_data_sb_block_size(data_device, ARG_UINT32(OPT_SECTOR_SIZE_ID));
		if (r < 0)
			return r;
	}

	if (!ARG_SET(OPT_UUID_ID)) {
		uuid_generate(uuid);
		uuid_unparse(uuid, uuid_str);
		if (!(tmp = strdup(uuid_str)))
			return -ENOMEM;
		ARG_SET_STR(OPT_UUID_ID, tmp);
	}

	if (!ARG_SET(OPT_HEADER_ID)) {
		r = snprintf(header_file, sizeof(header_file), "LUKS2-temp-%s.new", ARG_STR(OPT_UUID_ID));
		if (r < 0 || (size_t)r >= sizeof(header_file))
			return -EINVAL;

		fd = open(header_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR);
		if (fd == -1) {
			if (errno == EEXIST)
				log_err(_("Temporary header file %s already exists. Aborting."), header_file);
			else
				log_err(_("Cannot create temporary header file %s."), header_file);
			return -EINVAL;
		}

		r = posix_fallocate(fd, 0, 4096);
		close(fd);
		if (r) {
			log_err(_("Cannot create temporary header file %s."), header_file);
			r = -EINVAL;
			goto out;
		}

		if (!(tmp = strdup(header_file))) {
			r = -ENOMEM;
			goto out;
		}
		ARG_SET_STR(OPT_HEADER_ID, tmp);

		/*
		 * FIXME: just override offset here, but we should support both.
		 * offset and implicit offset via data shift (lvprepend?)
		 */
		if (!ARG_UINT64(OPT_OFFSET_ID))
			ARG_SET_UINT64(OPT_OFFSET_ID, imaxabs(data_shift) / (2 * SECTOR_SIZE));
		data_shift >>= 1;
		params.flags |= CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT;
	} else if (data_shift < 0) {
		if (!ARG_SET(OPT_LUKS2_METADATA_SIZE_ID))
			ARG_SET_UINT64(OPT_LUKS2_METADATA_SIZE_ID, 0x4000); /* missing default here */
		if (!ARG_SET(OPT_LUKS2_KEYSLOTS_SIZE_ID))
			ARG_SET_UINT64(OPT_LUKS2_KEYSLOTS_SIZE_ID, -data_shift - 2 * ARG_UINT64(OPT_LUKS2_METADATA_SIZE_ID));
		if (2 * ARG_UINT64(OPT_LUKS2_METADATA_SIZE_ID) + ARG_UINT64(OPT_LUKS2_KEYSLOTS_SIZE_ID) > (uint64_t)-data_shift) {
			log_err(_("LUKS2 metadata size is larger than data shift value."));
			return -EINVAL;
		}
	}

	r = luksFormat(cd, &password, &passwordLen);
	if (r < 0)
		goto out;

	if (!luks2_reencrypt_eligible(*cd)) {
		r = -EINVAL;
		goto out;
	}

	if (data_shift) {
		params.data_shift = imaxabs(data_shift) / SECTOR_SIZE,
		params.resilience = "datashift";
	}
	keyslot = !ARG_SET(OPT_KEY_SLOT_ID) ? 0 : ARG_INT32(OPT_KEY_SLOT_ID);
	r = crypt_reencrypt_init_by_passphrase(*cd, NULL, password, passwordLen,
			CRYPT_ANY_SLOT, keyslot, crypt_get_cipher(*cd),
			crypt_get_cipher_mode(*cd), &params);
	if (r < 0) {
		crypt_keyslot_destroy(*cd, keyslot);
		goto out;
	}

	/* Restore temporary header in head of data device */
	if (*header_file) {
		crypt_free(*cd);
		*cd = NULL;

		r = crypt_init(cd, data_device);
		if (!r)
			r = crypt_header_restore(*cd, CRYPT_LUKS2, header_file);

		if (r) {
			log_err(_("Failed to place new header at head of device %s."), data_device);
			goto out;
		}
	}

	/* activate device */
	if (device_name) {
		set_activation_flags(&activate_flags);
		r = crypt_activate_by_passphrase(*cd, device_name, ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen, activate_flags);
		if (r >= 0)
			log_std(_("%s/%s is now active and ready for online encryption.\n"), crypt_get_dir(), device_name);
	}

	if (r < 0)
		goto out;

	/* just load reencryption context to continue reencryption */
	if (!ARG_SET(OPT_INIT_ONLY_ID)) {
		params.flags &= ~CRYPT_REENCRYPT_INITIALIZE_ONLY;
		r = crypt_reencrypt_init_by_passphrase(*cd, device_name, password, passwordLen,
				CRYPT_ANY_SLOT, keyslot, NULL, NULL, &params);
	}
out:
	crypt_safe_free(password);
	if (*header_file)
		unlink(header_file);
	return r;
}

static enum device_status_info load_luks2_by_name(struct crypt_device **r_cd, const char *active_name, const char *header_device)
{
	int r;
	struct crypt_device *cd;
	struct stat st;

	assert(r_cd);
	assert(active_name);

	if (header_device && stat(header_device, &st) < 0 && errno == ENOENT)
		return DEVICE_NOT_LUKS;

	r = crypt_init_by_name_and_header(&cd, active_name, header_device);
	if (r)
		return DEVICE_INVALID;

	if (!isLUKS2(crypt_get_type(cd))) {
		log_err(_("Active device %s is not LUKS2."), active_name);
		crypt_free(cd);
		return DEVICE_INVALID;
	}

	r = luks2_reencrypt_in_progress(cd);
	if (r < 0) {
		crypt_free(cd);
		return DEVICE_INVALID;
	}

	*r_cd = cd;

	return !r ? DEVICE_LUKS2 : DEVICE_LUKS2_REENCRYPT;
}

static int reencrypt_restore_header(struct crypt_device **cd,
	const char *data_device, const char *header)
{
	int r;

	assert(cd);
	assert(data_device);
	assert(header);

	crypt_free(*cd);
	*cd = NULL;

	log_verbose(_("Restoring original LUKS2 header."));

	r = crypt_init(cd, data_device);
	if (r < 0)
		return r;

	r = crypt_header_restore(*cd, CRYPT_LUKS2, header);
	if (r < 0)
		log_err(_("Original LUKS2 header restore failed."));

	return r;
}

static int decrypt_luks2_datashift_init(struct crypt_device **cd,
	const char *data_device,
	const char *expheader)
{
	int fd, r;
	size_t passwordLen;
	struct stat hdr_st;
	bool remove_header = false;
	char *msg, *active_name = NULL, *password = NULL;
	struct crypt_params_reencrypt params = {
		.mode = CRYPT_REENCRYPT_DECRYPT,
		.direction = CRYPT_REENCRYPT_FORWARD,
		.resilience = "datashift-checksum",
		.hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
		.data_shift = crypt_get_data_offset(*cd),
		.device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
		.max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
		.flags = CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT
	};

	if (!ARG_SET(OPT_BATCH_MODE_ID)) {
		r = asprintf(&msg, _("Header file %s does not exist. Do you want to initialize LUKS2 "
				     "decryption of device %s and export LUKS2 header to file %s?"),
			     expheader, data_device, expheader);
		if (r < 0)
			return -ENOMEM;
		r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
		free(msg);
		if (r < 0)
			return r;
	}

	if ((r = decrypt_verify_and_set_params(&params)))
		return r;

	r = reencrypt_hint_force_offline_reencrypt(data_device);
	if (r < 0)
		return r;

	r = tools_get_key(NULL, &password, &passwordLen,
			ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID),
			ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID),
			verify_passphrase(0), 0, *cd);
	if (r < 0)
		return r;

	r = reencrypt_check_passphrase(*cd, ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen);
	if (r < 0)
		goto out;

	r = crypt_header_backup(*cd, CRYPT_LUKS2, expheader);
	if (r < 0)
		goto out;

	remove_header = true;

	fd = open(expheader, O_RDONLY);
	if (fd < 0)
		goto out;

	if (fstat(fd, &hdr_st)) {
		close(fd);
		r = -EINVAL;
		goto out;
	}

	r = fchmod(fd, hdr_st.st_mode  | S_IRUSR | S_IWUSR);
	close(fd);
	if (r) {
		log_err(_("Failed to add read/write permissions to exported header file."));
		r = -EINVAL;
		goto out;
	}

	crypt_free(*cd);
	*cd = NULL;

	/* reload with exported header */
	if (ARG_SET(OPT_ACTIVE_NAME_ID)) {
		if (load_luks2_by_name(cd, ARG_STR(OPT_ACTIVE_NAME_ID), expheader) != DEVICE_LUKS2) {
			r = -EINVAL;
			goto out;
		}
	} else {
		if ((r = crypt_init_data_device(cd, expheader, data_device)))
			goto out;
		if ((r = crypt_load(*cd, CRYPT_LUKS2, NULL)))
			goto out;
	}

	_set_reencryption_flags(&params.flags);

	if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID))
		r = reencrypt_get_active_name(*cd, data_device, &active_name);

	if (r < 0)
		goto out;

	r = tools_wipe_all_signatures(data_device, active_name == NULL, true);
	if (r < 0) {
		/* if header restore fails keep original header backup */
		if (reencrypt_restore_header(cd, data_device, expheader) < 0)
			remove_header = false;
		goto out;
	}

	remove_header = false;

	r = crypt_reencrypt_init_by_passphrase(*cd, active_name, password,
			passwordLen, ARG_INT32(OPT_KEY_SLOT_ID), CRYPT_ANY_SLOT,
			NULL, NULL, &params);

	if (r < 0 && crypt_reencrypt_status(*cd, NULL) == CRYPT_REENCRYPT_NONE) {
		/* if restore is successful we can remove header backup */
		if (!reencrypt_restore_header(cd, data_device, expheader))
			remove_header = true;
	}
out:
	free(active_name);
	crypt_safe_free(password);

	if (r < 0 && !remove_header && !stat(expheader, &hdr_st) && S_ISREG(hdr_st.st_mode))
		log_err(_("Reencryption initialization failed. Header backup is available in %s."),
			expheader);
	if (remove_header)
		unlink(expheader);

	return r;
}

static int decrypt_luks2_init(struct crypt_device *cd, const char *data_device)
{
	int r;
	size_t passwordLen;
	char *active_name = NULL, *password = NULL;
	struct crypt_params_reencrypt params = {
		.mode = CRYPT_REENCRYPT_DECRYPT,
		.direction = data_shift > 0 ? CRYPT_REENCRYPT_FORWARD : CRYPT_REENCRYPT_BACKWARD,
		.resilience = data_shift ? "datashift" : (ARG_STR(OPT_RESILIENCE_ID) ?: "checksum"),
		.hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
		.data_shift = imaxabs(data_shift) / SECTOR_SIZE,
		.device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
		.max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
	};

	if (!luks2_reencrypt_eligible(cd))
		return -EINVAL;

	if ((!crypt_get_metadata_device_name(cd) || crypt_header_is_detached(cd) <= 0 ||
	    crypt_get_data_offset(cd) > 0)) {
		log_err(_("LUKS2 decryption is supported with detached header device only (with data offset set to 0)."));
		return -ENOTSUP;
	}

	r = reencrypt_hint_force_offline_reencrypt(data_device);
	if (r < 0)
		return r;

	_set_reencryption_flags(&params.flags);

	r = tools_get_key(NULL, &password, &passwordLen,
			ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
			ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd);
	if (r < 0)
		return r;

	r = reencrypt_check_passphrase(cd, ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen);
	if (r < 0)
		goto out;

	if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID))
		r = reencrypt_get_active_name(cd, data_device, &active_name);
	if (r >= 0)
		r = crypt_reencrypt_init_by_passphrase(cd, active_name, password,
				passwordLen, ARG_INT32(OPT_KEY_SLOT_ID), CRYPT_ANY_SLOT, NULL, NULL, &params);

out:
	free(active_name);
	crypt_safe_free(password);
	return r;
}

struct keyslot_passwords {
	char *password;
	size_t passwordLen;
	int new;
};

static struct keyslot_passwords *init_keyslot_passwords(size_t count)
{
	size_t i;
	struct keyslot_passwords *tmp = calloc(count, sizeof(struct keyslot_passwords));

	if (!tmp)
		return tmp;

	for (i = 0; i < count; i++)
		tmp[i].new = -1;

	return tmp;
}

static int init_passphrase(struct keyslot_passwords *kp, size_t keyslot_passwords_length,
			   struct crypt_device *cd, const char *msg, int slot_to_check)
{
	crypt_keyslot_info ki;
	char *password;
	int r = -EINVAL, retry_count;
	size_t passwordLen;

	if (slot_to_check != CRYPT_ANY_SLOT) {
		ki = crypt_keyslot_status(cd, slot_to_check);
		if (ki < CRYPT_SLOT_ACTIVE || ki == CRYPT_SLOT_UNBOUND)
			return -ENOENT;
	}

	retry_count = set_tries_tty();

	while (retry_count--) {
		r = tools_get_key(msg,  &password, &passwordLen, 0, 0,
				  ARG_STR(OPT_KEY_FILE_ID), 0, 0, 0 /*pwquality*/, cd);
		if (r < 0)
			return r;
		if (quit) {
			crypt_safe_free(password);
			password = NULL;
			passwordLen = 0;
			return -EAGAIN;
		}

		r = crypt_activate_by_passphrase(cd, NULL, slot_to_check,
						 password, passwordLen, 0);
		if (r < 0) {
			crypt_safe_free(password);
			password = NULL;
			passwordLen = 0;
		}
		if (r < 0 && r != -EPERM)
			return r;

		if (r >= 0) {
			tools_keyslot_msg(r, UNLOCKED);
			if ((size_t)r >= keyslot_passwords_length) {
				crypt_safe_free(password);
				return -EINVAL;
			}
			kp[r].password = password;
			kp[r].passwordLen = passwordLen;
			break;
		}
		tools_passphrase_msg(r);
	}

	password = NULL;
	passwordLen = 0;

	return r;
}

static int _check_luks2_keyslots(struct crypt_device *cd, bool vk_change)
{
	int i, new_vk_slot = (vk_change ? 1 : 0), max = crypt_keyslot_max(CRYPT_LUKS2), active = 0, unbound = 0;

	if (max < 0)
		return max;

	for (i = 0; i < max; i++) {
		switch (crypt_keyslot_status(cd, i)) {
		case CRYPT_SLOT_INVALID:
			return -EINVAL;
		case CRYPT_SLOT_ACTIVE:
			/* fall-through */
		case CRYPT_SLOT_ACTIVE_LAST:
			active++;
			break;
		case CRYPT_SLOT_UNBOUND:
			unbound++;
			/* fall-through */
		default:
			break;
		}
	}

	/* at least one keyslot for reencryption plus new volume key (if needed) */
	if (active + unbound + new_vk_slot + 1 > max) {
		log_err(_("Not enough free keyslots for reencryption."));
		return -EINVAL;
	}

	if (!vk_change)
		return 0;

	if ((ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT) &&
            (2 * active + unbound + 1 > max)) {
		log_err(_("Not enough free keyslots for reencryption."));
		return -EINVAL;
	}

	return 0;
}

static int fill_keyslot_passwords(struct crypt_device *cd,
		struct keyslot_passwords *kp, size_t kp_size,
		bool vk_change)
{
	char msg[128];
	crypt_keyslot_info ki;
	int i, r = 0;

	if (vk_change && ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT && ARG_SET(OPT_KEY_FILE_ID)) {
		for (i = 0; (size_t)i < kp_size; i++) {
			ki = crypt_keyslot_status(cd, i);
			if (ki == CRYPT_SLOT_INVALID)
				return -EINVAL;
			if (ki == CRYPT_SLOT_ACTIVE) {
				log_err(_("Key file can be used only with --key-slot or with "
					  "exactly one key slot active."));
				return -EINVAL;
			}
		}
	}

	if (ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT) {
		for (i = 0; (size_t)i < kp_size; i++) {
			if (snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %d: "), i) < 0)
				return -EINVAL;
			r = init_passphrase(kp, kp_size, cd, msg, i);
			/* no need to initialize all keyslots with --keep-key */
			if (r >= 0 && !vk_change)
				break;
			if (r == -ENOENT)
				r = 0;
			if (r < 0)
				break;
		}
	} else {
		if (snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %u: "), ARG_INT32(OPT_KEY_SLOT_ID)) < 0)
			return -EINVAL;
		r = init_passphrase(kp, kp_size, cd, msg, ARG_INT32(OPT_KEY_SLOT_ID));
	}

	return r < 0 ? r : 0;
}

static int assign_tokens(struct crypt_device *cd, int keyslot_old, int keyslot_new)
{
	int token = 0, r = crypt_token_is_assigned(cd, token, keyslot_old);

	while (r != -EINVAL) {
		if (!r && (token != crypt_token_assign_keyslot(cd, token, keyslot_new)))
			return -EINVAL;
		token++;
		r = crypt_token_is_assigned(cd, token, keyslot_old);
	}

	/* we reached max token number, exit */
	return 0;
}

static int reencrypt_luks2_init(struct crypt_device *cd, const char *data_device)
{
	bool vk_size_change, sector_size_change, sector_size_increase, vk_change;
	size_t i, vk_size, kp_size;
	int r, keyslot_old = CRYPT_ANY_SLOT, keyslot_new = CRYPT_ANY_SLOT, key_size;
	char cipher[MAX_CIPHER_LEN], mode[MAX_CIPHER_LEN], *vk = NULL, *active_name = NULL;
	const char *new_cipher = NULL;
	struct keyslot_passwords *kp = NULL;
	struct crypt_params_luks2 luks2_params = {};
	struct crypt_params_reencrypt params = {
		.mode = CRYPT_REENCRYPT_REENCRYPT,
		.direction = data_shift < 0 ? CRYPT_REENCRYPT_BACKWARD : CRYPT_REENCRYPT_FORWARD,
		.resilience = data_shift ? "datashift" : (ARG_STR(OPT_RESILIENCE_ID) ?: "checksum"),
		.hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
		.data_shift = imaxabs(data_shift) / SECTOR_SIZE,
		.max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
		.device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
		.luks2 = &luks2_params,
	};

	if (!luks2_reencrypt_eligible(cd))
		return -EINVAL;

	_set_reencryption_flags(&params.flags);

	/* cipher */
	if (ARG_SET(OPT_CIPHER_ID))
		new_cipher = ARG_STR(OPT_CIPHER_ID);
	else if (!ARG_SET(OPT_CIPHER_ID) && crypt_is_cipher_null(crypt_get_cipher(cd))) {
		log_std(_("Switching data encryption cipher to %s.\n"), DEFAULT_CIPHER(LUKS1));
		new_cipher = DEFAULT_CIPHER(LUKS1);
	}

	if (!new_cipher) {
		strncpy(cipher, crypt_get_cipher(cd), MAX_CIPHER_LEN - 1);
		strncpy(mode, crypt_get_cipher_mode(cd), MAX_CIPHER_LEN - 1);
		cipher[MAX_CIPHER_LEN-1] = '\0';
		mode[MAX_CIPHER_LEN-1] = '\0';
	} else {
		if ((r = crypt_parse_name_and_mode(new_cipher, cipher, NULL, mode))) {
			log_err(_("No known cipher specification pattern detected."));
			return r;
		}

		/* the segment cipher is identical with existing one */
		if (!strcmp(cipher, crypt_get_cipher(cd)) && !strcmp(mode, crypt_get_cipher_mode(cd)))
			new_cipher = NULL;
	}

	/* sector size */
	luks2_params.sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID) ?: (uint32_t)crypt_get_sector_size(cd);
	sector_size_change = luks2_params.sector_size != (uint32_t)crypt_get_sector_size(cd);
	sector_size_increase = luks2_params.sector_size > (uint32_t)crypt_get_sector_size(cd);

	/* key size */
	if (ARG_SET(OPT_KEY_SIZE_ID) || new_cipher)
		key_size = get_adjusted_key_size(mode, DEFAULT_LUKS1_KEYBITS, 0);
	else
		key_size = crypt_get_volume_key_size(cd);

	if (!key_size)
		return -EINVAL;
	vk_size = key_size;

	vk_size_change = key_size != crypt_get_volume_key_size(cd);

	/* volume key */
	vk_change = !ARG_SET(OPT_KEEP_KEY_ID);

	if (vk_change && ARG_SET(OPT_VOLUME_KEY_FILE_ID)) {
		r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &vk, key_size);
		if (r < 0)
			goto out;

		if (!crypt_volume_key_verify(cd, vk, key_size)) {
			/* passed key was valid volume key */
			vk_change = false;
			crypt_safe_free(vk);
			vk = NULL;
		}
	}

	if (!vk_change && !vk_size_change && !new_cipher && !sector_size_change) {
		log_err(_("No data segment parameters changed. Reencryption aborted."));
		r = -EINVAL;
		goto out;
	}

	if (!ARG_SET(OPT_INIT_ONLY_ID) || (tools_blkid_supported() && sector_size_increase)) {
		r = reencrypt_hint_force_offline_reencrypt(data_device);
		if (r < 0)
			goto out;
	}

	r = _check_luks2_keyslots(cd, vk_change);
	if (r)
		goto out;

	r = crypt_keyslot_max(CRYPT_LUKS2);
	if (r < 0)
		goto out;
	kp_size = r;

	kp = init_keyslot_passwords(kp_size);
	if (!kp) {
		r = -ENOMEM;
		goto out;
	}

	/* coverity[overrun-call] */
	r = fill_keyslot_passwords(cd, kp, kp_size, vk_change);
	if (r)
		goto out;

	r = -ENOENT;

	for (i = 0; i < kp_size; i++) {
		if (!vk_change) {
			if (kp[i].password) {
				r = keyslot_old = kp[i].new = i;
				break;
			}
			continue;
		}

		if (kp[i].password && keyslot_new < 0) {
			r = set_keyslot_params(cd, i);
			if (r < 0)
				break;
			r = crypt_keyslot_add_by_key(cd, CRYPT_ANY_SLOT, vk, key_size,
					kp[i].password, kp[i].passwordLen, CRYPT_VOLUME_KEY_NO_SEGMENT);
			tools_keyslot_msg(r, CREATED);
			if (r < 0)
				break;

			kp[i].new = r;
			keyslot_new = r;
			keyslot_old = i;
			if (!vk) {
				/* key generated in crypt_keyslot_add_by_key() call above */
				vk = crypt_safe_alloc(key_size);
				if (!vk) {
					r = -ENOMEM;
					break;
				}
				r = crypt_volume_key_get(cd, keyslot_new, vk, &vk_size, kp[i].password, kp[i].passwordLen);
				if (r < 0)
					break;
			}
			r = assign_tokens(cd, i, r);
			if (r < 0)
				break;
		} else if (kp[i].password) {
			r = set_keyslot_params(cd, i);
			if (r < 0)
				break;
			r = crypt_keyslot_add_by_key(cd, CRYPT_ANY_SLOT, vk, key_size,
					kp[i].password, kp[i].passwordLen, CRYPT_VOLUME_KEY_NO_SEGMENT | CRYPT_VOLUME_KEY_DIGEST_REUSE);
			tools_keyslot_msg(r, CREATED);
			if (r < 0)
				break;
			kp[i].new = r;
			r = assign_tokens(cd, i, r);
			if (r < 0)
				break;
		}
	}

	if (r < 0)
		goto out;

	/*
	 * with --init-only lookup active device only if
	 * blkid probes are allowed and sector size increase
	 * is requested.
	 */
	if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID) &&
	    (!ARG_SET(OPT_INIT_ONLY_ID) || (tools_blkid_supported() && sector_size_increase))) {
		r = reencrypt_get_active_name(cd, data_device, &active_name);
		if (r < 0)
			goto out;
	}

	if (sector_size_increase && !active_name && tools_blkid_supported() &&
	    !ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID)) {
		log_err(_("Encryption sector size increase on offline device is not supported.\n"
			  "Activate the device first or use --force-offline-reencrypt option (dangerous!)."));
		r = -EINVAL;
		goto out;
	}

	if (sector_size_increase && active_name) {
		r = reencrypt_check_active_device_sb_block_size(active_name, luks2_params.sector_size);
		if (r < 0)
			goto out;
	}

	r = crypt_reencrypt_init_by_passphrase(cd,
			ARG_SET(OPT_INIT_ONLY_ID) ? NULL : active_name,
			kp[keyslot_old].password, kp[keyslot_old].passwordLen,
			keyslot_old, kp[keyslot_old].new, cipher, mode, &params);
out:
	crypt_safe_free(vk);
	if (kp) {
		for (i = 0; i < kp_size; i++) {
			crypt_safe_free(kp[i].password);
			if (r < 0 && kp[i].new >= 0 && kp[i].new != (int)i &&
			    crypt_reencrypt_status(cd, NULL) == CRYPT_REENCRYPT_NONE &&
			    crypt_keyslot_destroy(cd, kp[i].new))
				log_dbg("Failed to remove keyslot %d with unbound key.", kp[i].new);
		}
		free(kp);
	}
	free(active_name);
	return r;
}

static int reencrypt_luks2_resume(struct crypt_device *cd)
{
	int r;
	char *backing_file = NULL;
	struct tools_progress_params prog_parms = {
		.frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID),
		.batch_mode = ARG_SET(OPT_BATCH_MODE_ID),
		.json_output = ARG_SET(OPT_PROGRESS_JSON_ID),
		.interrupt_message = _("\nReencryption interrupted."),
		.device = tools_get_device_name(crypt_get_device_name(cd), &backing_file)
	};

	if (ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID) && !ARG_SET(OPT_BATCH_MODE_ID))
		log_std(_("Resuming LUKS reencryption in forced offline mode.\n"));

	set_int_handler(0);
	r = crypt_reencrypt_run(cd, tools_progress, &prog_parms);
	free(backing_file);
	return r;
}

static int check_broken_luks_signature(const char *device)
{
	int r;
	size_t count;

	r = tools_detect_signatures(device, PRB_ONLY_LUKS, &count, ARG_SET(OPT_BATCH_MODE_ID));
	if (r < 0)
		return -EINVAL;
	if (count) {
		log_err(_("Device %s contains broken LUKS metadata. Aborting operation."), device);
		return -EINVAL;
	}

	return 0;
}

static int _encrypt(struct crypt_device *cd, const char *type, enum device_status_info dev_st, int action_argc, const char **action_argv)
{
	const char *device_ptr;
	enum device_status_info data_dev_st;
	struct stat st;
	struct crypt_device *encrypt_cd = NULL;
	int r = -EINVAL;

	if (dev_st == DEVICE_LUKS2 || dev_st == DEVICE_LUKS1) {
		log_err(_("Device %s is already LUKS device. Aborting operation."),
			uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
		return -EINVAL;
	}

	if (dev_st == DEVICE_NOT_LUKS &&
	    (!ARG_SET(OPT_HEADER_ID) || !stat(ARG_STR(OPT_HEADER_ID), &st))) {
		device_ptr = ARG_SET(OPT_HEADER_ID) ? ARG_STR(OPT_HEADER_ID) : action_argv[0];
		r = check_broken_luks_signature(device_ptr);
		if (r < 0)
			return r;
	}

	/* check data device type/state */
	if (ARG_SET(OPT_HEADER_ID)) {
		device_ptr = cd ? crypt_get_device_name(cd) : action_argv[0];
		data_dev_st = check_luks_device(device_ptr);

		if (data_dev_st == DEVICE_INVALID)
			return -EINVAL;

		if (data_dev_st == DEVICE_LUKS2 || data_dev_st == DEVICE_LUKS1) {
			log_err(_("Device %s is already LUKS device. Aborting operation."),
				device_ptr);
			return -EINVAL;
		}

		if (data_dev_st == DEVICE_LUKS2_REENCRYPT || data_dev_st == DEVICE_LUKS1_UNUSABLE) {
			log_err(_("Device %s is already in LUKS reencryption. Aborting operation."),
				device_ptr);
			return -EINVAL;
		}

		r = check_broken_luks_signature(device_ptr);
		if (r < 0)
			return r;
	}

	if (!type)
		type = crypt_get_default_type();

	if (dev_st == DEVICE_LUKS1_UNUSABLE || isLUKS1(type)) {
		r = reencrypt_is_header_detached(ARG_STR(OPT_HEADER_ID), action_argv[0]);
		if (r < 0)
			return r;
		if (!r && !ARG_SET(OPT_REDUCE_DEVICE_SIZE_ID)) {
			log_err(_("Encryption without detached header (--header) is not possible without data device size reduction (--reduce-device-size)."));
			return -ENOTSUP;
		}
		return reencrypt_luks1(action_argv[0]);
	} else if (dev_st == DEVICE_NOT_LUKS) {
		r = encrypt_luks2_init(&encrypt_cd, action_argv[0], action_argc > 1 ? action_argv[1] : NULL);
		if (r < 0 || ARG_SET(OPT_INIT_ONLY_ID)) {
			crypt_free(encrypt_cd);
			return r;
		}
		cd = encrypt_cd;
		dev_st = DEVICE_LUKS2_REENCRYPT;
	} else if (dev_st == DEVICE_LUKS2_REENCRYPT &&
		   (r = reencrypt_luks2_load(cd, action_argv[0])) < 0)
		return r;

	if (dev_st != DEVICE_LUKS2_REENCRYPT)
		return -EINVAL;

	r = reencrypt_luks2_resume(cd);

	crypt_free(encrypt_cd);
	return r;
}

static int _decrypt(struct crypt_device **cd, enum device_status_info dev_st, const char *data_device)
{
	int r;
	struct stat st;
	bool export_header = false;

	assert(cd);

	if (dev_st == DEVICE_LUKS1 || dev_st == DEVICE_LUKS1_UNUSABLE)
		return reencrypt_luks1(data_device);

	/* header file does not exist, try loading device type from data device */
	if (dev_st == DEVICE_NOT_LUKS && ARG_SET(OPT_HEADER_ID) &&
	    (stat(ARG_STR(OPT_HEADER_ID), &st) < 0) && errno == ENOENT) {
		if (ARG_SET(OPT_ACTIVE_NAME_ID))
			dev_st = load_luks2_by_name(cd, ARG_STR(OPT_ACTIVE_NAME_ID), NULL);
		else
			dev_st = load_luks(cd, NULL, uuid_or_device(data_device));

		/*
		 * If data device is not LUKS2 report 'header is missing' error
		 * message user would get originally.
		 */
		if (dev_st != DEVICE_LUKS2) {
			log_err(_("Device %s does not exist or access denied."),
				ARG_STR(OPT_HEADER_ID));
			return -EINVAL;
		}

		export_header = true;
	}

	if (dev_st == DEVICE_LUKS2_REENCRYPT) {
		if ((r = reencrypt_luks2_load(*cd, data_device)) < 0)
			return r;
	} else if (dev_st == DEVICE_LUKS2) {
		if (!ARG_SET(OPT_HEADER_ID)) {
			log_err(_("LUKS2 decryption requires --header option."));
			return -EINVAL;
		}

		if (export_header)
			r = decrypt_luks2_datashift_init(cd, data_device, ARG_STR(OPT_HEADER_ID));
		else
			r = decrypt_luks2_init(*cd, data_device);

		if (r < 0 || ARG_SET(OPT_INIT_ONLY_ID))
			return r;
	} else if (dev_st == DEVICE_NOT_LUKS) {
		log_err(_("Device %s is not a valid LUKS device."),
			ARG_STR(OPT_HEADER_ID) ?: uuid_or_device(data_device));
		return -EINVAL;
	}

	r = reencrypt_luks2_resume(*cd);
	return r;
}

static int _reencrypt(struct crypt_device *cd, enum device_status_info dev_st, const char *data_device)
{
	int r;

	if (dev_st == DEVICE_LUKS1 || dev_st == DEVICE_LUKS1_UNUSABLE)
		return reencrypt_luks1(data_device);
	else if (dev_st == DEVICE_LUKS2_REENCRYPT) {
		if ((r = reencrypt_luks2_load(cd, data_device)) < 0)
			return r;
	} else if (dev_st == DEVICE_LUKS2) {
		r = reencrypt_luks2_init(cd, data_device);
		if (r < 0|| ARG_SET(OPT_INIT_ONLY_ID))
			return r;
	} else
		return -EINVAL;

	return reencrypt_luks2_resume(cd);
}

int reencrypt(int action_argc, const char **action_argv)
{
	enum device_status_info dev_st;
	int r = -EINVAL;
	struct crypt_device *cd = NULL;
	const char *type = luksType(device_type);

	if (action_argc < 1 && (!ARG_SET(OPT_ACTIVE_NAME_ID) || ARG_SET(OPT_ENCRYPT_ID))) {
		log_err(_("Command requires device as argument."));
		return r;
	}

	if (ARG_SET(OPT_ACTIVE_NAME_ID))
		dev_st = load_luks2_by_name(&cd, ARG_STR(OPT_ACTIVE_NAME_ID), ARG_STR(OPT_HEADER_ID));
	else
		dev_st = load_luks(&cd, ARG_STR(OPT_HEADER_ID), uuid_or_device(action_argv[0]));

	if (dev_st == DEVICE_INVALID)
		return r;

	if (dev_st == DEVICE_LUKS1 && isLUKS2(type)) {
		log_err(_("Conflicting versions. Device %s is LUKS1."),
			uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
		goto out;
	}

	if (dev_st == DEVICE_LUKS1_UNUSABLE && isLUKS2(type)) {
		log_err(_("Conflicting versions. Device %s is in LUKS1 reencryption."),
			uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
		goto out;
	}

	if (dev_st == DEVICE_LUKS2 && isLUKS1(type)) {
		log_err(_("Conflicting versions. Device %s is LUKS2."),
			uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
		goto out;
	}

	if (dev_st == DEVICE_LUKS2_REENCRYPT && isLUKS1(type)) {
		log_err(_("Conflicting versions. Device %s is in LUKS2 reencryption."),
			uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
		goto out;
	}

	if (dev_st == DEVICE_LUKS2_REENCRYPT && ARG_SET(OPT_INIT_ONLY_ID)) {
		log_err(_("LUKS2 reencryption already initialized. Aborting operation."));
		r = -EINVAL;
		goto out;
	}

	if (ARG_SET(OPT_RESUME_ONLY_ID) &&
	    (dev_st == DEVICE_LUKS2 || dev_st == DEVICE_LUKS1 || dev_st == DEVICE_NOT_LUKS)) {
		log_err(_("Device reencryption not in progress."));
		r = -EINVAL;
		goto out;
	}

	if (ARG_SET(OPT_ENCRYPT_ID))
		r = _encrypt(cd, type, dev_st, action_argc, action_argv);
	else if (ARG_SET(OPT_DECRYPT_ID))
		r = _decrypt(&cd, dev_st, action_argv[0]);
	else
		r = _reencrypt(cd, dev_st, action_argv[0]);

out:
	crypt_free(cd);
	return r;
}