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