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