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