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