Imported Upstream version 2.3.7
[platform/upstream/cryptsetup.git] / src / utils_reencrypt_luks1.c
1 /*
2  * cryptsetup - LUKS1 utility for offline re-encryption
3  *
4  * Copyright (C) 2012-2023 Red Hat, Inc. All rights reserved.
5  * Copyright (C) 2012-2023 Milan Broz
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include <sys/ioctl.h>
23 #include <linux/fs.h>
24 #include <uuid/uuid.h>
25
26 #include "cryptsetup.h"
27 #include "cryptsetup_args.h"
28 #include "utils_luks.h"
29
30 #define NO_UUID "cafecafe-cafe-cafe-cafe-cafecafeeeee"
31
32 extern int64_t data_shift;
33
34 #define MAX_SLOT 8
35
36 struct reenc_ctx {
37         char *device;
38         char *device_header;
39         char *device_uuid;
40         const char *type;
41         uint64_t device_size; /* overridden by parameter */
42         uint64_t device_size_new_real;
43         uint64_t device_size_org_real;
44         uint64_t device_offset;
45         uint64_t device_shift;
46         uint64_t data_offset;
47
48         bool stained;
49         bool in_progress;
50         enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
51         enum { REENCRYPT = 0, ENCRYPT = 1, DECRYPT = 2 } reencrypt_mode;
52
53         char header_file_org[PATH_MAX];
54         char header_file_new[PATH_MAX];
55         char log_file[PATH_MAX];
56
57         char crypt_path_org[PATH_MAX];
58         char crypt_path_new[PATH_MAX];
59         int log_fd;
60         char log_buf[SECTOR_SIZE];
61
62         struct {
63                 char *password;
64                 size_t passwordLen;
65         } p[MAX_SLOT];
66         int keyslot;
67
68         uint64_t resume_bytes;
69 };
70
71 char MAGIC[]   = {'L','U','K','S', 0xba, 0xbe};
72 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
73 int  MAGIC_L = 6;
74
75 typedef enum {
76         MAKE_UNUSABLE,
77         MAKE_USABLE,
78         CHECK_UNUSABLE,
79         CHECK_OPEN,
80 } header_magic;
81
82 static void _quiet_log(int level, const char *msg, void *usrptr)
83 {
84         if (!ARG_SET(OPT_DEBUG_ID))
85                 return;
86         tool_log(level, msg, usrptr);
87 }
88
89 static int alignment(int fd)
90 {
91         int alignment;
92
93         alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
94         if (alignment < 0)
95                 alignment = 4096;
96         return alignment;
97 }
98
99 static size_t pagesize(void)
100 {
101         long r = sysconf(_SC_PAGESIZE);
102         return r < 0 ? 4096 : (size_t)r;
103 }
104
105 static const char *hdr_device(const struct reenc_ctx *rc)
106 {
107         return rc->device_header ?: rc->device;
108 }
109
110 /* Depends on the first two fields of LUKS1 header format, magic and version */
111 static int device_check(struct reenc_ctx *rc, const char *device, header_magic set_magic, bool exclusive)
112 {
113         char *buf = NULL;
114         int r, devfd;
115         ssize_t s;
116         uint16_t version;
117         size_t buf_size = pagesize();
118         struct stat st;
119
120         if (stat(device, &st)) {
121                 log_err(_("Cannot open device %s."), device);
122                 return -EINVAL;
123         }
124
125         /* coverity[toctou] */
126         devfd = open(device, O_RDWR | ((S_ISBLK(st.st_mode) && exclusive) ? O_EXCL : 0)); /* lgtm[cpp/toctou-race-condition] */
127         if (devfd == -1) {
128                 if (errno == EBUSY) {
129                         log_err(_("Cannot exclusively open %s, device in use."),
130                                 device);
131                         return -EBUSY;
132                 }
133                 log_err(_("Cannot open device %s."), device);
134                 return -EINVAL;
135         }
136
137         if (set_magic == CHECK_OPEN) {
138                 r = 0;
139                 goto out;
140         }
141
142         if (posix_memalign((void *)&buf, alignment(devfd), buf_size)) {
143                 log_err(_("Allocation of aligned memory failed."));
144                 r = -ENOMEM;
145                 goto out;
146         }
147
148         s = read(devfd, buf, buf_size);
149         if (s < 0 || s != (ssize_t)buf_size) {
150                 log_err(_("Cannot read device %s."), device);
151                 r = -EIO;
152                 goto out;
153         }
154
155         /* Be sure that we do not process new version of header */
156         memcpy((void*)&version, &buf[MAGIC_L], sizeof(uint16_t));
157         version = be16_to_cpu(version);
158
159         if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L) &&
160             version == 1) {
161                 log_verbose(_("Marking LUKS1 device %s unusable."), device);
162                 memcpy(buf, NOMAGIC, MAGIC_L);
163                 r = 0;
164         } else if (set_magic == CHECK_UNUSABLE && version == 1) {
165                 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
166                 if (rc && !r)
167                         rc->device_uuid = strndup(&buf[0xa8], 40);
168                 goto out;
169         } else
170                 r = -EINVAL;
171
172         if (!r && version == 1) {
173                 if (lseek(devfd, 0, SEEK_SET) == -1)
174                         goto out;
175                 s = write(devfd, buf, buf_size);
176                 if (s < 0 || s != (ssize_t)buf_size || fsync(devfd) < 0) {
177                         log_err(_("Cannot write device %s."), device);
178                         r = -EIO;
179                 }
180                 if (rc && s > 0 && set_magic == MAKE_UNUSABLE)
181                         rc->stained = true;
182         }
183         if (r)
184                 log_dbg("LUKS signature check failed for %s.", device);
185 out:
186         if (buf)
187                 memset(buf, 0, buf_size);
188         free(buf);
189         close(devfd);
190         return r;
191 }
192
193 static int create_empty_header(const char *new_file)
194 {
195         int fd, r = 0;
196
197         log_dbg("Creating empty file %s of size 4096.", new_file);
198
199         /* coverity[toctou] */
200         fd = open(new_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR);
201         if (fd == -1 || posix_fallocate(fd, 0, 4096))
202                 r = -EINVAL;
203         if (fd >= 0)
204                 close(fd);
205
206         return r;
207 }
208
209 static int write_log(struct reenc_ctx *rc)
210 {
211         ssize_t r;
212
213         memset(rc->log_buf, 0, SECTOR_SIZE);
214         if (snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
215             "version = %d\nUUID = %s\ndirection = %d\nmode = %d\n"
216             "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
217             2, rc->device_uuid, rc->reencrypt_direction, rc->reencrypt_mode,
218             rc->device_offset, rc->device_shift) < 0)
219                 return -EINVAL;
220
221         if (lseek(rc->log_fd, 0, SEEK_SET) == -1)
222                 return -EIO;
223
224         r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE);
225         if (r < 0 || r != SECTOR_SIZE) {
226                 log_err(_("Cannot write reencryption log file."));
227                 return -EIO;
228         }
229
230         return 0;
231 }
232
233 static int parse_line_log(struct reenc_ctx *rc, const char *line)
234 {
235         uint64_t u64;
236         int i;
237         char s[64];
238
239         /* whole line is comment */
240         if (*line == '#')
241                 return 0;
242
243         if (sscanf(line, "version = %d", &i) == 1) {
244                 if (i < 1 || i > 2) {
245                         log_dbg("Log: Unexpected version = %i", i);
246                         return -EINVAL;
247                 }
248         } else if (sscanf(line, "UUID = %40s", s) == 1) {
249                 if (!rc->device_uuid || strcmp(rc->device_uuid, s)) {
250                         log_dbg("Log: Unexpected UUID %s", s);
251                         return -EINVAL;
252                 }
253         } else if (sscanf(line, "direction = %d", &i) == 1) {
254                 log_dbg("Log: direction = %i", i);
255                 rc->reencrypt_direction = i;
256         } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
257                 log_dbg("Log: offset = %" PRIu64, u64);
258                 rc->device_offset = u64;
259         } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
260                 log_dbg("Log: shift = %" PRIu64, u64);
261                 rc->device_shift = u64;
262         } else if (sscanf(line, "mode = %d", &i) == 1) { /* added in v2 */
263                 log_dbg("Log: mode = %i", i);
264                 rc->reencrypt_mode = i;
265                 if (rc->reencrypt_mode != REENCRYPT &&
266                     rc->reencrypt_mode != ENCRYPT &&
267                     rc->reencrypt_mode != DECRYPT)
268                         return -EINVAL;
269         } else
270                 return -EINVAL;
271
272         return 0;
273 }
274
275 static int parse_log(struct reenc_ctx *rc)
276 {
277         char *start, *end;
278         ssize_t s;
279
280         s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE);
281         if (s == -1) {
282                 log_err(_("Cannot read reencryption log file."));
283                 return -EIO;
284         }
285
286         rc->log_buf[SECTOR_SIZE - 1] = '\0';
287         start = rc->log_buf;
288         do {
289                 end = strchr(start, '\n');
290                 if (end) {
291                         *end++ = '\0';
292                         if (parse_line_log(rc, start)) {
293                                 log_err(_("Wrong log format."));
294                                 return -EINVAL;
295                         }
296                 }
297
298                 start = end;
299         } while (start);
300
301         return 0;
302 }
303
304 static void close_log(struct reenc_ctx *rc)
305 {
306         log_dbg("Closing LUKS reencryption log file %s.", rc->log_file);
307         if (rc->log_fd != -1)
308                 close(rc->log_fd);
309 }
310
311 static int open_log(struct reenc_ctx *rc)
312 {
313         int flags = ARG_SET(OPT_USE_FSYNC_ID) ? O_SYNC : 0;
314
315         rc->log_fd = open(rc->log_file, O_RDWR|O_EXCL|O_CREAT|flags, S_IRUSR|S_IWUSR);
316         if (rc->log_fd != -1) {
317                 log_dbg("Created LUKS reencryption log file %s.", rc->log_file);
318                 rc->stained = 0;
319         } else if (errno == EEXIST) {
320                 log_std(_("Log file %s exists, resuming reencryption.\n"), rc->log_file);
321                 rc->log_fd = open(rc->log_file, O_RDWR|flags);
322                 rc->in_progress = true;
323         }
324
325         if (rc->log_fd == -1)
326                 return -EINVAL;
327
328         if (!rc->in_progress && write_log(rc) < 0) {
329                 close_log(rc);
330                 return -EIO;
331         }
332
333         /* Be sure it is correct format */
334         return parse_log(rc);
335 }
336
337 static int activate_luks_headers(struct reenc_ctx *rc)
338 {
339         struct crypt_device *cd = NULL, *cd_new = NULL;
340         const char *pwd_old, *pwd_new, pwd_empty[] = "";
341         size_t pwd_old_len, pwd_new_len;
342         int r;
343
344         log_dbg("Activating LUKS devices from headers.");
345
346         /* Never use real password for empty header processing */
347         if (rc->reencrypt_mode == REENCRYPT) {
348                 pwd_old = rc->p[rc->keyslot].password;
349                 pwd_old_len = rc->p[rc->keyslot].passwordLen;
350                 pwd_new = pwd_old;
351                 pwd_new_len = pwd_old_len;
352         } else if (rc->reencrypt_mode == DECRYPT) {
353                 pwd_old = rc->p[rc->keyslot].password;
354                 pwd_old_len = rc->p[rc->keyslot].passwordLen;
355                 pwd_new = pwd_empty;
356                 pwd_new_len = 0;
357         } else if (rc->reencrypt_mode == ENCRYPT) {
358                 pwd_old = pwd_empty;
359                 pwd_old_len = 0;
360                 pwd_new = rc->p[rc->keyslot].password;
361                 pwd_new_len = rc->p[rc->keyslot].passwordLen;
362         } else
363                 return -EINVAL;
364
365         if ((r = crypt_init_data_device(&cd, rc->header_file_org, rc->device)) ||
366             (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
367                 goto out;
368
369         log_verbose(_("Activating temporary device using old LUKS header."));
370         if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org,
371                 ARG_INT32(OPT_KEY_SLOT_ID), pwd_old, pwd_old_len,
372                 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
373                 goto out;
374
375         if ((r = crypt_init_data_device(&cd_new, rc->header_file_new, rc->device)) ||
376             (r = crypt_load(cd_new, CRYPT_LUKS1, NULL)))
377                 goto out;
378
379         log_verbose(_("Activating temporary device using new LUKS header."));
380         if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new,
381                 ARG_INT32(OPT_KEY_SLOT_ID), pwd_new, pwd_new_len,
382                 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
383                 goto out;
384         r = 0;
385 out:
386         crypt_free(cd);
387         crypt_free(cd_new);
388         if (r < 0)
389                 log_err(_("Activation of temporary devices failed."));
390         return r;
391 }
392
393 static int create_new_keyslot(struct reenc_ctx *rc, int keyslot,
394                               struct crypt_device *cd_old,
395                               struct crypt_device *cd_new)
396 {
397         int r;
398         char *key = NULL;
399         size_t key_size;
400
401         if (cd_old && crypt_keyslot_status(cd_old, keyslot) == CRYPT_SLOT_UNBOUND) {
402                 key_size = 4096;
403                 key = crypt_safe_alloc(key_size);
404                 if (!key)
405                         return -ENOMEM;
406                 r = crypt_volume_key_get(cd_old, keyslot, key, &key_size,
407                         rc->p[keyslot].password, rc->p[keyslot].passwordLen);
408                 if (r == keyslot) {
409                         r = crypt_keyslot_add_by_key(cd_new, keyslot, key, key_size,
410                                 rc->p[keyslot].password, rc->p[keyslot].passwordLen,
411                                 CRYPT_VOLUME_KEY_NO_SEGMENT);
412                 } else
413                         r = -EINVAL;
414                 crypt_safe_free(key);
415         } else
416                 r = crypt_keyslot_add_by_volume_key(cd_new, keyslot, NULL, 0,
417                         rc->p[keyslot].password, rc->p[keyslot].passwordLen);
418
419         return r;
420 }
421
422 static int create_new_header(struct reenc_ctx *rc, struct crypt_device *cd_old,
423                              const char *cipher, const char *cipher_mode,
424                              const char *uuid,
425                              const char *key, int key_size,
426                              uint64_t metadata_size,
427                              uint64_t keyslots_size,
428                              void *params)
429 {
430         struct crypt_device *cd_new = NULL;
431         int i, r;
432
433         if ((r = crypt_init(&cd_new, rc->header_file_new)))
434                 goto out;
435
436         if (ARG_SET(OPT_USE_RANDOM_ID))
437                 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
438         else if (ARG_SET(OPT_USE_URANDOM_ID))
439                 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
440
441         r = set_pbkdf_params(cd_new, CRYPT_LUKS1);
442         if (r) {
443                 log_err(_("Failed to set pbkdf parameters."));
444                 goto out;
445         }
446
447         r = crypt_set_data_offset(cd_new, rc->data_offset);
448         if (r) {
449                 log_err(_("Failed to set data offset."));
450                 goto out;
451         }
452
453         r = crypt_set_metadata_size(cd_new, metadata_size, keyslots_size);
454         if (r) {
455                 log_err(_("Failed to set metadata size."));
456                 goto out;
457         }
458
459         r = crypt_format(cd_new, CRYPT_LUKS1, cipher, cipher_mode, uuid, key, key_size, params);
460         check_signal(&r);
461         if (r < 0)
462                 goto out;
463         log_verbose(_("New LUKS header for device %s created."), rc->device);
464
465         for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) {
466                 if (!rc->p[i].password)
467                         continue;
468
469                 r = create_new_keyslot(rc, i, cd_old, cd_new);
470                 check_signal(&r);
471                 if (r < 0)
472                         goto out;
473                 tools_keyslot_msg(r, CREATED);
474                 r = 0;
475         }
476 out:
477         crypt_free(cd_new);
478         return r;
479 }
480
481 static int backup_luks_headers(struct reenc_ctx *rc)
482 {
483         struct crypt_device *cd = NULL;
484         struct crypt_params_luks1 params = {0};
485         char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
486         char *key = NULL;
487         size_t key_size;
488         uint64_t mdata_size = 0, keyslots_size = 0;
489         int r;
490
491         log_dbg("Creating LUKS header backup for device %s.", hdr_device(rc));
492
493         if ((r = crypt_init(&cd, hdr_device(rc))) ||
494             (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
495                 goto out;
496
497         if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rc->header_file_org)))
498                 goto out;
499
500         log_verbose(_("%s header backup of device %s created."), "LUKS1", rc->device);
501
502         /* For decrypt, new header will be fake one, so we are done here. */
503         if (rc->reencrypt_mode == DECRYPT)
504                 goto out;
505
506         rc->data_offset = crypt_get_data_offset(cd) + ROUND_SECTOR(ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID));
507
508         if ((r = create_empty_header(rc->header_file_new)))
509                 goto out;
510
511         params.hash = ARG_STR(OPT_HASH_ID) ?: DEFAULT_LUKS1_HASH;
512         params.data_device = rc->device;
513
514         if (ARG_SET(OPT_CIPHER_ID)) {
515                 r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID), cipher, NULL, cipher_mode);
516                 if (r < 0) {
517                         log_err(_("No known cipher specification pattern detected."));
518                         goto out;
519                 }
520         }
521
522         key_size = ARG_SET(OPT_KEY_SIZE_ID) ? ARG_UINT32(OPT_KEY_SIZE_ID) / 8 : (uint32_t)crypt_get_volume_key_size(cd);
523
524         if (ARG_SET(OPT_KEEP_KEY_ID)) {
525                 log_dbg("Keeping key from old header.");
526                 key_size = crypt_get_volume_key_size(cd);
527                 key = crypt_safe_alloc(key_size);
528                 if (!key) {
529                         r = -ENOMEM;
530                         goto out;
531                 }
532                 r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, key, &key_size,
533                         rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
534         } else if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) {
535                 log_dbg("Loading new key from file.");
536                 r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &key, key_size);
537         }
538
539         if (r < 0)
540                 goto out;
541
542         r = create_new_header(rc, cd,
543                 ARG_SET(OPT_CIPHER_ID) ? cipher : crypt_get_cipher(cd),
544                 ARG_SET(OPT_CIPHER_ID) ? cipher_mode : crypt_get_cipher_mode(cd),
545                 crypt_get_uuid(cd),
546                 key,
547                 key_size,
548                 mdata_size,
549                 keyslots_size,
550                 (void*)&params);
551
552 out:
553         crypt_free(cd);
554         crypt_safe_free(key);
555         if (r)
556                 log_err(_("Creation of LUKS backup headers failed."));
557         return r;
558 }
559
560 /* Create fake header for original device */
561 static int backup_fake_header(struct reenc_ctx *rc)
562 {
563         struct crypt_device *cd_new = NULL;
564         struct crypt_params_luks1 params = {0};
565         char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
566         const char *header_file_fake;
567         int r;
568
569         log_dbg("Creating fake (cipher_null) header for %s device.",
570                 (rc->reencrypt_mode == DECRYPT) ? "new" : "original");
571
572         header_file_fake = (rc->reencrypt_mode == DECRYPT) ? rc->header_file_new : rc->header_file_org;
573
574         if (!ARG_SET(OPT_KEY_SIZE_ID))
575                 ARG_SET_UINT32(OPT_KEY_SIZE_ID, DEFAULT_LUKS1_KEYBITS);
576
577         if (ARG_SET(OPT_CIPHER_ID)) {
578                 r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID), cipher, NULL, cipher_mode);
579                 if (r < 0) {
580                         log_err(_("No known cipher specification pattern detected."));
581                         goto out;
582                 }
583         }
584
585         r = create_empty_header(header_file_fake);
586         if (r < 0)
587                 return r;
588
589         params.hash = ARG_STR(OPT_HASH_ID) ?: DEFAULT_LUKS1_HASH;
590         params.data_alignment = 0;
591         params.data_device = rc->device;
592
593         r = crypt_init(&cd_new, header_file_fake);
594         if (r < 0)
595                 return r;
596
597         r = crypt_format(cd_new, CRYPT_LUKS1, "cipher_null", "ecb",
598                          NO_UUID, NULL, ARG_UINT32(OPT_KEY_SIZE_ID) / 8, &params);
599         check_signal(&r);
600         if (r < 0)
601                 goto out;
602
603         r = crypt_keyslot_add_by_volume_key(cd_new, rc->keyslot, NULL, 0,
604                         rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
605         check_signal(&r);
606         if (r < 0)
607                 goto out;
608
609         /* The real header is backup header created in backup_luks_headers() */
610         if (rc->reencrypt_mode == DECRYPT) {
611                 r = 0;
612                 goto out;
613         }
614
615         r = create_empty_header(rc->header_file_new);
616         if (r < 0)
617                 goto out;
618
619         params.data_alignment = ROUND_SECTOR(ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID));
620         r = create_new_header(rc, NULL,
621                 ARG_SET(OPT_CIPHER_ID) ? cipher : DEFAULT_LUKS1_CIPHER,
622                 ARG_SET(OPT_CIPHER_ID) ? cipher_mode : DEFAULT_LUKS1_MODE,
623                 NULL, NULL,
624                 ARG_UINT32(OPT_KEY_SIZE_ID) / 8,
625                 0,
626                 0,
627                 (void*)&params);
628 out:
629         crypt_free(cd_new);
630         return r;
631 }
632
633 static void remove_headers(struct reenc_ctx *rc)
634 {
635         struct crypt_device *cd = NULL;
636
637         log_dbg("Removing headers.");
638
639         if (crypt_init(&cd, NULL))
640                 return;
641         crypt_set_log_callback(cd, _quiet_log, NULL);
642         if (*rc->header_file_org)
643                 (void)crypt_deactivate(cd, rc->header_file_org);
644         if (*rc->header_file_new)
645                 (void)crypt_deactivate(cd, rc->header_file_new);
646         crypt_free(cd);
647 }
648
649 static int restore_luks_header(struct reenc_ctx *rc)
650 {
651         struct stat st;
652         struct crypt_device *cd = NULL;
653         int fd, r;
654
655         log_dbg("Restoring header for %s from %s.", hdr_device(rc), rc->header_file_new);
656
657         /*
658          * For new encryption and new detached header in file just move it.
659          * For existing file try to ensure we have preallocated space for restore.
660          */
661         if (ARG_SET(OPT_ENCRYPT_ID) && rc->device_header) {
662                 r = stat(rc->device_header, &st);
663                 if (r == -1) {
664                         r = rename(rc->header_file_new, rc->device_header);
665                         goto out;
666                 } else if ((st.st_mode & S_IFMT) == S_IFREG &&
667                         stat(rc->header_file_new, &st) != -1) {
668                         /* coverity[toctou] */
669                         fd = open(rc->device_header, O_WRONLY);
670                         if (fd != -1) {
671                                 if (posix_fallocate(fd, 0, st.st_size)) {};
672                                 close(fd);
673                         }
674                 }
675         }
676
677         r = crypt_init(&cd, hdr_device(rc));
678         if (r == 0) {
679                 r = crypt_header_restore(cd, CRYPT_LUKS1, rc->header_file_new);
680         }
681
682         crypt_free(cd);
683 out:
684         if (r)
685                 log_err(_("Cannot restore %s header on device %s."), "LUKS1", hdr_device(rc));
686         else {
687                 log_verbose(_("%s header on device %s restored."), "LUKS1", hdr_device(rc));
688                 rc->stained = false;
689         }
690         return r;
691 }
692
693 static ssize_t read_buf(int fd, void *buf, size_t count)
694 {
695         size_t read_size = 0;
696         ssize_t s;
697
698         do {
699                 /* This expects that partial read is aligned in buffer */
700                 s = read(fd, buf, count - read_size);
701                 if (s == -1 && errno != EINTR)
702                         return s;
703                 if (s == 0)
704                         return (ssize_t)read_size;
705                 if (s > 0) {
706                         if (s != (ssize_t)count)
707                                 log_dbg("Partial read %zd / %zu.", s, count);
708                         read_size += (size_t)s;
709                         buf = (uint8_t*)buf + s;
710                 }
711         } while (read_size != count);
712
713         return (ssize_t)count;
714 }
715
716 static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new,
717                              size_t block_size, void *buf, uint64_t *bytes)
718 {
719         ssize_t s1, s2;
720         int r = -EIO;
721         char *backing_file = NULL;
722         struct tools_progress_params prog_parms = {
723                 .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID),
724                 .batch_mode = ARG_SET(OPT_BATCH_MODE_ID),
725                 .json_output = ARG_SET(OPT_PROGRESS_JSON_ID),
726                 .interrupt_message = _("\nReencryption interrupted."),
727                 .device = tools_get_device_name(rc->device, &backing_file)
728         };
729
730         log_dbg("Reencrypting in forward direction.");
731
732         if (lseek(fd_old, rc->device_offset, SEEK_SET) < 0 ||
733             lseek(fd_new, rc->device_offset, SEEK_SET) < 0) {
734                 log_err(_("Cannot seek to device offset."));
735                 goto out;
736         }
737
738         rc->resume_bytes = *bytes = rc->device_offset;
739
740         tools_progress(rc->device_size, *bytes, &prog_parms);
741
742         if (write_log(rc) < 0)
743                 goto out;
744
745         while (!quit && rc->device_offset < rc->device_size) {
746                 if ((rc->device_size - rc->device_offset) < (uint64_t)block_size)
747                         block_size = rc->device_size - rc->device_offset;
748                 s1 = read_buf(fd_old, buf, block_size);
749                 if (s1 < 0 || ((size_t)s1 != block_size &&
750                     (rc->device_offset + s1) != rc->device_size)) {
751                         log_dbg("Read error, expecting %zu, got %zd.",
752                                 block_size, s1);
753                         goto out;
754                 }
755
756                 /* If device_size is forced, never write more than limit */
757                 if ((s1 + rc->device_offset) > rc->device_size)
758                         s1 = rc->device_size - rc->device_offset;
759
760                 s2 = write(fd_new, buf, s1);
761                 if (s2 < 0) {
762                         log_dbg("Write error, expecting %zu, got %zd.",
763                                 block_size, s2);
764                         goto out;
765                 }
766
767                 rc->device_offset += s1;
768                 if (ARG_SET(OPT_WRITE_LOG_ID) && write_log(rc) < 0)
769                         goto out;
770
771                 if (ARG_SET(OPT_USE_FSYNC_ID) && fsync(fd_new) < 0) {
772                         log_dbg("Write error, fsync.");
773                         goto out;
774                 }
775
776                 *bytes += (uint64_t)s2;
777
778                 tools_progress(rc->device_size, *bytes, &prog_parms);
779         }
780
781         r = 0;
782 out:
783         free(backing_file);
784         return quit ? -EAGAIN : r;
785 }
786
787 static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new,
788                               size_t block_size, void *buf, uint64_t *bytes)
789 {
790         ssize_t s1, s2, working_block;
791         off_t working_offset;
792         int r = -EIO;
793         char *backing_file = NULL;
794         struct tools_progress_params prog_parms = {
795                 .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID),
796                 .batch_mode = ARG_SET(OPT_BATCH_MODE_ID),
797                 .json_output = ARG_SET(OPT_PROGRESS_JSON_ID),
798                 .interrupt_message = _("\nReencryption interrupted."),
799                 .device = tools_get_device_name(rc->device, &backing_file)
800         };
801
802         log_dbg("Reencrypting in backward direction.");
803
804         if (!rc->in_progress) {
805                 rc->device_offset = rc->device_size;
806                 rc->resume_bytes = 0;
807                 *bytes = 0;
808         } else {
809                 rc->resume_bytes = rc->device_size - rc->device_offset;
810                 *bytes = rc->resume_bytes;
811         }
812
813         tools_progress(rc->device_size, *bytes, &prog_parms);
814
815         if (write_log(rc) < 0)
816                 goto out;
817
818         /* dirty the device during ENCRYPT mode */
819         rc->stained = true;
820
821         while (!quit && rc->device_offset) {
822                 if (rc->device_offset < block_size) {
823                         working_offset = 0;
824                         working_block = rc->device_offset;
825                 } else {
826                         working_offset = rc->device_offset - block_size;
827                         working_block = block_size;
828                 }
829
830                 if (lseek(fd_old, working_offset, SEEK_SET) < 0 ||
831                     lseek(fd_new, working_offset, SEEK_SET) < 0) {
832                         log_err(_("Cannot seek to device offset."));
833                         goto out;
834                 }
835
836                 s1 = read_buf(fd_old, buf, working_block);
837                 if (s1 < 0 || (s1 != working_block)) {
838                         log_dbg("Read error, expecting %zu, got %zd.",
839                                 block_size, s1);
840                         goto out;
841                 }
842
843                 s2 = write(fd_new, buf, working_block);
844                 if (s2 < 0) {
845                         log_dbg("Write error, expecting %zu, got %zd.",
846                                 block_size, s2);
847                         goto out;
848                 }
849
850                 rc->device_offset -= s1;
851                 if (ARG_SET(OPT_WRITE_LOG_ID) && write_log(rc) < 0)
852                         goto out;
853
854                 if (ARG_SET(OPT_USE_FSYNC_ID) && fsync(fd_new) < 0) {
855                         log_dbg("Write error, fsync.");
856                         goto out;
857                 }
858
859                 *bytes += (uint64_t)s2;
860
861                 tools_progress(rc->device_size, *bytes, &prog_parms);
862         }
863
864         r = 0;
865 out:
866         free(backing_file);
867         return quit ? -EAGAIN : r;
868 }
869
870 static void zero_rest_of_device(int fd, size_t block_size, void *buf,
871                                 uint64_t *bytes, uint64_t offset)
872 {
873         ssize_t s1, s2;
874
875         log_dbg("Zeroing rest of device.");
876
877         if (lseek(fd, offset, SEEK_SET) < 0) {
878                 log_dbg("Cannot seek to device offset.");
879                 return;
880         }
881
882         memset(buf, 0, block_size);
883         s1 = block_size;
884
885         while (!quit && *bytes) {
886                 if (*bytes < (uint64_t)s1)
887                         s1 = *bytes;
888
889                 s2 = write(fd, buf, s1);
890                 if (s2 != s1) {
891                         log_dbg("Write error, expecting %zd, got %zd.",
892                                 s1, s2);
893                         return;
894                 }
895
896                 if (ARG_SET(OPT_USE_FSYNC_ID) && fsync(fd) < 0) {
897                         log_dbg("Write error, fsync.");
898                         return;
899                 }
900
901                 *bytes -= s2;
902         }
903 }
904
905 static int copy_data(struct reenc_ctx *rc)
906 {
907         size_t block_size = ARG_UINT32(OPT_BLOCK_SIZE_ID) * 1024 * 1024;
908         int fd_old = -1, fd_new = -1;
909         int r = -EINVAL;
910         void *buf = NULL;
911         uint64_t bytes = 0;
912
913         log_dbg("Data copy preparation.");
914
915         fd_old = open(rc->crypt_path_org, O_RDONLY | (ARG_SET(OPT_USE_DIRECTIO_ID) ? O_DIRECT : 0));
916         if (fd_old == -1) {
917                 log_err(_("Cannot open temporary LUKS device."));
918                 goto out;
919         }
920
921         fd_new = open(rc->crypt_path_new, O_WRONLY | (ARG_SET(OPT_USE_DIRECTIO_ID) ? O_DIRECT : 0));
922         if (fd_new == -1) {
923                 log_err(_("Cannot open temporary LUKS device."));
924                 goto out;
925         }
926
927         if (ioctl(fd_old, BLKGETSIZE64, &rc->device_size_org_real) < 0) {
928                 log_err(_("Cannot get device size."));
929                 goto out;
930         }
931
932         if (ioctl(fd_new, BLKGETSIZE64, &rc->device_size_new_real) < 0) {
933                 log_err(_("Cannot get device size."));
934                 goto out;
935         }
936
937         if (ARG_SET(OPT_DEVICE_SIZE_ID))
938                 rc->device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID);
939         else if (rc->reencrypt_mode == DECRYPT)
940                 rc->device_size = rc->device_size_org_real;
941         else
942                 rc->device_size = rc->device_size_new_real;
943
944         if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
945                 log_err(_("Allocation of aligned memory failed."));
946                 r = -ENOMEM;
947                 goto out;
948         }
949
950         set_int_handler(0);
951
952         if (rc->reencrypt_direction == FORWARD)
953                 r = copy_data_forward(rc, fd_old, fd_new, block_size, buf, &bytes);
954         else
955                 r = copy_data_backward(rc, fd_old, fd_new, block_size, buf, &bytes);
956
957         /* Zero (wipe) rest of now plain-only device when decrypting.
958          * (To not leave any sign of encryption here.) */
959         if (!r && rc->reencrypt_mode == DECRYPT &&
960             rc->device_size_new_real > rc->device_size_org_real) {
961                 bytes = rc->device_size_new_real - rc->device_size_org_real;
962                 zero_rest_of_device(fd_new, block_size, buf, &bytes, rc->device_size_org_real);
963         }
964
965         set_int_block(1);
966
967         if (r < 0 && r != -EAGAIN)
968                 log_err(_("IO error during reencryption."));
969
970         (void)write_log(rc);
971 out:
972         if (fd_old != -1)
973                 close(fd_old);
974         if (fd_new != -1)
975                 close(fd_new);
976         free(buf);
977         return r;
978 }
979
980 static int initialize_uuid(struct reenc_ctx *rc)
981 {
982         struct crypt_device *cd = NULL;
983         int r;
984         uuid_t device_uuid;
985
986         log_dbg("Initialising UUID.");
987
988         if (ARG_SET(OPT_ENCRYPT_ID)) {
989                 rc->device_uuid = strdup(NO_UUID);
990                 return 0;
991         }
992
993         if (ARG_SET(OPT_DECRYPT_ID) && ARG_SET(OPT_UUID_ID)) {
994                 r = uuid_parse(ARG_STR(OPT_UUID_ID), device_uuid);
995                 if (!r)
996                         rc->device_uuid = strdup(ARG_STR(OPT_UUID_ID));
997                 else
998                         log_err(_("Provided UUID is invalid."));
999
1000                 return r;
1001         }
1002
1003         /* Try to load LUKS from device */
1004         if ((r = crypt_init(&cd, hdr_device(rc))))
1005                 return r;
1006         crypt_set_log_callback(cd, _quiet_log, NULL);
1007         r = crypt_load(cd, CRYPT_LUKS1, NULL);
1008         if (!r)
1009                 rc->device_uuid = strdup(crypt_get_uuid(cd));
1010         else
1011                 /* Reencryption already in progress - magic header? */
1012                 r = device_check(rc, hdr_device(rc), CHECK_UNUSABLE, true);
1013
1014         crypt_free(cd);
1015         return r;
1016 }
1017
1018 static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd,
1019                             const char *msg, int slot_to_check, int check, int verify)
1020 {
1021         crypt_keyslot_info ki;
1022         char *password;
1023         int r = -EINVAL, retry_count;
1024         size_t passwordLen;
1025
1026         /* mode ENCRYPT call this without header */
1027         if (cd && slot_to_check != CRYPT_ANY_SLOT) {
1028                 ki = crypt_keyslot_status(cd, slot_to_check);
1029                 if (ki < CRYPT_SLOT_ACTIVE)
1030                         return -ENOENT;
1031         } else
1032                 ki = CRYPT_SLOT_ACTIVE;
1033
1034         retry_count = ARG_UINT32(OPT_TRIES_ID) ?: 1;
1035         while (retry_count--) {
1036                 r = tools_get_key(msg,  &password, &passwordLen, 0, 0,
1037                                   NULL /*opt_key_file*/, 0, verify, 0 /*pwquality*/, cd);
1038                 if (r < 0)
1039                         return r;
1040                 if (quit) {
1041                         crypt_safe_free(password);
1042                         password = NULL;
1043                         passwordLen = 0;
1044                         return -EAGAIN;
1045                 }
1046
1047                 if (check)
1048                         r = crypt_activate_by_passphrase(cd, NULL, slot_to_check,
1049                                 password, passwordLen, CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY);
1050                 else
1051                         r = (slot_to_check == CRYPT_ANY_SLOT) ? 0 : slot_to_check;
1052
1053                 if (r < 0) {
1054                         crypt_safe_free(password);
1055                         password = NULL;
1056                         passwordLen = 0;
1057                 }
1058                 if (r < 0 && r != -EPERM)
1059                         return r;
1060
1061                 if (r >= 0) {
1062                         tools_keyslot_msg(r, UNLOCKED);
1063                         rc->p[r].password = password;
1064                         rc->p[r].passwordLen = passwordLen;
1065                         if (ki != CRYPT_SLOT_UNBOUND)
1066                                 rc->keyslot = r;
1067                         break;
1068                 }
1069                 tools_passphrase_msg(r);
1070         }
1071
1072         password = NULL;
1073         passwordLen = 0;
1074
1075         return r;
1076 }
1077
1078 static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check)
1079 {
1080         char *password;
1081         int r;
1082         size_t passwordLen;
1083
1084         r = tools_get_key(NULL, &password, &passwordLen, ARG_UINT64(OPT_KEYFILE_OFFSET_ID),
1085                           ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), 0, 0, 0, cd);
1086         if (r < 0)
1087                 return r;
1088
1089         /* mode ENCRYPT call this without header */
1090         if (cd) {
1091                 r = crypt_activate_by_passphrase(cd, NULL, slot_check, password,
1092                                                  passwordLen, 0);
1093
1094                 /*
1095                  * Allow keyslot only if it is last slot or if user explicitly
1096                  * specify which slot to use (IOW others will be disabled).
1097                  */
1098                 if (r >= 0 && ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT &&
1099                     crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
1100                         log_err(_("Key file can be used only with --key-slot or with "
1101                                   "exactly one key slot active."));
1102                         r = -EINVAL;
1103                 }
1104         } else {
1105                 r = slot_check == CRYPT_ANY_SLOT ? 0 : slot_check;
1106         }
1107
1108         if (r < 0) {
1109                 crypt_safe_free(password);
1110                 tools_passphrase_msg(r);
1111         } else {
1112                 rc->keyslot = r;
1113                 rc->p[r].password = password;
1114                 rc->p[r].passwordLen = passwordLen;
1115         }
1116
1117         password = NULL;
1118         passwordLen = 0;
1119
1120         return r;
1121 }
1122
1123 static int initialize_passphrase(struct reenc_ctx *rc, const char *device)
1124 {
1125         struct crypt_device *cd = NULL;
1126         char msg[256];
1127         int i, r;
1128
1129         log_dbg("Passphrases initialization.");
1130
1131         if (rc->reencrypt_mode == ENCRYPT && !rc->in_progress) {
1132                 if (ARG_SET(OPT_KEY_FILE_ID))
1133                         r = init_keyfile(rc, NULL, ARG_INT32(OPT_KEY_SLOT_ID));
1134                 else
1135                         r = init_passphrase1(rc, NULL, _("Enter new passphrase: "), ARG_INT32(OPT_KEY_SLOT_ID), 0, 1);
1136                 return r > 0 ? 0 : r;
1137         }
1138
1139         if ((r = crypt_init_data_device(&cd, device, rc->device)) ||
1140             (r = crypt_load(cd, CRYPT_LUKS1, NULL))) {
1141                 crypt_free(cd);
1142                 return r;
1143         }
1144
1145         if (ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT)
1146                 snprintf(msg, sizeof(msg),
1147                          _("Enter passphrase for key slot %d: "), ARG_INT32(OPT_KEY_SLOT_ID));
1148         else
1149                 snprintf(msg, sizeof(msg), _("Enter any existing passphrase: "));
1150
1151         if (ARG_SET(OPT_KEY_FILE_ID)) {
1152                 r = init_keyfile(rc, cd, ARG_INT32(OPT_KEY_SLOT_ID));
1153         } else if (rc->in_progress ||
1154                    ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT ||
1155                    rc->reencrypt_mode == DECRYPT) {
1156                 r = init_passphrase1(rc, cd, msg, ARG_INT32(OPT_KEY_SLOT_ID), 1, 0);
1157         } else for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) {
1158                 snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %d: "), i);
1159                 r = init_passphrase1(rc, cd, msg, i, 1, 0);
1160                 if (r == -ENOENT) {
1161                         r = 0;
1162                         continue;
1163                 }
1164                 if (r < 0)
1165                         break;
1166         }
1167
1168         crypt_free(cd);
1169         return r > 0 ? 0 : r;
1170 }
1171
1172 static int initialize_context(struct reenc_ctx *rc, const char *device)
1173 {
1174         log_dbg("Initialising reencryption context.");
1175
1176         memset(rc, 0, sizeof(*rc));
1177
1178         rc->in_progress = false;
1179         rc->stained = true;
1180         rc->log_fd = -1;
1181
1182         if (!(rc->device = strndup(device, PATH_MAX)))
1183                 return -ENOMEM;
1184
1185         if (ARG_SET(OPT_HEADER_ID) && !(rc->device_header = strndup(ARG_STR(OPT_HEADER_ID), PATH_MAX)))
1186                 return -ENOMEM;
1187
1188         if (device_check(rc, rc->device, CHECK_OPEN, true) < 0)
1189                 return -EINVAL;
1190
1191         if (initialize_uuid(rc)) {
1192                 log_err(_("Device %s is not a valid LUKS device."), device);
1193                 return -EINVAL;
1194         }
1195
1196         if (ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT &&
1197             ARG_INT32(OPT_KEY_SLOT_ID) >= crypt_keyslot_max(CRYPT_LUKS1)) {
1198                 log_err(_("Key slot is invalid."));
1199                 return -EINVAL;
1200         }
1201
1202         /* Prepare device names */
1203         if (snprintf(rc->log_file, PATH_MAX,
1204                      "LUKS-%s.log", rc->device_uuid) < 0)
1205                 return -ENOMEM;
1206         if (snprintf(rc->header_file_org, PATH_MAX,
1207                      "LUKS-%s.org", rc->device_uuid) < 0)
1208                 return -ENOMEM;
1209         if (snprintf(rc->header_file_new, PATH_MAX,
1210                      "LUKS-%s.new", rc->device_uuid) < 0)
1211                 return -ENOMEM;
1212
1213         /* Paths to encrypted devices */
1214         if (snprintf(rc->crypt_path_org, PATH_MAX,
1215                      "%s/%s", crypt_get_dir(), rc->header_file_org) < 0)
1216                 return -ENOMEM;
1217         if (snprintf(rc->crypt_path_new, PATH_MAX,
1218                      "%s/%s", crypt_get_dir(), rc->header_file_new) < 0)
1219                 return -ENOMEM;
1220
1221         remove_headers(rc);
1222
1223         if (open_log(rc) < 0) {
1224                 log_err(_("Cannot open reencryption log file."));
1225                 return -EINVAL;
1226         }
1227
1228         if (!rc->in_progress) {
1229                 if (ARG_SET(OPT_UUID_ID)) {
1230                         log_err(_("No decryption in progress, provided UUID can "
1231                         "be used only to resume suspended decryption process."));
1232                         return -EINVAL;
1233                 }
1234
1235                 if (!ARG_SET(OPT_REDUCE_DEVICE_SIZE_ID))
1236                         rc->reencrypt_direction = FORWARD;
1237                 else {
1238                         rc->reencrypt_direction = BACKWARD;
1239                         rc->device_offset = (uint64_t)~0;
1240                 }
1241
1242                 if (ARG_SET(OPT_ENCRYPT_ID))
1243                         rc->reencrypt_mode = ENCRYPT;
1244                 else if (ARG_SET(OPT_DECRYPT_ID))
1245                         rc->reencrypt_mode = DECRYPT;
1246                 else
1247                         rc->reencrypt_mode = REENCRYPT;
1248         }
1249
1250         return 0;
1251 }
1252
1253 static void destroy_context(struct reenc_ctx *rc)
1254 {
1255         int i;
1256
1257         log_dbg("Destroying reencryption context.");
1258
1259         close_log(rc);
1260         remove_headers(rc);
1261
1262         if (!rc->stained) {
1263                 unlink(rc->log_file);
1264                 unlink(rc->header_file_org);
1265                 unlink(rc->header_file_new);
1266         }
1267
1268         for (i = 0; i < MAX_SLOT; i++)
1269                 crypt_safe_free(rc->p[i].password);
1270
1271         free(rc->device);
1272         free(rc->device_header);
1273         free(rc->device_uuid);
1274 }
1275
1276 int reencrypt_luks1(const char *device)
1277 {
1278         int r = -EINVAL;
1279         struct reenc_ctx *rc;
1280
1281         rc = malloc(sizeof(*rc));
1282         if (!rc)
1283                 return -ENOMEM;
1284
1285         if (!ARG_SET(OPT_BATCH_MODE_ID))
1286                 log_verbose(_("Reencryption will change: %s%s%s%s%s%s."),
1287                         ARG_SET(OPT_KEEP_KEY_ID) ? "" :  _("volume key"),
1288                         (!ARG_SET(OPT_KEEP_KEY_ID) && ARG_SET(OPT_HASH_ID)) ? ", " : "",
1289                         ARG_SET(OPT_HASH_ID) ? _("set hash to ") : "", ARG_STR(OPT_HASH_ID) ?: "",
1290                         ARG_SET(OPT_CIPHER_ID) ? _(", set cipher to "): "", ARG_STR(OPT_CIPHER_ID) ?: "");
1291         /* FIXME: block all non pbkdf2 pkdfs */
1292
1293         set_int_handler(0);
1294
1295         if (initialize_context(rc, device))
1296                 goto out;
1297
1298         log_dbg("Running reencryption.");
1299
1300         if (!rc->in_progress) {
1301                 if ((r = initialize_passphrase(rc, hdr_device(rc))))
1302                         goto out;
1303
1304                 log_dbg("Storing backup of LUKS headers.");
1305                 if (rc->reencrypt_mode == ENCRYPT) {
1306                         /* Create fake header for existing device */
1307                         if ((r = backup_fake_header(rc)))
1308                                 goto out;
1309                 } else {
1310                         if ((r = backup_luks_headers(rc)))
1311                                 goto out;
1312                         /* Create fake header for decrypted device */
1313                         if (rc->reencrypt_mode == DECRYPT &&
1314                             (r = backup_fake_header(rc)))
1315                                 goto out;
1316                         if ((r = device_check(rc, hdr_device(rc), MAKE_UNUSABLE, true)))
1317                                 goto out;
1318                 }
1319         } else {
1320                 if ((r = initialize_passphrase(rc, ARG_SET(OPT_DECRYPT_ID) ? rc->header_file_org : rc->header_file_new)))
1321                         goto out;
1322         }
1323
1324         if (!ARG_SET(OPT_KEEP_KEY_ID)) {
1325                 log_dbg("Running data area reencryption.");
1326                 if ((r = activate_luks_headers(rc)))
1327                         goto out;
1328
1329                 if ((r = copy_data(rc)))
1330                         goto out;
1331         } else
1332                 log_dbg("Keeping existing key, skipping data area reencryption.");
1333
1334         // FIXME: fix error path above to not skip this
1335         if (rc->reencrypt_mode != DECRYPT)
1336                 r = restore_luks_header(rc);
1337         else
1338                 rc->stained = false;
1339 out:
1340         destroy_context(rc);
1341         free(rc);
1342
1343         return r;
1344 }
1345
1346 int reencrypt_luks1_in_progress(const char *device)
1347 {
1348         struct stat st;
1349
1350         if (stat(device, &st) || (size_t)st.st_size < pagesize())
1351                 return -EINVAL;
1352
1353         return device_check(NULL, device, CHECK_UNUSABLE, false);
1354 }