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