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