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