Fix directio aligned buffer.
[platform/upstream/cryptsetup.git] / src / crypt_reencrypt.c
1 /*
2  * crypt_reencrypt - crypt utility for offline reencryption
3  *
4  * Copyright (C) 2012 Milan Broz All rights reserved.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * version 2 as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 #define _LARGEFILE64_SOURCE
21 #define _FILE_OFFSET_BITS 64
22 #define SECTOR_SIZE 512
23
24 #include <string.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdint.h>
28 #include <stdarg.h>
29 #include <inttypes.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <sys/stat.h>
33 #include <sys/ioctl.h>
34 #include <sys/time.h>
35 #include <linux/fs.h>
36 #include <fcntl.h>
37 #include <signal.h>
38 #include <popt.h>
39
40 #include "cryptsetup.h"
41
42 static int opt_verbose = 0;
43 static int opt_debug = 0;
44 static const char *opt_cipher = NULL;
45 static const char *opt_hash = NULL;
46 static const char *opt_key_file = NULL;
47 static long opt_keyfile_size = 0;
48 static long opt_keyfile_offset = 0;
49 static int opt_iteration_time = 1000;
50 static int opt_batch_mode = 0;
51 static int opt_version_mode = 0;
52 static int opt_random = 0;
53 static int opt_urandom = 0;
54 static int opt_bsize = 4;
55 static int opt_directio = 0;
56 static int opt_write_log = 0;
57 static int opt_tries = 3;
58 static int opt_key_slot = CRYPT_ANY_SLOT;
59
60 static const char **action_argv;
61
62 static volatile int quit = 0;
63
64 #define MAX_SLOT 8
65 struct reenc_ctx {
66         char *device;
67         char *device_uuid;
68         uint64_t device_size;
69         uint64_t device_offset;
70         uint64_t device_shift;
71
72         int in_progress:1;
73         enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
74
75         char header_file_org[PATH_MAX];
76         char header_file_new[PATH_MAX];
77         char log_file[PATH_MAX];
78
79         char crypt_path_org[PATH_MAX];
80         char crypt_path_new[PATH_MAX];
81         int log_fd;
82         char *log_buf;
83
84         struct {
85                 char *password;
86                 size_t passwordLen;
87         } p[MAX_SLOT];
88         int keyslot;
89
90         struct timeval start_time, end_time;
91         uint64_t restart_bytes;
92 };
93
94 char MAGIC[]   = {'L','U','K','S', 0xba, 0xbe};
95 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
96 int  MAGIC_L = 6;
97
98 typedef enum {
99         MAKE_UNUSABLE,
100         MAKE_USABLE,
101         CHECK_UNUSABLE
102 } header_magic;
103
104 __attribute__((format(printf, 5, 6)))
105 static void clogger(struct crypt_device *cd, int level, const char *file,
106                    int line, const char *format, ...)
107 {
108         va_list argp;
109         char *target = NULL;
110
111         va_start(argp, format);
112
113         if (vasprintf(&target, format, argp) > 0) {
114                 if (level >= 0) {
115                         crypt_log(cd, level, target);
116                 } else if (opt_debug)
117                         printf("# %s\n", target);
118         }
119
120         va_end(argp);
121         free(target);
122 }
123
124 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
125 {
126         switch(level) {
127
128         case CRYPT_LOG_NORMAL:
129                 fputs(msg, stdout);
130                 break;
131         case CRYPT_LOG_VERBOSE:
132                 if (opt_verbose)
133                         fputs(msg, stdout);
134                 break;
135         case CRYPT_LOG_ERROR:
136                 fputs(msg, stderr);
137                 break;
138         case CRYPT_LOG_DEBUG:
139                 if (opt_debug)
140                         printf("# %s\n", msg);
141                 break;
142         default:
143                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
144                 break;
145         }
146 }
147
148 static void _quiet_log(int level, const char *msg, void *usrptr)
149 {
150         if (!opt_verbose && (level == CRYPT_LOG_ERROR || level == CRYPT_LOG_NORMAL))
151                 level = CRYPT_LOG_VERBOSE;
152         _log(level, msg, usrptr);
153 }
154
155 static void int_handler(int sig __attribute__((__unused__)))
156 {
157         quit++;
158 }
159
160 static void set_int_block(int block)
161 {
162         sigset_t signals_open;
163
164         sigemptyset(&signals_open);
165         sigaddset(&signals_open, SIGINT);
166         sigaddset(&signals_open, SIGTERM);
167         sigprocmask(block ? SIG_SETMASK : SIG_UNBLOCK, &signals_open, NULL);
168 }
169
170 static void set_int_handler(void)
171 {
172         struct sigaction sigaction_open;
173
174         memset(&sigaction_open, 0, sizeof(struct sigaction));
175         sigaction_open.sa_handler = int_handler;
176         sigaction(SIGINT, &sigaction_open, 0);
177         sigaction(SIGTERM, &sigaction_open, 0);
178         set_int_block(0);
179 }
180
181 /* The difference in seconds between two times in "timeval" format. */
182 static double time_diff(struct timeval start, struct timeval end)
183 {
184         return (end.tv_sec - start.tv_sec)
185                 + (end.tv_usec - start.tv_usec) / 1E6;
186 }
187
188 static int alignment(int fd)
189 {
190         int alignment;
191
192         alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
193         if (alignment < 0)
194                 alignment = 4096;
195         return alignment;
196 }
197
198 static int device_magic(struct reenc_ctx *rc, header_magic set_magic)
199 {
200         char *buf = NULL;
201         int r, devfd;
202         ssize_t s;
203
204         devfd = open(rc->device, O_RDWR | O_DIRECT);
205         if (devfd == -1)
206                 return errno == EBUSY ? -EBUSY : -EINVAL;
207
208         if (posix_memalign((void *)&buf, alignment(devfd), SECTOR_SIZE)) {
209                 log_err(_("Allocation of aligned memory failed.\n"));
210                 r = -ENOMEM;
211                 goto out;
212         }
213
214         s = read(devfd, buf, SECTOR_SIZE);
215         if (s < 0 || s != SECTOR_SIZE) {
216                 log_err(_("Cannot read device %s.\n"), rc->device);
217                 close(devfd);
218                 return -EIO;
219         }
220
221         if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L)) {
222                 log_verbose(_("Marking LUKS device %s unusable.\n"), rc->device);
223                 memcpy(buf, NOMAGIC, MAGIC_L);
224                 r = 0;
225
226         } else if (set_magic == MAKE_USABLE && !memcmp(buf, NOMAGIC, MAGIC_L)) {
227                 log_verbose(_("Marking LUKS device %s usable.\n"), rc->device);
228                 memcpy(buf, MAGIC, MAGIC_L);
229                 r = 0;
230         } else if (set_magic == CHECK_UNUSABLE) {
231                 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
232                 if (!r)
233                         rc->device_uuid = strndup(&buf[0xa8], 40);
234                 goto out;
235         } else
236                 r = -EINVAL;
237
238         if (!r) {
239                 if (lseek(devfd, 0, SEEK_SET) == -1)
240                         goto out;
241                 s = write(devfd, buf, SECTOR_SIZE);
242                 if (s < 0 || s != SECTOR_SIZE) {
243                         log_err(_("Cannot write device %s.\n"), rc->device);
244                         r = -EIO;
245                 }
246         } else
247                 log_dbg("LUKS signature check failed for %s.", rc->device);
248 out:
249         if (buf)
250                 memset(buf, 0, SECTOR_SIZE);
251         free(buf);
252         close(devfd);
253         return r;
254 }
255
256 static int create_empty_header(const char *new_file, const char *old_file)
257 {
258         struct stat st;
259         ssize_t size;
260         int fd, r = 0;
261         char *buf;
262
263         if (stat(old_file, &st) == -1 ||
264                  (st.st_mode & S_IFMT) != S_IFREG ||
265                  (st.st_size > 16 * 1024 * 1024))
266                 return -EINVAL;
267         size = st.st_size;
268
269         log_dbg("Creating empty file %s of size %lu.", new_file, (unsigned long)size);
270
271         if (!(buf = malloc(size)))
272                 return -ENOMEM;
273         memset(buf, 0, size);
274
275         fd = creat(new_file, S_IRUSR|S_IWUSR);
276         if(fd == -1) {
277                 free(buf);
278                 return -EINVAL;
279         }
280
281         if (write(fd, buf, size) < size)
282                 r = -EIO;
283
284         close(fd);
285         free(buf);
286         return r;
287 }
288
289 static int write_log(struct reenc_ctx *rc)
290 {
291         ssize_t r;
292
293         memset(rc->log_buf, 0, SECTOR_SIZE);
294         snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
295                 "version = %d\nUUID = %s\ndirection = %d\n"
296                 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
297                 1, rc->device_uuid, rc->reencrypt_direction,
298                 rc->device_offset, rc->device_shift);
299
300         lseek(rc->log_fd, 0, SEEK_SET);
301         r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE);
302         if (r < 0 || r != SECTOR_SIZE) {
303                 log_err(_("Cannot write reencryption log file.\n"));
304                 return -EIO;
305         }
306
307         return 0;
308 }
309
310 static int parse_line_log(struct reenc_ctx *rc, const char *line)
311 {
312         uint64_t u64;
313         int i;
314         char s[64];
315
316         /* whole line is comment */
317         if (*line == '#')
318                 return 0;
319
320         if (sscanf(line, "version = %d", &i) == 1) {
321                 if (i != 1) {
322                         log_dbg("Log: Unexpected version = %i", i);
323                         return -EINVAL;
324                 }
325         } else if (sscanf(line, "UUID = %40s", s) == 1) {
326                 if (!rc->device_uuid || strcmp(rc->device_uuid, s)) {
327                         log_dbg("Log: Unexpected UUID %s", s);
328                         return -EINVAL;
329                 }
330         } else if (sscanf(line, "direction = %d", &i) == 1) {
331                 log_dbg("Log: direction = %i", i);
332                 rc->reencrypt_direction = i;
333         } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
334                 log_dbg("Log: offset = %" PRIu64, u64);
335                 rc->device_offset = u64;
336         } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
337                 log_dbg("Log: shift = %" PRIu64, u64);
338                 rc->device_shift = u64;
339         } else
340                 return -EINVAL;
341
342         return 0;
343 }
344
345 static int parse_log(struct reenc_ctx *rc)
346 {
347         char *start, *end;
348         ssize_t s;
349
350         s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE);
351         if (s == -1) {
352                 log_err(_("Cannot read reencryption log file.\n"));
353                 return -EIO;
354         }
355
356         rc->log_buf[SECTOR_SIZE - 1] = '\0';
357         start = rc->log_buf;
358         do {
359                 end = strchr(start, '\n');
360                 if (end) {
361                         *end++ = '\0';
362                         if (parse_line_log(rc, start)) {
363                                 log_err("Wrong log format.\n");
364                                 return -EINVAL;
365                         }
366                 }
367
368                 start = end;
369         } while (start);
370
371         return 0;
372 }
373
374 static void close_log(struct reenc_ctx *rc)
375 {
376         log_dbg("Closing LUKS reencryption log file %s.", rc->log_file);
377         if (rc->log_fd != -1)
378                 close(rc->log_fd);
379         free(rc->log_buf);
380         rc->log_buf = NULL;
381 }
382
383 static int open_log(struct reenc_ctx *rc)
384 {
385         int flags, create_new;
386         struct stat st;
387
388         if (!stat(rc->log_file, &st))
389                 create_new = 0;
390         else if (errno == ENOENT)
391                 create_new = 1;
392         else
393                 return -EINVAL;
394
395         if (create_new) {
396                 log_dbg("Creating LUKS reencryption log file %s.", rc->log_file);
397                 flags = opt_directio ? O_RDWR|O_CREAT|O_DIRECT : O_RDWR|O_CREAT;
398                 rc->log_fd = open(rc->log_file, flags, S_IRUSR|S_IWUSR);
399                 if (rc->log_fd == -1)
400                         return -EINVAL;
401         } else {
402                 log_dbg("Log file %s exists, restarting.", rc->log_file);
403                 flags = opt_directio ? O_RDWR|O_DIRECT : O_RDWR;
404                 rc->log_fd = open(rc->log_file, flags);
405                 if (rc->log_fd == -1)
406                         return -EINVAL;
407                 rc->in_progress = 1;
408         }
409
410         if (posix_memalign((void *)&rc->log_buf, alignment(rc->log_fd), SECTOR_SIZE)) {
411                 log_err(_("Allocation of aligned memory failed.\n"));
412                 close_log(rc);
413                 return -ENOMEM;
414         }
415
416         if (create_new && write_log(rc) < 0) {
417                 close_log(rc);
418                 return -EIO;
419         }
420
421         /* Be sure it is correct format */
422         return parse_log(rc);
423 }
424
425 static int activate_luks_headers(struct reenc_ctx *rc)
426 {
427         struct crypt_device *cd = NULL, *cd_new = NULL;
428         int r;
429
430         log_dbg("Activating LUKS devices from headers.");
431
432         if ((r = crypt_init(&cd, rc->header_file_org)) ||
433             (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
434             (r = crypt_set_data_device(cd, rc->device)))
435                 goto out;
436
437         if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org,
438                 opt_key_slot, rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen,
439                 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
440                 goto out;
441
442         if ((r = crypt_init(&cd_new, rc->header_file_new)) ||
443             (r = crypt_load(cd_new, CRYPT_LUKS1, NULL)) ||
444             (r = crypt_set_data_device(cd_new, rc->device)))
445                 goto out;
446
447         if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new,
448                 opt_key_slot, rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen,
449                 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
450                 goto out;
451         r = 0;
452 out:
453         crypt_free(cd);
454         crypt_free(cd_new);
455         if (r < 0)
456                 log_err(_("Activation of temporary devices failed.\n"));
457         return r;
458 }
459
460 static int backup_luks_headers(struct reenc_ctx *rc)
461 {
462         struct crypt_device *cd = NULL, *cd_new = NULL;
463         struct crypt_params_luks1 params = {0};
464         char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
465         int i, r;
466
467         log_dbg("Creating LUKS header backup for device %s.", rc->device);
468
469         if ((r = crypt_init(&cd, rc->device)) ||
470             (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
471                 goto out;
472
473         crypt_set_confirm_callback(cd, NULL, NULL);
474         if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rc->header_file_org)))
475                 goto out;
476         log_verbose(_("LUKS header backup of device %s created.\n"), rc->device);
477
478         if ((r = create_empty_header(rc->header_file_new, rc->header_file_org)))
479                 goto out;
480
481         params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
482         params.data_alignment = crypt_get_data_offset(cd);
483         params.data_device = rc->device;
484
485         if ((r = crypt_init(&cd_new, rc->header_file_new)))
486                 goto out;
487
488         if (opt_random)
489                 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
490         else if (opt_urandom)
491                 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
492
493         if (opt_iteration_time)
494                 crypt_set_iteration_time(cd_new, opt_iteration_time);
495
496         if (opt_cipher) {
497                 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
498                 if (r < 0) {
499                         log_err(_("No known cipher specification pattern detected.\n"));
500                         goto out;
501                 }
502         }
503
504         if ((r = crypt_format(cd_new, CRYPT_LUKS1,
505                         opt_cipher ? cipher : crypt_get_cipher(cd),
506                         opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
507                         crypt_get_uuid(cd),
508                         NULL, crypt_get_volume_key_size(cd), &params)))
509                 goto out;
510         log_verbose(_("New LUKS header for device %s created.\n"), rc->device);
511
512         for (i = 0; i < MAX_SLOT; i++) {
513                 if (!rc->p[i].password)
514                         continue;
515                 if ((r = crypt_keyslot_add_by_volume_key(cd_new, i,
516                         NULL, 0, rc->p[i].password, rc->p[i].passwordLen)) < 0)
517                         goto out;
518                 log_verbose(_("Activated keyslot %i.\n"), r);
519                 r = 0;
520         }
521 out:
522         crypt_free(cd);
523         crypt_free(cd_new);
524         if (r)
525                 log_err(_("Creation of LUKS backup headers failed.\n"));
526         return r;
527 }
528
529 static void remove_headers(struct reenc_ctx *rc)
530 {
531         struct crypt_device *cd = NULL;
532
533         log_dbg("Removing headers.");
534
535         if (crypt_init(&cd, NULL))
536                 return;
537         crypt_set_log_callback(cd, _quiet_log, NULL);
538         (void)crypt_deactivate(cd, rc->header_file_org);
539         (void)crypt_deactivate(cd, rc->header_file_new);
540         crypt_free(cd);
541 }
542
543 static int restore_luks_header(struct reenc_ctx *rc)
544 {
545         struct crypt_device *cd = NULL;
546         int r;
547
548         log_dbg("Restoring header for %s from %s.", rc->device, rc->header_file_new);
549
550         r = crypt_init(&cd, rc->device);
551         if (r == 0) {
552                 crypt_set_confirm_callback(cd, NULL, NULL);
553                 r = crypt_header_restore(cd, CRYPT_LUKS1, rc->header_file_new);
554         }
555
556         crypt_free(cd);
557         if (r)
558                 log_err(_("Cannot restore LUKS header on device %s.\n"), rc->device);
559         else
560                 log_verbose(_("LUKS header on device %s restored.\n"), rc->device);
561         return r;
562 }
563
564 static void print_progress(struct reenc_ctx *rc, uint64_t bytes, int final)
565 {
566         uint64_t mbytes = (bytes - rc->restart_bytes) / 1024 / 1024;
567         struct timeval now_time;
568         double tdiff;
569
570         gettimeofday(&now_time, NULL);
571         if (!final && time_diff(rc->end_time, now_time) < 0.5)
572                 return;
573
574         rc->end_time = now_time;
575
576         if (opt_batch_mode)
577                 return;
578
579         tdiff = time_diff(rc->start_time, rc->end_time);
580         if (!tdiff)
581                 return;
582
583         /* vt100 code clear line */
584         log_err("\33[2K\r");
585         log_err(_("Progress: %5.1f%%, time elapsed %4.0f seconds, "
586                 "%4llu MiB written, speed %5.1f MiB/s%s"),
587                 (double)bytes / rc->device_size * 100,
588                 time_diff(rc->start_time, rc->end_time),
589                 (unsigned long long)mbytes, (double)(mbytes) / tdiff,
590                 final ? "\n" :"");
591 }
592
593 static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new,
594                              size_t block_size, void *buf, uint64_t *bytes)
595 {
596         ssize_t s1, s2;
597
598         log_dbg("Reencrypting in forward direction.");
599
600         if (lseek64(fd_old, rc->device_offset, SEEK_SET) < 0 ||
601             lseek64(fd_new, rc->device_offset, SEEK_SET) < 0) {
602                 log_err(_("Cannot seek to device offset.\n"));
603                 return -EIO;
604         }
605
606         rc->restart_bytes = *bytes = rc->device_offset;
607
608         if (write_log(rc) < 0)
609                 return -EIO;
610
611         while (!quit && rc->device_offset < rc->device_size) {
612                 s1 = read(fd_old, buf, block_size);
613                 if (s1 < 0 || ((size_t)s1 != block_size &&
614                     (rc->device_offset + s1) != rc->device_size)) {
615                         log_dbg("Read error, expecting %d, got %d.",
616                                 (int)block_size, (int)s1);
617                         return -EIO;
618                 }
619                 s2 = write(fd_new, buf, s1);
620                 if (s2 < 0) {
621                         log_dbg("Write error, expecting %d, got %d.",
622                                 (int)block_size, (int)s2);
623                         return -EIO;
624                 }
625                 rc->device_offset += s1;
626                 if (opt_write_log && write_log(rc) < 0)
627                         return -EIO;
628
629                 *bytes += (uint64_t)s2;
630                 print_progress(rc, *bytes, 0);
631         }
632
633         return quit ? -EAGAIN : 0;
634 }
635
636 static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new,
637                               size_t block_size, void *buf, uint64_t *bytes)
638 {
639         ssize_t s1, s2, working_block;
640         off64_t working_offset;
641
642         log_dbg("Reencrypting in backward direction.");
643
644         if (!rc->in_progress) {
645                 rc->device_offset = rc->device_size;
646                 rc->restart_bytes = 0;
647                 *bytes = 0;
648         } else {
649                 rc->restart_bytes = rc->device_size - rc->device_offset;
650                 *bytes = rc->restart_bytes;
651         }
652
653         if (write_log(rc) < 0)
654                 return -EIO;
655
656         while (!quit && rc->device_offset) {
657                 if (rc->device_offset < block_size) {
658                         working_offset = 0;
659                         working_block = rc->device_offset;
660                 } else {
661                         working_offset = rc->device_offset - block_size;
662                         working_block = block_size;
663                 }
664
665                 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
666                     lseek64(fd_new, working_offset, SEEK_SET) < 0) {
667                         log_err(_("Cannot seek to device offset.\n"));
668                         return -EIO;
669                 }
670
671                 s1 = read(fd_old, buf, working_block);
672                 if (s1 < 0 || (s1 != working_block)) {
673                         log_dbg("Read error, expecting %d, got %d.",
674                                 (int)block_size, (int)s1);
675                         return -EIO;
676                 }
677                 s2 = write(fd_new, buf, working_block);
678                 if (s2 < 0) {
679                         log_dbg("Write error, expecting %d, got %d.",
680                                 (int)block_size, (int)s2);
681                         return -EIO;
682                 }
683                 rc->device_offset -= s1;
684                 if (opt_write_log && write_log(rc) < 0)
685                         return -EIO;
686
687                 *bytes += (uint64_t)s2;
688                 print_progress(rc, *bytes, 0);
689         }
690
691         return quit ? -EAGAIN : 0;
692 }
693
694 static int copy_data(struct reenc_ctx *rc)
695 {
696         size_t block_size = opt_bsize * 1024 * 1024;
697         int fd_old = -1, fd_new = -1;
698         int r = -EINVAL;
699         void *buf = NULL;
700         uint64_t bytes = 0;
701
702         log_dbg("Data copy preparation.");
703
704         fd_old = open(rc->crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
705         if (fd_old == -1) {
706                 log_err(_("Cannot open temporary LUKS header file.\n"));
707                 goto out;
708         }
709
710         fd_new = open(rc->crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
711         if (fd_new == -1) {
712                 log_err(_("Cannot open temporary LUKS header file.\n"));
713                 goto out;
714         }
715
716         /* Check size */
717         if (ioctl(fd_old, BLKGETSIZE64, &rc->device_size) < 0) {
718                 log_err(_("Cannot get device size.\n"));
719                 goto out;
720         }
721
722         if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
723                 log_err(_("Allocation of aligned memory failed.\n"));
724                 r = -ENOMEM;
725                 goto out;
726         }
727
728         set_int_handler();
729         gettimeofday(&rc->start_time, NULL);
730
731         if (rc->reencrypt_direction == FORWARD)
732                 r = copy_data_forward(rc, fd_old, fd_new, block_size, buf, &bytes);
733         else
734                 r = copy_data_backward(rc, fd_old, fd_new, block_size, buf, &bytes);
735
736         set_int_block(1);
737         print_progress(rc, bytes, 1);
738
739         if (r == -EAGAIN)
740                  log_err(_("Interrupted by a signal.\n"));
741         else if (r < 0)
742                 log_err(_("IO error during reencryption.\n"));
743
744         (void)write_log(rc);
745 out:
746         if (fd_old != -1)
747                 close(fd_old);
748         if (fd_new != -1)
749                 close(fd_new);
750         free(buf);
751         return r;
752 }
753
754 static int initialize_uuid(struct reenc_ctx *rc)
755 {
756         struct crypt_device *cd = NULL;
757         int r;
758
759         log_dbg("Initialising UUID.");
760
761         /* Try to load LUKS from device */
762         if ((r = crypt_init(&cd, rc->device)))
763                 return r;
764         crypt_set_log_callback(cd, _quiet_log, NULL);
765         r = crypt_load(cd, CRYPT_LUKS1, NULL);
766         if (!r)
767                 rc->device_uuid = strdup(crypt_get_uuid(cd));
768         else
769                 /* Reencryption already in progress - magic header? */
770                 r = device_magic(rc, CHECK_UNUSABLE);
771
772         crypt_free(cd);
773         return r;
774 }
775
776 static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd,
777                             const char *msg, int slot_check)
778 {
779         int r = -EINVAL, slot, retry_count;
780
781         slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
782
783         retry_count = opt_tries ?: 1;
784         while (retry_count--) {
785                 r = crypt_get_key(msg, &rc->p[slot].password,
786                         &rc->p[slot].passwordLen,
787                         0, 0, NULL /*opt_key_file*/,
788                         0, 0, cd);
789                 if (r < 0)
790                         return r;
791
792                 r = crypt_activate_by_passphrase(cd, NULL, slot_check,
793                         rc->p[slot].password, rc->p[slot].passwordLen, 0);
794
795                 if (r < 0) {
796                         crypt_safe_free(rc->p[slot].password);
797                         rc->p[slot].password = NULL;
798                         rc->p[slot].passwordLen = 0;
799                 }
800                 if (r < 0 && r != -EPERM)
801                         return r;
802                 if (r >= 0) {
803                         rc->keyslot = slot;
804                         break;
805                 }
806                 log_err(_("No key available with this passphrase.\n"));
807         }
808         return r;
809 }
810
811 static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check)
812 {
813         int r, slot;
814
815         slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
816         r = crypt_get_key(NULL, &rc->p[slot].password, &rc->p[slot].passwordLen,
817                 opt_keyfile_offset, opt_keyfile_size, opt_key_file, 0, 0, cd);
818         if (r < 0)
819                 return r;
820
821         r = crypt_activate_by_passphrase(cd, NULL, slot_check,
822                 rc->p[slot].password, rc->p[slot].passwordLen, 0);
823
824         /*
825          * Allow keyslot only if it is last slot or if user explicitly
826          * specify whch slot to use (IOW others will be disabled).
827          */
828         if (r >= 0 && opt_key_slot == CRYPT_ANY_SLOT &&
829             crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
830                 log_err(_("Key file can be used only with --key-slot or with "
831                           "exactly one key slot active.\n"));
832                 r = -EINVAL;
833         }
834
835         if (r < 0) {
836                 crypt_safe_free(rc->p[slot].password);
837                 rc->p[slot].password = NULL;
838                 rc->p[slot].passwordLen = 0;
839                 if (r == -EPERM)
840                         log_err(_("No key available with this passphrase.\n"));
841                 return r;
842         } else
843                 rc->keyslot = slot;
844
845         return r;
846 }
847
848 static int initialize_passphrase(struct reenc_ctx *rc, const char *device)
849 {
850         struct crypt_device *cd = NULL;
851         crypt_keyslot_info ki;
852         char msg[256];
853         int i, r;
854
855         log_dbg("Passhrases initialization.");
856
857         if ((r = crypt_init(&cd, device)) ||
858             (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
859             (r = crypt_set_data_device(cd, rc->device))) {
860                 crypt_free(cd);
861                 return r;
862         }
863
864         if (opt_key_file) {
865                 r = init_keyfile(rc, cd, opt_key_slot);
866         } else if (rc->in_progress) {
867                 r = init_passphrase1(rc, cd, _("Enter any LUKS passphrase: "), CRYPT_ANY_SLOT);
868         } else for (i = 0; i < MAX_SLOT; i++) {
869                 ki = crypt_keyslot_status(cd, i);
870                 if (ki != CRYPT_SLOT_ACTIVE && ki != CRYPT_SLOT_ACTIVE_LAST)
871                         continue;
872
873                 snprintf(msg, sizeof(msg), _("Enter LUKS passphrase for key slot %u: "), i);
874                 r = init_passphrase1(rc, cd, msg, i);
875                 if (r < 0)
876                         break;
877         }
878
879         crypt_free(cd);
880         return r > 0 ? 0 : r;
881 }
882
883 static int initialize_context(struct reenc_ctx *rc, const char *device)
884 {
885         log_dbg("Initialising reencryption context.");
886
887         rc->log_fd =-1;
888
889         if (!(rc->device = strndup(device, PATH_MAX)))
890                 return -ENOMEM;
891
892         if (initialize_uuid(rc)) {
893                 log_err(_("Device %s is not a valid LUKS device.\n"), device);
894                 return -EINVAL;
895         }
896
897         /* Prepare device names */
898         if (snprintf(rc->log_file, PATH_MAX,
899                      "LUKS-%s.log", rc->device_uuid) < 0)
900                 return -ENOMEM;
901         if (snprintf(rc->header_file_org, PATH_MAX,
902                      "LUKS-%s.org", rc->device_uuid) < 0)
903                 return -ENOMEM;
904         if (snprintf(rc->header_file_new, PATH_MAX,
905                      "LUKS-%s.new", rc->device_uuid) < 0)
906                 return -ENOMEM;
907
908         /* Paths to encrypted devices */
909         if (snprintf(rc->crypt_path_org, PATH_MAX,
910                      "%s/%s", crypt_get_dir(), rc->header_file_org) < 0)
911                 return -ENOMEM;
912         if (snprintf(rc->crypt_path_new, PATH_MAX,
913                      "%s/%s", crypt_get_dir(), rc->header_file_new) < 0)
914                 return -ENOMEM;
915
916         remove_headers(rc);
917
918         if (open_log(rc) < 0) {
919                 log_err(_("Cannot open reencryption log file.\n"));
920                 return -EINVAL;
921         }
922
923         if (!rc->in_progress) {
924                 if (1 /*opt_new */)
925                         rc->reencrypt_direction = FORWARD;
926                 else {
927                         rc->reencrypt_direction = BACKWARD;
928                         rc->device_offset = (uint64_t)~0;
929                 }
930         }
931
932         return 0;
933 }
934
935 static void destroy_context(struct reenc_ctx *rc)
936 {
937         int i;
938
939         log_dbg("Destroying reencryption context.");
940
941         close_log(rc);
942         remove_headers(rc);
943
944         if ((rc->reencrypt_direction == FORWARD &&
945              rc->device_offset == rc->device_size) ||
946              rc->device_offset == 0) {
947                 unlink(rc->log_file);
948                 unlink(rc->header_file_org);
949                 unlink(rc->header_file_new);
950         }
951
952         for (i = 0; i < MAX_SLOT; i++)
953                 crypt_safe_free(rc->p[i].password);
954
955         free(rc->device);
956         free(rc->device_uuid);
957 }
958
959 static int run_reencrypt(const char *device)
960 {
961         int r = -EINVAL;
962         struct reenc_ctx rc = {};
963
964         if (initialize_context(&rc, device))
965                 goto out;
966
967         log_dbg("Running reencryption.");
968
969         if (!rc.in_progress) {
970                 if ((r = initialize_passphrase(&rc, rc.device)) ||
971                     (r = backup_luks_headers(&rc)) ||
972                     (r = device_magic(&rc, MAKE_UNUSABLE)))
973                         goto out;
974         } else {
975                 if ((r = initialize_passphrase(&rc, rc.header_file_new)))
976                         goto out;
977         }
978
979         if ((r = activate_luks_headers(&rc)))
980                 goto out;
981
982         if ((r = copy_data(&rc)))
983                 goto out;
984
985         r = restore_luks_header(&rc);
986 out:
987         destroy_context(&rc);
988         return r;
989 }
990
991 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
992                                              int exitcode, const char *error,
993                                              const char *more)
994 {
995         poptPrintUsage(popt_context, stderr, 0);
996         if (error)
997                 log_err("%s: %s\n", more, error);
998         poptFreeContext(popt_context);
999         exit(exitcode);
1000 }
1001
1002 static void help(poptContext popt_context,
1003                  enum poptCallbackReason reason __attribute__((unused)),
1004                  struct poptOption *key,
1005                  const char *arg __attribute__((unused)),
1006                  void *data __attribute__((unused)))
1007 {
1008         usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1009 }
1010
1011 static void _dbg_version_and_cmd(int argc, const char **argv)
1012 {
1013         int i;
1014
1015         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
1016         for (i = 0; i < argc; i++) {
1017                 if (i)
1018                         log_std(" ");
1019                 log_std("%s", argv[i]);
1020         }
1021         log_std("\"\n");
1022 }
1023
1024 int main(int argc, const char **argv)
1025 {
1026         static struct poptOption popt_help_options[] = {
1027                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
1028                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
1029                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
1030                 POPT_TABLEEND
1031         };
1032         static struct poptOption popt_options[] = {
1033                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1034                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
1035                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
1036                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
1037                 { "block-size",        'B',  POPT_ARG_INT, &opt_bsize,                  0, N_("Reencryption block size"), N_("MiB") },
1038                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1039                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1040                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
1041                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1042                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
1043                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
1044                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
1045                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
1046                 { "use-directio",      '\0', POPT_ARG_NONE, &opt_directio,              0, N_("Use direct-io when accesing devices."), NULL },
1047                 { "write-log",         '\0', POPT_ARG_NONE, &opt_write_log,             0, N_("Update log file after every block."), NULL },
1048                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Use only this slot (others will be disabled)."), NULL },
1049                 { "keyfile-offset",   '\0',  POPT_ARG_LONG, &opt_keyfile_offset,        0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1050                 { "keyfile-size",      'l',  POPT_ARG_LONG, &opt_keyfile_size,          0, N_("Limits the read from keyfile"), N_("bytes") },
1051                 POPT_TABLEEND
1052         };
1053         poptContext popt_context;
1054         int r;
1055
1056         crypt_set_log_callback(NULL, _log, NULL);
1057
1058         set_int_block(1);
1059
1060         setlocale(LC_ALL, "");
1061         bindtextdomain(PACKAGE, LOCALEDIR);
1062         textdomain(PACKAGE);
1063
1064         popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1065         poptSetOtherOptionHelp(popt_context,
1066                                N_("[OPTION...] <device>]"));
1067
1068         while((r = poptGetNextOpt(popt_context)) > 0) {
1069                 if (r < 0)
1070                         break;
1071         }
1072
1073         if (r < -1)
1074                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1075                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1076         if (opt_version_mode) {
1077                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1078                 poptFreeContext(popt_context);
1079                 exit(EXIT_SUCCESS);
1080         }
1081
1082         if (!opt_batch_mode)
1083                 log_err(_("WARNING: this is experimental code, it can completely break your data.\n"));
1084
1085         action_argv = poptGetArgs(popt_context);
1086         if(!action_argv)
1087                 usage(popt_context, EXIT_FAILURE, _("Argument required."),
1088                       poptGetInvocationName(popt_context));
1089
1090         if (opt_random && opt_urandom)
1091                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1092                       poptGetInvocationName(popt_context));
1093
1094         if (opt_bsize < 1 || opt_bsize > 64)
1095                 usage(popt_context, EXIT_FAILURE,
1096                       _("Only values between 1MiB and 64 MiB allowed for reencryption block size."),
1097                       poptGetInvocationName(popt_context));
1098
1099         if (opt_debug) {
1100                 opt_verbose = 1;
1101                 crypt_set_debug_level(-1);
1102                 _dbg_version_and_cmd(argc, argv);
1103         }
1104
1105         r = run_reencrypt(action_argv[0]);
1106
1107         poptFreeContext(popt_context);
1108
1109         /* Translate exit code to simple codes */
1110         switch (r) {
1111         case 0:         r = EXIT_SUCCESS; break;
1112         case -EEXIST:
1113         case -EBUSY:    r = 5; break;
1114         case -ENOTBLK:
1115         case -ENODEV:   r = 4; break;
1116         case -ENOMEM:   r = 3; break;
1117         case -EPERM:    r = 2; break;
1118         case -EAGAIN:
1119         case -EINVAL:
1120         case -ENOENT:
1121         case -ENOSYS:
1122         default:        r = EXIT_FAILURE;
1123         }
1124         return r;
1125 }