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