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