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