Fixed the build error for riscv64 arch using gcc 13
[platform/upstream/cryptsetup.git] / src / cryptsetup_reencrypt.c
1 /*
2  * cryptsetup-reencrypt - crypt utility for offline re-encryption
3  *
4  * Copyright (C) 2012-2021 Red Hat, Inc. All rights reserved.
5  * Copyright (C) 2012-2021 Milan Broz All rights reserved.
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 "cryptsetup.h"
23 #include <sys/ioctl.h>
24 #include <linux/fs.h>
25 #include <arpa/inet.h>
26 #include <uuid/uuid.h>
27
28 #define PACKAGE_REENC "cryptsetup-reencrypt"
29
30 #define NO_UUID "cafecafe-cafe-cafe-cafe-cafecafeeeee"
31
32 static char *opt_cipher = NULL;
33 static char *opt_hash = NULL;
34 static char *opt_key_file = NULL;
35 static char *opt_master_key_file = NULL;
36 static char *opt_uuid = NULL;
37 static char *opt_type = NULL;
38 static char *opt_pbkdf = NULL;
39 static char *opt_header_device = NULL;
40
41 /* helper strings converted to uint64_t later */
42 static char *opt_reduce_size_str = NULL;
43 static char *opt_device_size_str = NULL;
44
45 static uint64_t opt_reduce_size = 0;
46 static uint64_t opt_device_size = 0;
47
48 static long opt_keyfile_size = 0;
49 static long opt_keyfile_offset = 0;
50 static int opt_iteration_time = 0;
51 static long opt_pbkdf_memory = DEFAULT_LUKS2_MEMORY_KB;
52 static long opt_pbkdf_parallel = DEFAULT_LUKS2_PARALLEL_THREADS;
53 static long opt_pbkdf_iterations = 0;
54 static int opt_random = 0;
55 static int opt_urandom = 0;
56 static int opt_bsize = 4;
57 static int opt_directio = 0;
58 static int opt_fsync = 0;
59 static int opt_write_log = 0;
60 static int opt_tries = 3;
61 static int opt_key_slot = CRYPT_ANY_SLOT;
62 static int opt_key_size = 0;
63 static int opt_new = 0;
64 static int opt_keep_key = 0;
65 static int opt_decrypt = 0;
66
67 static const char **action_argv;
68
69 static const char *set_pbkdf = NULL;
70
71 #define MAX_SLOT 32
72 #define MAX_TOKEN 32
73 struct reenc_ctx {
74         char *device;
75         char *device_header;
76         char *device_uuid;
77         const char *type;
78         uint64_t device_size; /* overridden by parameter */
79         uint64_t device_size_new_real;
80         uint64_t device_size_org_real;
81         uint64_t device_offset;
82         uint64_t device_shift;
83         uint64_t data_offset;
84
85         unsigned int stained:1;
86         unsigned int in_progress:1;
87         enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
88         enum { REENCRYPT = 0, ENCRYPT = 1, DECRYPT = 2 } reencrypt_mode;
89
90         char header_file_org[PATH_MAX];
91         char header_file_tmp[PATH_MAX];
92         char header_file_new[PATH_MAX];
93         char log_file[PATH_MAX];
94
95         char crypt_path_org[PATH_MAX];
96         char crypt_path_new[PATH_MAX];
97         int log_fd;
98         char log_buf[SECTOR_SIZE];
99
100         struct {
101                 char *password;
102                 size_t passwordLen;
103         } p[MAX_SLOT];
104         int keyslot;
105
106         uint64_t resume_bytes;
107 };
108
109 char MAGIC[]   = {'L','U','K','S', 0xba, 0xbe};
110 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
111 int  MAGIC_L = 6;
112
113 typedef enum {
114         MAKE_UNUSABLE,
115         MAKE_USABLE,
116         CHECK_UNUSABLE,
117         CHECK_OPEN,
118 } header_magic;
119
120 void tools_cleanup(void)
121 {
122         FREE_AND_NULL(opt_cipher);
123         FREE_AND_NULL(opt_hash);
124         FREE_AND_NULL(opt_key_file);
125         FREE_AND_NULL(opt_master_key_file);
126         FREE_AND_NULL(opt_uuid);
127         FREE_AND_NULL(opt_type);
128         FREE_AND_NULL(opt_pbkdf);
129         FREE_AND_NULL(opt_header_device);
130         FREE_AND_NULL(opt_reduce_size_str);
131         FREE_AND_NULL(opt_device_size_str);
132 }
133
134 static void _quiet_log(int level, const char *msg, void *usrptr)
135 {
136         if (!opt_debug)
137                 return;
138         tool_log(level, msg, usrptr);
139 }
140
141 static int alignment(int fd)
142 {
143         int alignment;
144
145         alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
146         if (alignment < 0)
147                 alignment = 4096;
148         return alignment;
149 }
150
151 static size_t pagesize(void)
152 {
153         long r = sysconf(_SC_PAGESIZE);
154         return r < 0 ? 4096 : (size_t)r;
155 }
156
157 static const char *luksType(const char *type)
158 {
159         if (type && !strcmp(type, "luks2"))
160                 return CRYPT_LUKS2;
161
162         if (type && !strcmp(type, "luks1"))
163                 return CRYPT_LUKS1;
164
165         if (!type || !strcmp(type, "luks"))
166                 return crypt_get_default_type();
167
168         return NULL;
169 }
170
171 static const char *hdr_device(const struct reenc_ctx *rc)
172 {
173         return rc->device_header ?: rc->device;
174 }
175
176 static int set_reencrypt_requirement(const struct reenc_ctx *rc)
177 {
178         uint32_t reqs;
179         int r = -EINVAL;
180         struct crypt_device *cd = NULL;
181         struct crypt_params_integrity ip = { 0 };
182
183         if (crypt_init(&cd, hdr_device(rc)) ||
184             crypt_load(cd, CRYPT_LUKS2, NULL) ||
185             crypt_persistent_flags_get(cd, CRYPT_FLAGS_REQUIREMENTS, &reqs))
186                 goto out;
187
188         /* reencrypt already in-progress */
189         if (reqs & CRYPT_REQUIREMENT_OFFLINE_REENCRYPT) {
190                 log_err(_("Reencryption already in-progress."));
191                 goto out;
192         }
193
194         /* raw integrity info is available since 2.0 */
195         if (crypt_get_integrity_info(cd, &ip) || ip.tag_size) {
196                 log_err(_("Reencryption of device with integrity profile is not supported."));
197                 r = -ENOTSUP;
198                 goto out;
199         }
200
201         r = crypt_persistent_flags_set(cd, CRYPT_FLAGS_REQUIREMENTS, reqs | CRYPT_REQUIREMENT_OFFLINE_REENCRYPT);
202 out:
203         crypt_free(cd);
204         return r;
205 }
206
207 /* Depends on the first two fields of LUKS1 header format, magic and version */
208 static int device_check(struct reenc_ctx *rc, const char *device, header_magic set_magic)
209 {
210         char *buf = NULL;
211         int r, devfd;
212         ssize_t s;
213         uint16_t version;
214         size_t buf_size = pagesize();
215         struct stat st;
216
217         if (stat(device, &st)) {
218                 log_err(_("Cannot open device %s."), device);
219                 return -EINVAL;
220         }
221
222         /* coverity[toctou] */
223         devfd = open(device, O_RDWR | (S_ISBLK(st.st_mode) ? O_EXCL : 0));
224         if (devfd == -1) {
225                 if (errno == EBUSY) {
226                         log_err(_("Cannot exclusively open %s, device in use."),
227                                 device);
228                         return -EBUSY;
229                 }
230                 log_err(_("Cannot open device %s."), device);
231                 return -EINVAL;
232         }
233
234         if (set_magic == CHECK_OPEN) {
235                 r = 0;
236                 goto out;
237         }
238
239         if (posix_memalign((void *)&buf, alignment(devfd), buf_size)) {
240                 log_err(_("Allocation of aligned memory failed."));
241                 r = -ENOMEM;
242                 goto out;
243         }
244
245         s = read(devfd, buf, buf_size);
246         if (s < 0 || s != (ssize_t)buf_size) {
247                 log_err(_("Cannot read device %s."), device);
248                 r = -EIO;
249                 goto out;
250         }
251
252         /* Be sure that we do not process new version of header */
253         memcpy((void*)&version, &buf[MAGIC_L], sizeof(uint16_t));
254         version = ntohs(version);
255
256         if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L) &&
257             version == 1) {
258                 log_verbose(_("Marking LUKS1 device %s unusable."), device);
259                 memcpy(buf, NOMAGIC, MAGIC_L);
260                 r = 0;
261         } else if (set_magic == MAKE_UNUSABLE && version == 2) {
262                 log_verbose(_("Setting LUKS2 offline reencrypt flag on device %s."), device);
263                 r = set_reencrypt_requirement(rc);
264                 if (!r)
265                         rc->stained = 1;
266         } else if (set_magic == CHECK_UNUSABLE && version == 1) {
267                 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
268                 if (!r)
269                         rc->device_uuid = strndup(&buf[0xa8], 40);
270                 goto out;
271         } else
272                 r = -EINVAL;
273
274         if (!r && version == 1) {
275                 if (lseek(devfd, 0, SEEK_SET) == -1)
276                         goto out;
277                 s = write(devfd, buf, buf_size);
278                 if (s < 0 || s != (ssize_t)buf_size || fsync(devfd) < 0) {
279                         log_err(_("Cannot write device %s."), device);
280                         r = -EIO;
281                 }
282                 if (s > 0 && set_magic == MAKE_UNUSABLE)
283                         rc->stained = 1;
284         }
285         if (r)
286                 log_dbg("LUKS signature check failed for %s.", device);
287 out:
288         if (buf)
289                 memset(buf, 0, buf_size);
290         free(buf);
291         close(devfd);
292         return r;
293 }
294
295 static int create_empty_header(const char *new_file)
296 {
297         int fd, r = 0;
298
299         log_dbg("Creating empty file %s of size 4096.", new_file);
300
301         /* coverity[toctou] */
302         fd = open(new_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR);
303         if (fd == -1 || posix_fallocate(fd, 0, 4096))
304                 r = -EINVAL;
305         if (fd >= 0)
306                 close(fd);
307
308         return r;
309 }
310
311 static int write_log(struct reenc_ctx *rc)
312 {
313         ssize_t r;
314
315         memset(rc->log_buf, 0, SECTOR_SIZE);
316         snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
317                 "version = %d\nUUID = %s\ndirection = %d\nmode = %d\n"
318                 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
319                 2, rc->device_uuid, rc->reencrypt_direction, rc->reencrypt_mode,
320                 rc->device_offset, rc->device_shift);
321
322         if (lseek(rc->log_fd, 0, SEEK_SET) == -1)
323                 return -EIO;
324
325         r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE);
326         if (r < 0 || r != SECTOR_SIZE) {
327                 log_err(_("Cannot write reencryption log file."));
328                 return -EIO;
329         }
330
331         return 0;
332 }
333
334 static int parse_line_log(struct reenc_ctx *rc, const char *line)
335 {
336         uint64_t u64;
337         int i;
338         char s[64];
339
340         /* whole line is comment */
341         if (*line == '#')
342                 return 0;
343
344         if (sscanf(line, "version = %d", &i) == 1) {
345                 if (i < 1 || i > 2) {
346                         log_dbg("Log: Unexpected version = %i", i);
347                         return -EINVAL;
348                 }
349         } else if (sscanf(line, "UUID = %40s", s) == 1) {
350                 if (!rc->device_uuid || strcmp(rc->device_uuid, s)) {
351                         log_dbg("Log: Unexpected UUID %s", s);
352                         return -EINVAL;
353                 }
354         } else if (sscanf(line, "direction = %d", &i) == 1) {
355                 log_dbg("Log: direction = %i", i);
356                 rc->reencrypt_direction = i;
357         } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
358                 log_dbg("Log: offset = %" PRIu64, u64);
359                 rc->device_offset = u64;
360         } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
361                 log_dbg("Log: shift = %" PRIu64, u64);
362                 rc->device_shift = u64;
363         } else if (sscanf(line, "mode = %d", &i) == 1) { /* added in v2 */
364                 log_dbg("Log: mode = %i", i);
365                 rc->reencrypt_mode = i;
366                 if (rc->reencrypt_mode != REENCRYPT &&
367                     rc->reencrypt_mode != ENCRYPT &&
368                     rc->reencrypt_mode != DECRYPT)
369                         return -EINVAL;
370         } else
371                 return -EINVAL;
372
373         return 0;
374 }
375
376 static int parse_log(struct reenc_ctx *rc)
377 {
378         char *start, *end;
379         ssize_t s;
380
381         s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE);
382         if (s == -1) {
383                 log_err(_("Cannot read reencryption log file."));
384                 return -EIO;
385         }
386
387         rc->log_buf[SECTOR_SIZE - 1] = '\0';
388         start = rc->log_buf;
389         do {
390                 end = strchr(start, '\n');
391                 if (end) {
392                         *end++ = '\0';
393                         if (parse_line_log(rc, start)) {
394                                 log_err("Wrong log format.");
395                                 return -EINVAL;
396                         }
397                 }
398
399                 start = end;
400         } while (start);
401
402         return 0;
403 }
404
405 static void close_log(struct reenc_ctx *rc)
406 {
407         log_dbg("Closing LUKS reencryption log file %s.", rc->log_file);
408         if (rc->log_fd != -1)
409                 close(rc->log_fd);
410 }
411
412 static int open_log(struct reenc_ctx *rc)
413 {
414         int flags = opt_fsync ? O_SYNC : 0;
415
416         rc->log_fd = open(rc->log_file, O_RDWR|O_EXCL|O_CREAT|flags, S_IRUSR|S_IWUSR);
417         if (rc->log_fd != -1) {
418                 log_dbg("Created LUKS reencryption log file %s.", rc->log_file);
419                 rc->stained = 0;
420         } else if (errno == EEXIST) {
421                 log_std(_("Log file %s exists, resuming reencryption.\n"), rc->log_file);
422                 rc->log_fd = open(rc->log_file, O_RDWR|flags);
423                 rc->in_progress = 1;
424         }
425
426         if (rc->log_fd == -1)
427                 return -EINVAL;
428
429         if (!rc->in_progress && write_log(rc) < 0) {
430                 close_log(rc);
431                 return -EIO;
432         }
433
434         /* Be sure it is correct format */
435         return parse_log(rc);
436 }
437
438 static int activate_luks_headers(struct reenc_ctx *rc)
439 {
440         struct crypt_device *cd = NULL, *cd_new = NULL;
441         const char *pwd_old, *pwd_new, pwd_empty[] = "";
442         size_t pwd_old_len, pwd_new_len;
443         int r;
444
445         log_dbg("Activating LUKS devices from headers.");
446
447         /* Never use real password for empty header processing */
448         if (rc->reencrypt_mode == REENCRYPT) {
449                 pwd_old = rc->p[rc->keyslot].password;
450                 pwd_old_len = rc->p[rc->keyslot].passwordLen;
451                 pwd_new = pwd_old;
452                 pwd_new_len = pwd_old_len;
453         } else if (rc->reencrypt_mode == DECRYPT) {
454                 pwd_old = rc->p[rc->keyslot].password;
455                 pwd_old_len = rc->p[rc->keyslot].passwordLen;
456                 pwd_new = pwd_empty;
457                 pwd_new_len = 0;
458         } else if (rc->reencrypt_mode == ENCRYPT) {
459                 pwd_old = pwd_empty;
460                 pwd_old_len = 0;
461                 pwd_new = rc->p[rc->keyslot].password;
462                 pwd_new_len = rc->p[rc->keyslot].passwordLen;
463         } else
464                 return -EINVAL;
465
466         if ((r = crypt_init_data_device(&cd, rc->header_file_org, rc->device)) ||
467             (r = crypt_load(cd, CRYPT_LUKS, NULL)))
468                 goto out;
469
470         log_verbose(_("Activating temporary device using old LUKS header."));
471         if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org,
472                 opt_key_slot, pwd_old, pwd_old_len,
473                 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
474                 goto out;
475
476         if ((r = crypt_init_data_device(&cd_new, rc->header_file_new, rc->device)) ||
477             (r = crypt_load(cd_new, CRYPT_LUKS, NULL)))
478                 goto out;
479
480         log_verbose(_("Activating temporary device using new LUKS header."));
481         if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new,
482                 opt_key_slot, pwd_new, pwd_new_len,
483                 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
484                 goto out;
485         r = 0;
486 out:
487         crypt_free(cd);
488         crypt_free(cd_new);
489         if (r < 0)
490                 log_err(_("Activation of temporary devices failed."));
491         return r;
492 }
493
494 static int set_pbkdf_params(struct crypt_device *cd, const char *dev_type)
495 {
496         const struct crypt_pbkdf_type *pbkdf_default;
497         struct crypt_pbkdf_type pbkdf = {};
498
499         pbkdf_default = crypt_get_pbkdf_default(dev_type);
500         if (!pbkdf_default)
501                 return -EINVAL;
502
503         pbkdf.type = set_pbkdf ?: pbkdf_default->type;
504         pbkdf.hash = opt_hash ?: pbkdf_default->hash;
505         pbkdf.time_ms = (uint32_t)opt_iteration_time ?: pbkdf_default->time_ms;
506         if (strcmp(pbkdf.type, CRYPT_KDF_PBKDF2)) {
507                 pbkdf.max_memory_kb = (uint32_t)opt_pbkdf_memory ?: pbkdf_default->max_memory_kb;
508                 pbkdf.parallel_threads = (uint32_t)opt_pbkdf_parallel ?: pbkdf_default->parallel_threads;
509         }
510
511         if (opt_pbkdf_iterations) {
512                 pbkdf.iterations = opt_pbkdf_iterations;
513                 pbkdf.time_ms = 0;
514                 pbkdf.flags |= CRYPT_PBKDF_NO_BENCHMARK;
515         }
516
517         return crypt_set_pbkdf_type(cd, &pbkdf);
518 }
519
520 static int create_new_keyslot(struct reenc_ctx *rc, int keyslot,
521                               struct crypt_device *cd_old,
522                               struct crypt_device *cd_new)
523 {
524         int r;
525         char *key = NULL;
526         size_t key_size;
527
528         if (cd_old && crypt_keyslot_status(cd_old, keyslot) == CRYPT_SLOT_UNBOUND) {
529                 key_size = 4096;
530                 key = crypt_safe_alloc(key_size);
531                 if (!key)
532                         return -ENOMEM;
533                 r = crypt_volume_key_get(cd_old, keyslot, key, &key_size,
534                         rc->p[keyslot].password, rc->p[keyslot].passwordLen);
535                 if (r == keyslot) {
536                         r = crypt_keyslot_add_by_key(cd_new, keyslot, key, key_size,
537                                 rc->p[keyslot].password, rc->p[keyslot].passwordLen,
538                                 CRYPT_VOLUME_KEY_NO_SEGMENT);
539                 } else
540                         r = -EINVAL;
541                 crypt_safe_free(key);
542         } else
543                 r = crypt_keyslot_add_by_volume_key(cd_new, keyslot, NULL, 0,
544                         rc->p[keyslot].password, rc->p[keyslot].passwordLen);
545
546         return r;
547 }
548
549 static int create_new_header(struct reenc_ctx *rc, struct crypt_device *cd_old,
550                              const char *cipher, const char *cipher_mode,
551                              const char *uuid,
552                              const char *key, int key_size,
553                              const char *type,
554                              uint64_t metadata_size,
555                              uint64_t keyslots_size,
556                              void *params)
557 {
558         struct crypt_device *cd_new = NULL;
559         int i, r;
560
561         if ((r = crypt_init(&cd_new, rc->header_file_new)))
562                 goto out;
563
564         if (opt_random)
565                 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
566         else if (opt_urandom)
567                 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
568
569         r = set_pbkdf_params(cd_new, type);
570         if (r) {
571                 log_err(_("Failed to set pbkdf parameters."));
572                 goto out;
573         }
574
575         r = crypt_set_data_offset(cd_new, rc->data_offset);
576         if (r) {
577                 log_err(_("Failed to set data offset."));
578                 goto out;
579         }
580
581         r = crypt_set_metadata_size(cd_new, metadata_size, keyslots_size);
582         if (r) {
583                 log_err(_("Failed to set metadata size."));
584                 goto out;
585         }
586
587         r = crypt_format(cd_new, type, cipher, cipher_mode, uuid, key, key_size, params);
588         check_signal(&r);
589         if (r < 0)
590                 goto out;
591         log_verbose(_("New LUKS header for device %s created."), rc->device);
592
593         for (i = 0; i < crypt_keyslot_max(type); i++) {
594                 if (!rc->p[i].password)
595                         continue;
596
597                 r = create_new_keyslot(rc, i, cd_old, cd_new);
598                 check_signal(&r);
599                 if (r < 0)
600                         goto out;
601                 tools_keyslot_msg(r, CREATED);
602                 r = 0;
603         }
604 out:
605         crypt_free(cd_new);
606         return r;
607 }
608
609 static int isLUKS2(const char *type)
610 {
611         return (type && !strcmp(type, CRYPT_LUKS2));
612 }
613
614 static int luks2_metadata_copy(struct reenc_ctx *rc)
615 {
616         const char *json, *type;
617         crypt_token_info ti;
618         uint32_t flags;
619         int i, r = -EINVAL;
620         struct crypt_device *cd_old = NULL, *cd_new = NULL;
621
622         if (crypt_init(&cd_old, rc->header_file_tmp) ||
623             crypt_load(cd_old, CRYPT_LUKS2, NULL))
624                 goto out;
625
626         if (crypt_init(&cd_new, rc->header_file_new) ||
627             crypt_load(cd_new, CRYPT_LUKS2, NULL))
628                 goto out;
629
630         /*
631          * we have to erase keyslots missing in new header so that we can
632          * transfer tokens from old header to new one
633          */
634         for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS2); i++)
635                 if (!rc->p[i].password && crypt_keyslot_status(cd_old, i) == CRYPT_SLOT_ACTIVE) {
636                         r = crypt_keyslot_destroy(cd_old, i);
637                         if (r < 0)
638                                 goto out;
639                 }
640
641         for (i = 0; i < MAX_TOKEN; i++) {
642                 ti = crypt_token_status(cd_old, i, &type);
643                 switch (ti) {
644                 case CRYPT_TOKEN_INVALID:
645                         log_dbg("Internal error.");
646                         r = -EINVAL;
647                         goto out;
648                 case CRYPT_TOKEN_INACTIVE:
649                         break;
650                 case CRYPT_TOKEN_INTERNAL_UNKNOWN:
651                         log_err(_("This version of cryptsetup-reencrypt can't handle new internal token type %s."), type);
652                         r = -EINVAL;
653                         goto out;
654                 case CRYPT_TOKEN_INTERNAL:
655                         /* fallthrough */
656                 case CRYPT_TOKEN_EXTERNAL:
657                         /* fallthrough */
658                 case CRYPT_TOKEN_EXTERNAL_UNKNOWN:
659                         if (crypt_token_json_get(cd_old, i, &json) != i) {
660                                 log_dbg("Failed to get %s token (%d).", type, i);
661                                 r = -EINVAL;
662                                 goto out;
663                         }
664                         if (crypt_token_json_set(cd_new, i, json) != i) {
665                                 log_dbg("Failed to create %s token (%d).", type, i);
666                                 r = -EINVAL;
667                                 goto out;
668                         }
669                 }
670         }
671
672         if ((r = crypt_persistent_flags_get(cd_old, CRYPT_FLAGS_ACTIVATION, &flags))) {
673                 log_err(_("Failed to read activation flags from backup header."));
674                 goto out;
675         }
676         if ((r = crypt_persistent_flags_set(cd_new, CRYPT_FLAGS_ACTIVATION, flags))) {
677                 log_err(_("Failed to write activation flags to new header."));
678                 goto out;
679         }
680         if ((r = crypt_persistent_flags_get(cd_old, CRYPT_FLAGS_REQUIREMENTS, &flags))) {
681                 log_err(_("Failed to read requirements from backup header."));
682                 goto out;
683         }
684         if ((r = crypt_persistent_flags_set(cd_new, CRYPT_FLAGS_REQUIREMENTS, flags)))
685                 log_err(_("Failed to read requirements from backup header."));
686 out:
687         crypt_free(cd_old);
688         crypt_free(cd_new);
689         unlink(rc->header_file_tmp);
690
691         return r;
692 }
693
694 static int backup_luks_headers(struct reenc_ctx *rc)
695 {
696         struct crypt_device *cd = NULL;
697         struct crypt_params_luks1 params = {0};
698         struct crypt_params_luks2 params2 = {0};
699         struct stat st;
700         char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
701         char *key = NULL;
702         size_t key_size;
703         uint64_t mdata_size = 0, keyslots_size = 0;
704         int r;
705
706         log_dbg("Creating LUKS header backup for device %s.", hdr_device(rc));
707
708         if ((r = crypt_init(&cd, hdr_device(rc))) ||
709             (r = crypt_load(cd, CRYPT_LUKS, NULL)))
710                 goto out;
711
712         if ((r = crypt_header_backup(cd, CRYPT_LUKS, rc->header_file_org)))
713                 goto out;
714         if (isLUKS2(rc->type)) {
715                 if ((r = crypt_header_backup(cd, CRYPT_LUKS2, rc->header_file_tmp)))
716                         goto out;
717                 if ((r = stat(rc->header_file_tmp, &st)))
718                         goto out;
719                 /* coverity[toctou] */
720                 if ((r = chmod(rc->header_file_tmp, st.st_mode | S_IWUSR)))
721                         goto out;
722         }
723         log_verbose(_("%s header backup of device %s created."), isLUKS2(rc->type) ? "LUKS2" : "LUKS1", rc->device);
724
725         /* For decrypt, new header will be fake one, so we are done here. */
726         if (rc->reencrypt_mode == DECRYPT)
727                 goto out;
728
729         rc->data_offset = crypt_get_data_offset(cd) + ROUND_SECTOR(opt_reduce_size);
730
731         if ((r = create_empty_header(rc->header_file_new)))
732                 goto out;
733
734         params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
735         params2.data_device = params.data_device = rc->device;
736         params2.sector_size = crypt_get_sector_size(cd);
737
738         if (opt_cipher) {
739                 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
740                 if (r < 0) {
741                         log_err(_("No known cipher specification pattern detected."));
742                         goto out;
743                 }
744         }
745
746         key_size = opt_key_size ? opt_key_size / 8 : crypt_get_volume_key_size(cd);
747
748         if (opt_keep_key) {
749                 log_dbg("Keeping key from old header.");
750                 key_size = crypt_get_volume_key_size(cd);
751                 key = crypt_safe_alloc(key_size);
752                 if (!key) {
753                         r = -ENOMEM;
754                         goto out;
755                 }
756                 r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, key, &key_size,
757                         rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
758         } else if (opt_master_key_file) {
759                 log_dbg("Loading new key from file.");
760                 r = tools_read_mk(opt_master_key_file, &key, key_size);
761         }
762
763         if (r < 0)
764                 goto out;
765
766         if (isLUKS2(crypt_get_type(cd)) && crypt_get_metadata_size(cd, &mdata_size, &keyslots_size))
767                 goto out;
768
769         r = create_new_header(rc, cd,
770                 opt_cipher ? cipher : crypt_get_cipher(cd),
771                 opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
772                 crypt_get_uuid(cd),
773                 key,
774                 key_size,
775                 rc->type,
776                 mdata_size,
777                 keyslots_size,
778                 isLUKS2(rc->type) ? (void*)&params2 : (void*)&params);
779
780         if (!r && isLUKS2(rc->type))
781                 r = luks2_metadata_copy(rc);
782 out:
783         crypt_free(cd);
784         crypt_safe_free(key);
785         if (r)
786                 log_err(_("Creation of LUKS backup headers failed."));
787         return r;
788 }
789
790 /* Create fake header for original device */
791 static int backup_fake_header(struct reenc_ctx *rc)
792 {
793         struct crypt_device *cd_new = NULL;
794         struct crypt_params_luks1 params = {0};
795         struct crypt_params_luks2 params2 = {0};
796         char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
797         const char *header_file_fake;
798         int r;
799
800         log_dbg("Creating fake (cipher_null) header for %s device.",
801                 (rc->reencrypt_mode == DECRYPT) ? "new" : "original");
802
803         header_file_fake = (rc->reencrypt_mode == DECRYPT) ? rc->header_file_new : rc->header_file_org;
804
805         if (!opt_key_size)
806                 opt_key_size = DEFAULT_LUKS1_KEYBITS;
807
808         if (opt_cipher) {
809                 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
810                 if (r < 0) {
811                         log_err(_("No known cipher specification pattern detected."));
812                         goto out;
813                 }
814         }
815
816         r = create_empty_header(header_file_fake);
817         if (r < 0)
818                 return r;
819
820         params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
821         params2.data_alignment = params.data_alignment = 0;
822         params2.data_device = params.data_device = rc->device;
823         params2.sector_size = crypt_get_sector_size(NULL);
824         params2.pbkdf = crypt_get_pbkdf_default(CRYPT_LUKS2);
825
826         r = crypt_init(&cd_new, header_file_fake);
827         if (r < 0)
828                 return r;
829
830         r = crypt_format(cd_new, CRYPT_LUKS1, "cipher_null", "ecb",
831                          NO_UUID, NULL, opt_key_size / 8, &params);
832         check_signal(&r);
833         if (r < 0)
834                 goto out;
835
836         r = crypt_keyslot_add_by_volume_key(cd_new, rc->keyslot, NULL, 0,
837                         rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
838         check_signal(&r);
839         if (r < 0)
840                 goto out;
841
842         /* The real header is backup header created in backup_luks_headers() */
843         if (rc->reencrypt_mode == DECRYPT) {
844                 r = 0;
845                 goto out;
846         }
847
848         r = create_empty_header(rc->header_file_new);
849         if (r < 0)
850                 goto out;
851
852         params2.data_alignment = params.data_alignment = ROUND_SECTOR(opt_reduce_size);
853         r = create_new_header(rc, NULL,
854                 opt_cipher ? cipher : DEFAULT_LUKS1_CIPHER,
855                 opt_cipher ? cipher_mode : DEFAULT_LUKS1_MODE,
856                 NULL, NULL,
857                 (opt_key_size ? opt_key_size : DEFAULT_LUKS1_KEYBITS) / 8,
858                 rc->type,
859                 0,
860                 0,
861                 isLUKS2(rc->type) ? (void*)&params2 : (void*)&params);
862 out:
863         crypt_free(cd_new);
864         return r;
865 }
866
867 static void remove_headers(struct reenc_ctx *rc)
868 {
869         struct crypt_device *cd = NULL;
870
871         log_dbg("Removing headers.");
872
873         if (crypt_init(&cd, NULL))
874                 return;
875         crypt_set_log_callback(cd, _quiet_log, NULL);
876         if (*rc->header_file_org)
877                 (void)crypt_deactivate(cd, rc->header_file_org);
878         if (*rc->header_file_new)
879                 (void)crypt_deactivate(cd, rc->header_file_new);
880         crypt_free(cd);
881 }
882
883 static int restore_luks_header(struct reenc_ctx *rc)
884 {
885         struct stat st;
886         struct crypt_device *cd = NULL;
887         int fd, r;
888
889         log_dbg("Restoring header for %s from %s.", hdr_device(rc), rc->header_file_new);
890
891         /*
892          * For new encryption and new detached header in file just move it.
893          * For existing file try to ensure we have preallocated space for restore.
894          */
895         if (opt_new && rc->device_header) {
896                 r = stat(rc->device_header, &st);
897                 if (r == -1) {
898                         r = rename(rc->header_file_new, rc->device_header);
899                         goto out;
900                 } else if ((st.st_mode & S_IFMT) == S_IFREG &&
901                         stat(rc->header_file_new, &st) != -1) {
902                         /* coverity[toctou] */
903                         fd = open(rc->device_header, O_WRONLY);
904                         if (fd != -1) {
905                                 if (posix_fallocate(fd, 0, st.st_size)) {};
906                                 close(fd);
907                         }
908                 }
909         }
910
911         r = crypt_init(&cd, hdr_device(rc));
912         if (r == 0) {
913                 r = crypt_header_restore(cd, rc->type, rc->header_file_new);
914         }
915
916         crypt_free(cd);
917 out:
918         if (r)
919                 log_err(_("Cannot restore %s header on device %s."), isLUKS2(rc->type) ? "LUKS2" : "LUKS1", hdr_device(rc));
920         else {
921                 log_verbose(_("%s header on device %s restored."), isLUKS2(rc->type) ? "LUKS2" : "LUKS1", hdr_device(rc));
922                 rc->stained = 0;
923         }
924         return r;
925 }
926
927 static ssize_t read_buf(int fd, void *buf, size_t count)
928 {
929         size_t read_size = 0;
930         ssize_t s;
931
932         do {
933                 /* This expects that partial read is aligned in buffer */
934                 s = read(fd, buf, count - read_size);
935                 if (s == -1 && errno != EINTR)
936                         return s;
937                 if (s == 0)
938                         return (ssize_t)read_size;
939                 if (s > 0) {
940                         if (s != (ssize_t)count)
941                                 log_dbg("Partial read %zd / %zu.", s, count);
942                         read_size += (size_t)s;
943                         buf = (uint8_t*)buf + s;
944                 }
945         } while (read_size != count);
946
947         return (ssize_t)count;
948 }
949
950 static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new,
951                              size_t block_size, void *buf, uint64_t *bytes)
952 {
953         ssize_t s1, s2;
954
955         log_dbg("Reencrypting in forward direction.");
956
957         if (lseek64(fd_old, rc->device_offset, SEEK_SET) < 0 ||
958             lseek64(fd_new, rc->device_offset, SEEK_SET) < 0) {
959                 log_err(_("Cannot seek to device offset."));
960                 return -EIO;
961         }
962
963         rc->resume_bytes = *bytes = rc->device_offset;
964
965         tools_reencrypt_progress(rc->device_size, *bytes, NULL);
966
967         if (write_log(rc) < 0)
968                 return -EIO;
969
970         while (!quit && rc->device_offset < rc->device_size) {
971                 s1 = read_buf(fd_old, buf, block_size);
972                 if (s1 < 0 || ((size_t)s1 != block_size &&
973                     (rc->device_offset + s1) != rc->device_size)) {
974                         log_dbg("Read error, expecting %zu, got %zd.",
975                                 block_size, s1);
976                         return -EIO;
977                 }
978
979                 /* If device_size is forced, never write more than limit */
980                 if ((s1 + rc->device_offset) > rc->device_size)
981                         s1 = rc->device_size - rc->device_offset;
982
983                 s2 = write(fd_new, buf, s1);
984                 if (s2 < 0) {
985                         log_dbg("Write error, expecting %zu, got %zd.",
986                                 block_size, s2);
987                         return -EIO;
988                 }
989
990                 rc->device_offset += s1;
991                 if (opt_write_log && write_log(rc) < 0)
992                         return -EIO;
993
994                 if (opt_fsync && fsync(fd_new) < 0) {
995                         log_dbg("Write error, fsync.");
996                         return -EIO;
997                 }
998
999                 *bytes += (uint64_t)s2;
1000
1001                 tools_reencrypt_progress(rc->device_size, *bytes, NULL);
1002         }
1003
1004         return quit ? -EAGAIN : 0;
1005 }
1006
1007 static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new,
1008                               size_t block_size, void *buf, uint64_t *bytes)
1009 {
1010         ssize_t s1, s2, working_block;
1011         off64_t working_offset;
1012
1013         log_dbg("Reencrypting in backward direction.");
1014
1015         if (!rc->in_progress) {
1016                 rc->device_offset = rc->device_size;
1017                 rc->resume_bytes = 0;
1018                 *bytes = 0;
1019         } else {
1020                 rc->resume_bytes = rc->device_size - rc->device_offset;
1021                 *bytes = rc->resume_bytes;
1022         }
1023
1024         tools_reencrypt_progress(rc->device_size, *bytes, NULL);
1025
1026         if (write_log(rc) < 0)
1027                 return -EIO;
1028
1029         /* dirty the device during ENCRYPT mode */
1030         rc->stained = 1;
1031
1032         while (!quit && rc->device_offset) {
1033                 if (rc->device_offset < block_size) {
1034                         working_offset = 0;
1035                         working_block = rc->device_offset;
1036                 } else {
1037                         working_offset = rc->device_offset - block_size;
1038                         working_block = block_size;
1039                 }
1040
1041                 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
1042                     lseek64(fd_new, working_offset, SEEK_SET) < 0) {
1043                         log_err(_("Cannot seek to device offset."));
1044                         return -EIO;
1045                 }
1046
1047                 s1 = read_buf(fd_old, buf, working_block);
1048                 if (s1 < 0 || (s1 != working_block)) {
1049                         log_dbg("Read error, expecting %zu, got %zd.",
1050                                 block_size, s1);
1051                         return -EIO;
1052                 }
1053
1054                 s2 = write(fd_new, buf, working_block);
1055                 if (s2 < 0) {
1056                         log_dbg("Write error, expecting %zu, got %zd.",
1057                                 block_size, s2);
1058                         return -EIO;
1059                 }
1060
1061                 rc->device_offset -= s1;
1062                 if (opt_write_log && write_log(rc) < 0)
1063                         return -EIO;
1064
1065                 if (opt_fsync && fsync(fd_new) < 0) {
1066                         log_dbg("Write error, fsync.");
1067                         return -EIO;
1068                 }
1069
1070                 *bytes += (uint64_t)s2;
1071
1072                 tools_reencrypt_progress(rc->device_size, *bytes, NULL);
1073         }
1074
1075         return quit ? -EAGAIN : 0;
1076 }
1077
1078 static void zero_rest_of_device(int fd, size_t block_size, void *buf,
1079                                 uint64_t *bytes, uint64_t offset)
1080 {
1081         ssize_t s1, s2;
1082
1083         log_dbg("Zeroing rest of device.");
1084
1085         if (lseek64(fd, offset, SEEK_SET) < 0) {
1086                 log_dbg("Cannot seek to device offset.");
1087                 return;
1088         }
1089
1090         memset(buf, 0, block_size);
1091         s1 = block_size;
1092
1093         while (!quit && *bytes) {
1094                 if (*bytes < (uint64_t)s1)
1095                         s1 = *bytes;
1096
1097                 s2 = write(fd, buf, s1);
1098                 if (s2 != s1) {
1099                         log_dbg("Write error, expecting %zd, got %zd.",
1100                                 s1, s2);
1101                         return;
1102                 }
1103
1104                 if (opt_fsync && fsync(fd) < 0) {
1105                         log_dbg("Write error, fsync.");
1106                         return;
1107                 }
1108
1109                 *bytes -= s2;
1110         }
1111 }
1112
1113 static int copy_data(struct reenc_ctx *rc)
1114 {
1115         size_t block_size = opt_bsize * 1024 * 1024;
1116         int fd_old = -1, fd_new = -1;
1117         int r = -EINVAL;
1118         void *buf = NULL;
1119         uint64_t bytes = 0;
1120
1121         log_dbg("Data copy preparation.");
1122
1123         fd_old = open(rc->crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
1124         if (fd_old == -1) {
1125                 log_err(_("Cannot open temporary LUKS device."));
1126                 goto out;
1127         }
1128
1129         fd_new = open(rc->crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
1130         if (fd_new == -1) {
1131                 log_err(_("Cannot open temporary LUKS device."));
1132                 goto out;
1133         }
1134
1135         if (ioctl(fd_old, BLKGETSIZE64, &rc->device_size_org_real) < 0) {
1136                 log_err(_("Cannot get device size."));
1137                 goto out;
1138         }
1139
1140         if (ioctl(fd_new, BLKGETSIZE64, &rc->device_size_new_real) < 0) {
1141                 log_err(_("Cannot get device size."));
1142                 goto out;
1143         }
1144
1145         if (opt_device_size)
1146                 rc->device_size = opt_device_size;
1147         else if (rc->reencrypt_mode == DECRYPT)
1148                 rc->device_size = rc->device_size_org_real;
1149         else
1150                 rc->device_size = rc->device_size_new_real;
1151
1152         if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
1153                 log_err(_("Allocation of aligned memory failed."));
1154                 r = -ENOMEM;
1155                 goto out;
1156         }
1157
1158         set_int_handler(0);
1159
1160         if (rc->reencrypt_direction == FORWARD)
1161                 r = copy_data_forward(rc, fd_old, fd_new, block_size, buf, &bytes);
1162         else
1163                 r = copy_data_backward(rc, fd_old, fd_new, block_size, buf, &bytes);
1164
1165         /* Zero (wipe) rest of now plain-only device when decrypting.
1166          * (To not leave any sign of encryption here.) */
1167         if (!r && rc->reencrypt_mode == DECRYPT &&
1168             rc->device_size_new_real > rc->device_size_org_real) {
1169                 bytes = rc->device_size_new_real - rc->device_size_org_real;
1170                 zero_rest_of_device(fd_new, block_size, buf, &bytes, rc->device_size_org_real);
1171         }
1172
1173         set_int_block(1);
1174
1175         if (r < 0 && r != -EAGAIN)
1176                 log_err(_("IO error during reencryption."));
1177
1178         (void)write_log(rc);
1179 out:
1180         if (fd_old != -1)
1181                 close(fd_old);
1182         if (fd_new != -1)
1183                 close(fd_new);
1184         free(buf);
1185         return r;
1186 }
1187
1188 static int initialize_uuid(struct reenc_ctx *rc)
1189 {
1190         struct crypt_device *cd = NULL;
1191         int r;
1192         uuid_t device_uuid;
1193
1194         log_dbg("Initialising UUID.");
1195
1196         if (opt_new) {
1197                 rc->device_uuid = strdup(NO_UUID);
1198                 rc->type = luksType(opt_type);
1199                 return 0;
1200         }
1201
1202         if (opt_decrypt && opt_uuid) {
1203                 r = uuid_parse(opt_uuid, device_uuid);
1204                 if (!r)
1205                         rc->device_uuid = strdup(opt_uuid);
1206                 else
1207                         log_err(_("Provided UUID is invalid."));
1208
1209                 return r;
1210         }
1211
1212         /* Try to load LUKS from device */
1213         if ((r = crypt_init(&cd, hdr_device(rc))))
1214                 return r;
1215         crypt_set_log_callback(cd, _quiet_log, NULL);
1216         r = crypt_load(cd, CRYPT_LUKS, NULL);
1217         if (!r)
1218                 rc->device_uuid = strdup(crypt_get_uuid(cd));
1219         else
1220                 /* Reencryption already in progress - magic header? */
1221                 r = device_check(rc, hdr_device(rc), CHECK_UNUSABLE);
1222
1223         if (!r)
1224                 rc->type = isLUKS2(crypt_get_type(cd)) ? CRYPT_LUKS2 : CRYPT_LUKS1;
1225
1226         crypt_free(cd);
1227         return r;
1228 }
1229
1230 static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd,
1231                             const char *msg, int slot_to_check, int check, int verify)
1232 {
1233         crypt_keyslot_info ki;
1234         char *password;
1235         int r = -EINVAL, retry_count;
1236         size_t passwordLen;
1237
1238         /* mode ENCRYPT call this without header */
1239         if (cd && slot_to_check != CRYPT_ANY_SLOT) {
1240                 ki = crypt_keyslot_status(cd, slot_to_check);
1241                 if (ki < CRYPT_SLOT_ACTIVE)
1242                         return -ENOENT;
1243         } else
1244                 ki = CRYPT_SLOT_ACTIVE;
1245
1246         retry_count = opt_tries ?: 1;
1247         while (retry_count--) {
1248                 r = tools_get_key(msg,  &password, &passwordLen, 0, 0,
1249                                   NULL /*opt_key_file*/, 0, verify, 0 /*pwquality*/, cd);
1250                 if (r < 0)
1251                         return r;
1252                 if (quit) {
1253                         crypt_safe_free(password);
1254                         password = NULL;
1255                         passwordLen = 0;
1256                         return -EAGAIN;
1257                 }
1258
1259                 if (check)
1260                         r = crypt_activate_by_passphrase(cd, NULL, slot_to_check,
1261                                 password, passwordLen, CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY);
1262                 else
1263                         r = (slot_to_check == CRYPT_ANY_SLOT) ? 0 : slot_to_check;
1264
1265                 if (r < 0) {
1266                         crypt_safe_free(password);
1267                         password = NULL;
1268                         passwordLen = 0;
1269                 }
1270                 if (r < 0 && r != -EPERM)
1271                         return r;
1272
1273                 if (r >= 0) {
1274                         tools_keyslot_msg(r, UNLOCKED);
1275                         rc->p[r].password = password;
1276                         rc->p[r].passwordLen = passwordLen;
1277                         if (ki != CRYPT_SLOT_UNBOUND)
1278                                 rc->keyslot = r;
1279                         break;
1280                 }
1281                 tools_passphrase_msg(r);
1282         }
1283
1284         password = NULL;
1285         passwordLen = 0;
1286
1287         return r;
1288 }
1289
1290 static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check)
1291 {
1292         char *password;
1293         int r;
1294         size_t passwordLen;
1295
1296         r = tools_get_key(NULL, &password, &passwordLen, opt_keyfile_offset,
1297                           opt_keyfile_size, opt_key_file, 0, 0, 0, cd);
1298         if (r < 0)
1299                 return r;
1300
1301         /* mode ENCRYPT call this without header */
1302         if (cd) {
1303                 r = crypt_activate_by_passphrase(cd, NULL, slot_check, password,
1304                                                  passwordLen, 0);
1305
1306                 /*
1307                  * Allow keyslot only if it is last slot or if user explicitly
1308                  * specify which slot to use (IOW others will be disabled).
1309                  */
1310                 if (r >= 0 && opt_key_slot == CRYPT_ANY_SLOT &&
1311                     crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
1312                         log_err(_("Key file can be used only with --key-slot or with "
1313                                   "exactly one key slot active."));
1314                         r = -EINVAL;
1315                 }
1316         } else {
1317                 r = slot_check == CRYPT_ANY_SLOT ? 0 : slot_check;
1318         }
1319
1320         if (r < 0) {
1321                 crypt_safe_free(password);
1322                 tools_passphrase_msg(r);
1323         } else {
1324                 rc->keyslot = r;
1325                 rc->p[r].password = password;
1326                 rc->p[r].passwordLen = passwordLen;
1327         }
1328
1329         password = NULL;
1330         passwordLen = 0;
1331
1332         return r;
1333 }
1334
1335 static int initialize_passphrase(struct reenc_ctx *rc, const char *device)
1336 {
1337         struct crypt_device *cd = NULL;
1338         char msg[256];
1339         int i, r;
1340
1341         log_dbg("Passphrases initialization.");
1342
1343         if (rc->reencrypt_mode == ENCRYPT && !rc->in_progress) {
1344                 if (opt_key_file)
1345                         r = init_keyfile(rc, NULL, opt_key_slot);
1346                 else
1347                         r = init_passphrase1(rc, NULL, _("Enter new passphrase: "), opt_key_slot, 0, 1);
1348                 return r > 0 ? 0 : r;
1349         }
1350
1351         if ((r = crypt_init_data_device(&cd, device, rc->device)) ||
1352             (r = crypt_load(cd, CRYPT_LUKS, NULL))) {
1353                 crypt_free(cd);
1354                 return r;
1355         }
1356
1357         if (opt_key_slot != CRYPT_ANY_SLOT)
1358                 snprintf(msg, sizeof(msg),
1359                          _("Enter passphrase for key slot %d: "), opt_key_slot);
1360         else
1361                 snprintf(msg, sizeof(msg), _("Enter any existing passphrase: "));
1362
1363         if (opt_key_file) {
1364                 r = init_keyfile(rc, cd, opt_key_slot);
1365         } else if (rc->in_progress ||
1366                    opt_key_slot != CRYPT_ANY_SLOT ||
1367                    rc->reencrypt_mode == DECRYPT) {
1368                 r = init_passphrase1(rc, cd, msg, opt_key_slot, 1, 0);
1369         } else for (i = 0; i < crypt_keyslot_max(crypt_get_type(cd)); i++) {
1370                 snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %d: "), i);
1371                 r = init_passphrase1(rc, cd, msg, i, 1, 0);
1372                 if (r == -ENOENT) {
1373                         r = 0;
1374                         continue;
1375                 }
1376                 if (r < 0)
1377                         break;
1378         }
1379
1380         crypt_free(cd);
1381         return r > 0 ? 0 : r;
1382 }
1383
1384 static int initialize_context(struct reenc_ctx *rc, const char *device)
1385 {
1386         log_dbg("Initialising reencryption context.");
1387
1388         rc->log_fd = -1;
1389
1390         /* FIXME: replace MAX_KEYSLOT with crypt_keyslot_max(CRYPT_LUKS2) */
1391         if (crypt_keyslot_max(CRYPT_LUKS2) > MAX_SLOT) {
1392                 log_dbg("Internal error");
1393                 return -EINVAL;
1394         }
1395
1396         if (!(rc->device = strndup(device, PATH_MAX)))
1397                 return -ENOMEM;
1398
1399         if (opt_header_device && !(rc->device_header = strndup(opt_header_device, PATH_MAX)))
1400                 return -ENOMEM;
1401
1402         if (device_check(rc, rc->device, CHECK_OPEN) < 0)
1403                 return -EINVAL;
1404
1405         if (initialize_uuid(rc)) {
1406                 log_err(_("Device %s is not a valid LUKS device."), device);
1407                 return -EINVAL;
1408         }
1409
1410         if (opt_key_slot != CRYPT_ANY_SLOT &&
1411             opt_key_slot >= crypt_keyslot_max(rc->type)) {
1412                 log_err(_("Key slot is invalid."));
1413                 return -EINVAL;
1414         }
1415
1416         /* Prepare device names */
1417         if (snprintf(rc->log_file, PATH_MAX,
1418                      "LUKS-%s.log", rc->device_uuid) < 0)
1419                 return -ENOMEM;
1420         if (snprintf(rc->header_file_org, PATH_MAX,
1421                      "LUKS-%s.org", rc->device_uuid) < 0)
1422                 return -ENOMEM;
1423         if (snprintf(rc->header_file_new, PATH_MAX,
1424                      "LUKS-%s.new", rc->device_uuid) < 0)
1425                 return -ENOMEM;
1426         if (snprintf(rc->header_file_tmp, PATH_MAX,
1427                      "LUKS-%s.tmp", rc->device_uuid) < 0)
1428                 return -ENOMEM;
1429
1430         /* Paths to encrypted devices */
1431         if (snprintf(rc->crypt_path_org, PATH_MAX,
1432                      "%s/%s", crypt_get_dir(), rc->header_file_org) < 0)
1433                 return -ENOMEM;
1434         if (snprintf(rc->crypt_path_new, PATH_MAX,
1435                      "%s/%s", crypt_get_dir(), rc->header_file_new) < 0)
1436                 return -ENOMEM;
1437
1438         remove_headers(rc);
1439
1440         if (open_log(rc) < 0) {
1441                 log_err(_("Cannot open reencryption log file."));
1442                 return -EINVAL;
1443         }
1444
1445         if (!rc->in_progress) {
1446                 if (opt_uuid) {
1447                         log_err(_("No decryption in progress, provided UUID can "
1448                         "be used only to resume suspended decryption process."));
1449                         return -EINVAL;
1450                 }
1451
1452                 if (!opt_reduce_size)
1453                         rc->reencrypt_direction = FORWARD;
1454                 else {
1455                         rc->reencrypt_direction = BACKWARD;
1456                         rc->device_offset = (uint64_t)~0;
1457                 }
1458
1459                 if (opt_new)
1460                         rc->reencrypt_mode = ENCRYPT;
1461                 else if (opt_decrypt)
1462                         rc->reencrypt_mode = DECRYPT;
1463                 else
1464                         rc->reencrypt_mode = REENCRYPT;
1465         }
1466
1467         return 0;
1468 }
1469
1470 static void destroy_context(struct reenc_ctx *rc)
1471 {
1472         int i;
1473
1474         log_dbg("Destroying reencryption context.");
1475
1476         close_log(rc);
1477         remove_headers(rc);
1478
1479         if (!rc->stained) {
1480                 unlink(rc->log_file);
1481                 unlink(rc->header_file_org);
1482                 unlink(rc->header_file_new);
1483                 unlink(rc->header_file_tmp);
1484         }
1485
1486         for (i = 0; i < MAX_SLOT; i++)
1487                 crypt_safe_free(rc->p[i].password);
1488
1489         free(rc->device);
1490         free(rc->device_header);
1491         free(rc->device_uuid);
1492 }
1493
1494 static int luks2_change_pbkdf_params(struct reenc_ctx *rc)
1495 {
1496         int i, r;
1497         struct crypt_device *cd = NULL;
1498
1499         if ((r = initialize_passphrase(rc, hdr_device(rc))))
1500                 return r;
1501
1502         if (crypt_init(&cd, hdr_device(rc)) ||
1503             crypt_load(cd, CRYPT_LUKS2, NULL)) {
1504                 r = -EINVAL;
1505                 goto out;
1506         }
1507
1508         if ((r = set_pbkdf_params(cd, CRYPT_LUKS2)))
1509                 goto out;
1510
1511         log_dbg("LUKS2 keyslot pbkdf params change.");
1512
1513         r = -EINVAL;
1514
1515         for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS2); i++) {
1516                 if (!rc->p[i].password)
1517                         continue;
1518                 if ((r = crypt_keyslot_change_by_passphrase(cd, i, i,
1519                         rc->p[i].password, rc->p[i].passwordLen,
1520                         rc->p[i].password, rc->p[i].passwordLen)) < 0)
1521                         goto out;
1522                 log_verbose(_("Changed pbkdf parameters in keyslot %i."), r);
1523                 r = 0;
1524         }
1525
1526         if (r)
1527                 goto out;
1528
1529         /* see create_new_header */
1530         for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS2); i++)
1531                 if (!rc->p[i].password)
1532                         (void)crypt_keyslot_destroy(cd, i);
1533 out:
1534         crypt_free(cd);
1535         return r;
1536 }
1537
1538 static int run_reencrypt(const char *device)
1539 {
1540         int r = -EINVAL;
1541         static struct reenc_ctx rc = {
1542                 .stained = 1
1543         };
1544
1545         set_int_handler(0);
1546
1547         if (initialize_context(&rc, device))
1548                 goto out;
1549
1550         /* short-circuit LUKS2 keyslot parameters change */
1551         if (opt_keep_key && isLUKS2(rc.type)) {
1552                 r = luks2_change_pbkdf_params(&rc);
1553                 goto out;
1554         }
1555
1556         log_dbg("Running reencryption.");
1557
1558         if (!rc.in_progress) {
1559                 if ((r = initialize_passphrase(&rc, hdr_device(&rc))))
1560                         goto out;
1561
1562                 log_dbg("Storing backup of LUKS headers.");
1563                 if (rc.reencrypt_mode == ENCRYPT) {
1564                         /* Create fake header for existing device */
1565                         if ((r = backup_fake_header(&rc)))
1566                                 goto out;
1567                 } else {
1568                         if ((r = backup_luks_headers(&rc)))
1569                                 goto out;
1570                         /* Create fake header for decrypted device */
1571                         if (rc.reencrypt_mode == DECRYPT &&
1572                             (r = backup_fake_header(&rc)))
1573                                 goto out;
1574                         if ((r = device_check(&rc, hdr_device(&rc), MAKE_UNUSABLE)))
1575                                 goto out;
1576                 }
1577         } else {
1578                 if ((r = initialize_passphrase(&rc, opt_decrypt ? rc.header_file_org : rc.header_file_new)))
1579                         goto out;
1580         }
1581
1582         if (!opt_keep_key) {
1583                 log_dbg("Running data area reencryption.");
1584                 if ((r = activate_luks_headers(&rc)))
1585                         goto out;
1586
1587                 if ((r = copy_data(&rc)))
1588                         goto out;
1589         } else
1590                 log_dbg("Keeping existing key, skipping data area reencryption.");
1591
1592         // FIXME: fix error path above to not skip this
1593         if (rc.reencrypt_mode != DECRYPT)
1594                 r = restore_luks_header(&rc);
1595         else
1596                 rc.stained = 0;
1597 out:
1598         destroy_context(&rc);
1599         return r;
1600 }
1601
1602 static void help(poptContext popt_context,
1603                  enum poptCallbackReason reason __attribute__((unused)),
1604                  struct poptOption *key,
1605                  const char *arg __attribute__((unused)),
1606                  void *data __attribute__((unused)))
1607 {
1608         if (key->shortName == '?') {
1609                 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1610                 poptPrintHelp(popt_context, stdout, 0);
1611                 tools_cleanup();
1612                 poptFreeContext(popt_context);
1613                 exit(EXIT_SUCCESS);
1614         } else if (key->shortName == 'V') {
1615                 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1616                 tools_cleanup();
1617                 poptFreeContext(popt_context);
1618                 exit(EXIT_SUCCESS);
1619         } else
1620                 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1621 }
1622
1623 int main(int argc, const char **argv)
1624 {
1625         static struct poptOption popt_help_options[] = {
1626                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
1627                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
1628                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
1629                 { "version",'V', POPT_ARG_NONE,     NULL, 0, N_("Print package version"),  NULL },
1630                 POPT_TABLEEND
1631         };
1632         static struct poptOption popt_options[] = {
1633                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1634                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
1635                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
1636                 { "block-size",        'B',  POPT_ARG_INT, &opt_bsize,                  0, N_("Reencryption block size"), N_("MiB") },
1637                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1638                 { "key-size",          's',  POPT_ARG_INT, &opt_key_size,               0, N_("The size of the encryption key"), N_("BITS") },
1639                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1640                 { "keep-key",          '\0', POPT_ARG_NONE, &opt_keep_key,              0, N_("Do not change key, no data area reencryption"), NULL },
1641                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file"), NULL },
1642                 { "master-key-file",   '\0', POPT_ARG_STRING, &opt_master_key_file,     0, N_("Read new volume (master) key from file"), NULL },
1643                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1644                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
1645                 { "progress-frequency",'\0', POPT_ARG_INT, &opt_progress_frequency,     0, N_("Progress line update (in seconds)"), N_("secs") },
1646                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
1647                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key"), NULL },
1648                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key"), NULL },
1649                 { "use-directio",      '\0', POPT_ARG_NONE, &opt_directio,              0, N_("Use direct-io when accessing devices"), NULL },
1650                 { "use-fsync",         '\0', POPT_ARG_NONE, &opt_fsync,                 0, N_("Use fsync after each block"), NULL },
1651                 { "write-log",         '\0', POPT_ARG_NONE, &opt_write_log,             0, N_("Update log file after every block"), NULL },
1652                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Use only this slot (others will be disabled)"), NULL },
1653                 { "keyfile-offset",   '\0',  POPT_ARG_LONG, &opt_keyfile_offset,        0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1654                 { "keyfile-size",      'l',  POPT_ARG_LONG, &opt_keyfile_size,          0, N_("Limits the read from keyfile"), N_("bytes") },
1655                 { "reduce-device-size",'\0', POPT_ARG_STRING, &opt_reduce_size_str,     0, N_("Reduce data device size (move data offset). DANGEROUS!"), N_("bytes") },
1656                 { "device-size",       '\0', POPT_ARG_STRING, &opt_device_size_str,     0, N_("Use only specified device size (ignore rest of device). DANGEROUS!"), N_("bytes") },
1657                 { "new",               'N',  POPT_ARG_NONE, &opt_new,                   0, N_("Create new header on not encrypted device"), NULL },
1658                 { "decrypt",           '\0', POPT_ARG_NONE, &opt_decrypt,               0, N_("Permanently decrypt device (remove encryption)"), NULL },
1659                 { "uuid",              '\0', POPT_ARG_STRING, &opt_uuid,                0, N_("The UUID used to resume decryption"), NULL },
1660                 { "type",              '\0', POPT_ARG_STRING, &opt_type,                0, N_("Type of LUKS metadata: luks1, luks2"), NULL },
1661                 { "pbkdf",             '\0', POPT_ARG_STRING, &opt_pbkdf,               0, N_("PBKDF algorithm (for LUKS2): argon2i, argon2id, pbkdf2"), NULL },
1662                 { "pbkdf-memory",      '\0', POPT_ARG_LONG, &opt_pbkdf_memory,          0, N_("PBKDF memory cost limit"), N_("kilobytes") },
1663                 { "pbkdf-parallel",    '\0', POPT_ARG_LONG, &opt_pbkdf_parallel,        0, N_("PBKDF parallel cost"), N_("threads") },
1664                 { "pbkdf-force-iterations",'\0',POPT_ARG_LONG, &opt_pbkdf_iterations,   0, N_("PBKDF iterations cost (forced, disables benchmark)"), NULL },
1665                 { "header",            '\0', POPT_ARG_STRING, &opt_header_device,       0, N_("Device or file with separated LUKS header"), NULL },
1666                 POPT_TABLEEND
1667         };
1668         poptContext popt_context;
1669         int r;
1670
1671         crypt_set_log_callback(NULL, tool_log, NULL);
1672
1673         setlocale(LC_ALL, "");
1674         bindtextdomain(PACKAGE, LOCALEDIR);
1675         textdomain(PACKAGE);
1676
1677         popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1678         poptSetOtherOptionHelp(popt_context,
1679                                _("[OPTION...] <device>"));
1680
1681         while((r = poptGetNextOpt(popt_context)) > 0) ;
1682         if (r < -1)
1683                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1684                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1685
1686         if (!opt_batch_mode)
1687                 log_verbose(_("Reencryption will change: %s%s%s%s%s%s."),
1688                         opt_keep_key ? "" :  _("volume key"),
1689                         (!opt_keep_key && opt_hash) ? ", " : "",
1690                         opt_hash   ? _("set hash to ")    : "", opt_hash   ?: "",
1691                         opt_cipher ? _(", set cipher to "): "", opt_cipher ?: "");
1692
1693         action_argv = poptGetArgs(popt_context);
1694         if(!action_argv)
1695                 usage(popt_context, EXIT_FAILURE, _("Argument required."),
1696                       poptGetInvocationName(popt_context));
1697
1698         if (opt_random && opt_urandom)
1699                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1700                       poptGetInvocationName(popt_context));
1701
1702         if (opt_bsize < 0 || opt_key_size < 0 || opt_iteration_time < 0 ||
1703             opt_tries < 0 || opt_keyfile_offset < 0 || opt_key_size < 0 ||
1704             opt_pbkdf_iterations < 0 || opt_pbkdf_memory < 0 ||
1705             opt_pbkdf_parallel < 0) {
1706                 usage(popt_context, EXIT_FAILURE,
1707                       _("Negative number for option not permitted."),
1708                       poptGetInvocationName(popt_context));
1709         }
1710
1711         if (opt_pbkdf && crypt_parse_pbkdf(opt_pbkdf, &set_pbkdf))
1712                 usage(popt_context, EXIT_FAILURE,
1713                 _("Password-based key derivation function (PBKDF) can be only pbkdf2 or argon2i/argon2id."),
1714                 poptGetInvocationName(popt_context));
1715
1716         if (opt_pbkdf_iterations && opt_iteration_time)
1717                 usage(popt_context, EXIT_FAILURE,
1718                 _("PBKDF forced iterations cannot be combined with iteration time option."),
1719                 poptGetInvocationName(popt_context));
1720
1721         if (opt_bsize < 1 || opt_bsize > 64)
1722                 usage(popt_context, EXIT_FAILURE,
1723                       _("Only values between 1 MiB and 64 MiB allowed for reencryption block size."),
1724                       poptGetInvocationName(popt_context));
1725
1726         if (opt_key_size % 8)
1727                 usage(popt_context, EXIT_FAILURE,
1728                       _("Key size must be a multiple of 8 bits"),
1729                       poptGetInvocationName(popt_context));
1730
1731         if (opt_key_slot != CRYPT_ANY_SLOT &&
1732             (opt_key_slot < 0 || opt_key_slot >= crypt_keyslot_max(CRYPT_LUKS2)))
1733                 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1734                       poptGetInvocationName(popt_context));
1735
1736         if (opt_random && opt_urandom)
1737                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1738                       poptGetInvocationName(popt_context));
1739
1740         if (opt_device_size_str &&
1741             tools_string_to_size(NULL, opt_device_size_str, &opt_device_size))
1742                 usage(popt_context, EXIT_FAILURE, _("Invalid device size specification."),
1743                       poptGetInvocationName(popt_context));
1744
1745         if (opt_reduce_size_str &&
1746             tools_string_to_size(NULL, opt_reduce_size_str, &opt_reduce_size))
1747                 usage(popt_context, EXIT_FAILURE, _("Invalid device size specification."),
1748                       poptGetInvocationName(popt_context));
1749         if (opt_reduce_size > 64 * 1024 * 1024)
1750                 usage(popt_context, EXIT_FAILURE, _("Maximum device reduce size is 64 MiB."),
1751                       poptGetInvocationName(popt_context));
1752         if (opt_reduce_size % SECTOR_SIZE)
1753                 usage(popt_context, EXIT_FAILURE, _("Reduce size must be multiple of 512 bytes sector."),
1754                       poptGetInvocationName(popt_context));
1755
1756         if (opt_new && (!opt_reduce_size && !opt_header_device))
1757                 usage(popt_context, EXIT_FAILURE, _("Option --new must be used together with --reduce-device-size or --header."),
1758                       poptGetInvocationName(popt_context));
1759
1760         if (opt_keep_key && (opt_cipher || opt_new || opt_master_key_file))
1761                 usage(popt_context, EXIT_FAILURE, _("Option --keep-key can be used only with --hash, --iter-time or --pbkdf-force-iterations."),
1762                       poptGetInvocationName(popt_context));
1763
1764         if (opt_new && opt_decrypt)
1765                 usage(popt_context, EXIT_FAILURE, _("Option --new cannot be used together with --decrypt."),
1766                       poptGetInvocationName(popt_context));
1767
1768         if (opt_decrypt && (opt_cipher || opt_hash || opt_reduce_size || opt_keep_key || opt_device_size))
1769                 usage(popt_context, EXIT_FAILURE, _("Option --decrypt is incompatible with specified parameters."),
1770                       poptGetInvocationName(popt_context));
1771
1772         if (opt_uuid && !opt_decrypt)
1773                 usage(popt_context, EXIT_FAILURE, _("Option --uuid is allowed only together with --decrypt."),
1774                       poptGetInvocationName(popt_context));
1775
1776         if (!luksType(opt_type))
1777                 usage(popt_context, EXIT_FAILURE, _("Invalid luks type. Use one of these: 'luks', 'luks1' or 'luks2'."),
1778                       poptGetInvocationName(popt_context));
1779
1780         if (opt_debug) {
1781                 opt_verbose = 1;
1782                 crypt_set_debug_level(-1);
1783                 dbg_version_and_cmd(argc, argv);
1784         }
1785
1786         r = run_reencrypt(action_argv[0]);
1787         tools_cleanup();
1788         poptFreeContext(popt_context);
1789         return translate_errno(r);
1790 }