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