Loop is automatically allocated in crypt_set_data_device().
[platform/upstream/cryptsetup.git] / lib / setup.c
1 /*
2  * libcryptsetup - cryptsetup library
3  *
4  * Copyright (C) 2004, Christophe Saout <christophe@saout.de>
5  * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
6  * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * version 2 as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include <string.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <fcntl.h>
27 #include <errno.h>
28
29 #include "libcryptsetup.h"
30 #include "luks.h"
31 #include "loopaes.h"
32 #include "verity.h"
33 #include "internal.h"
34
35 struct crypt_device {
36         char *type;
37
38         char *device;
39         char *metadata_device;
40
41         /* loopback automatic detach helpers */
42         int loop_device_fd;
43         int loop_metadata_device_fd;
44
45         struct volume_key *volume_key;
46         uint64_t timeout;
47         uint64_t iteration_time;
48         int tries;
49         int password_verify;
50         int rng_type;
51
52         /* used in CRYPT_LUKS1 */
53         struct luks_phdr hdr;
54         uint64_t PBKDF2_per_sec;
55
56         /* used in CRYPT_PLAIN */
57         struct crypt_params_plain plain_hdr;
58         char *plain_cipher;
59         char *plain_cipher_mode;
60         char *plain_uuid;
61         unsigned int plain_key_size;
62
63         /* used in CRYPT_LOOPAES */
64         struct crypt_params_loopaes loopaes_hdr;
65         char *loopaes_cipher;
66         char *loopaes_cipher_mode;
67         char *loopaes_uuid;
68         unsigned int loopaes_key_size;
69
70         /* used in CRYPT_VERITY */
71         struct crypt_params_verity verity_hdr;
72         char *verity_root_hash;
73         uint64_t verity_root_hash_size;
74         char *verity_uuid;
75
76         /* callbacks definitions */
77         void (*log)(int level, const char *msg, void *usrptr);
78         void *log_usrptr;
79         int (*confirm)(const char *msg, void *usrptr);
80         void *confirm_usrptr;
81         int (*password)(const char *msg, char *buf, size_t length, void *usrptr);
82         void *password_usrptr;
83
84         /* last error message */
85         char error[MAX_ERROR_LENGTH];
86 };
87
88 /* Global error */
89 /* FIXME: not thread safe, remove this later */
90 static char global_error[MAX_ERROR_LENGTH] = {0};
91
92 /* Log helper */
93 static void (*_default_log)(int level, const char *msg, void *usrptr) = NULL;
94 static int _debug_level = 0;
95
96 void crypt_set_debug_level(int level)
97 {
98         _debug_level = level;
99 }
100
101 int crypt_get_debug_level(void)
102 {
103         return _debug_level;
104 }
105
106 static void crypt_set_error(struct crypt_device *cd, const char *error)
107 {
108         size_t size = strlen(error);
109
110         /* Set global error, ugly hack... */
111         strncpy(global_error, error, MAX_ERROR_LENGTH - 2);
112         if (size < MAX_ERROR_LENGTH && global_error[size - 1] == '\n')
113                 global_error[size - 1] = '\0';
114
115         /* Set error string per context */
116         if (cd) {
117                 strncpy(cd->error, error, MAX_ERROR_LENGTH - 2);
118                 if (size < MAX_ERROR_LENGTH && cd->error[size - 1] == '\n')
119                         cd->error[size - 1] = '\0';
120         }
121 }
122
123 void crypt_log(struct crypt_device *cd, int level, const char *msg)
124 {
125         if (cd && cd->log)
126                 cd->log(level, msg, cd->log_usrptr);
127         else if (_default_log)
128                 _default_log(level, msg, NULL);
129
130         if (level == CRYPT_LOG_ERROR)
131                 crypt_set_error(cd, msg);
132 }
133
134 __attribute__((format(printf, 5, 6)))
135 void logger(struct crypt_device *cd, int level, const char *file,
136             int line, const char *format, ...)
137 {
138         va_list argp;
139         char *target = NULL;
140
141         va_start(argp, format);
142
143         if (vasprintf(&target, format, argp) > 0 ) {
144                 if (level >= 0) {
145                         crypt_log(cd, level, target);
146 #ifdef CRYPT_DEBUG
147                 } else if (_debug_level)
148                         printf("# %s:%d %s\n", file ?: "?", line, target);
149 #else
150                 } else if (_debug_level)
151                         printf("# %s\n", target);
152 #endif
153         }
154
155         va_end(argp);
156         free(target);
157 }
158
159 static const char *mdata_device(struct crypt_device *cd)
160 {
161         return cd->metadata_device ?: cd->device;
162 }
163
164 static int init_crypto(struct crypt_device *ctx)
165 {
166         int r;
167
168         crypt_fips_libcryptsetup_check(ctx);
169
170         r = crypt_random_init(ctx);
171         if (r < 0) {
172                 log_err(ctx, _("Cannot initialize crypto RNG backend.\n"));
173                 return r;
174         }
175
176         r = crypt_backend_init(ctx);
177         if (r < 0)
178                 log_err(ctx, _("Cannot initialize crypto backend.\n"));
179
180         log_dbg("Crypto backend (%s) initialized.", crypt_backend_version());
181         return r;
182 }
183
184 static int process_key(struct crypt_device *cd, const char *hash_name,
185                        size_t key_size, const char *pass, size_t passLen,
186                        struct volume_key **vk)
187 {
188         int r;
189
190         if (!key_size)
191                 return -EINVAL;
192
193         *vk = crypt_alloc_volume_key(key_size, NULL);
194         if (!*vk)
195                 return -ENOMEM;
196
197         if (hash_name) {
198                 r = crypt_plain_hash(cd, hash_name, (*vk)->key, key_size, pass, passLen);
199                 if (r < 0) {
200                         if (r == -ENOENT)
201                                 log_err(cd, _("Hash algorithm %s not supported.\n"),
202                                         hash_name);
203                         else
204                                 log_err(cd, _("Key processing error (using hash %s).\n"),
205                                         hash_name);
206                         crypt_free_volume_key(*vk);
207                         *vk = NULL;
208                         return -EINVAL;
209                 }
210         } else if (passLen > key_size) {
211                 memcpy((*vk)->key, pass, key_size);
212         } else {
213                 memcpy((*vk)->key, pass, passLen);
214         }
215
216         return 0;
217 }
218
219 static int isPLAIN(const char *type)
220 {
221         return (type && !strcmp(CRYPT_PLAIN, type));
222 }
223
224 static int isLUKS(const char *type)
225 {
226         return (type && !strcmp(CRYPT_LUKS1, type));
227 }
228
229 static int isLOOPAES(const char *type)
230 {
231         return (type && !strcmp(CRYPT_LOOPAES, type));
232 }
233
234 static int isVERITY(const char *type)
235 {
236         return (type && !strcmp(CRYPT_VERITY, type));
237 }
238
239 /* keyslot helpers */
240 static int keyslot_verify_or_find_empty(struct crypt_device *cd, int *keyslot)
241 {
242         if (*keyslot == CRYPT_ANY_SLOT) {
243                 *keyslot = LUKS_keyslot_find_empty(&cd->hdr);
244                 if (*keyslot < 0) {
245                         log_err(cd, _("All key slots full.\n"));
246                         return -EINVAL;
247                 }
248         }
249
250         switch (LUKS_keyslot_info(&cd->hdr, *keyslot)) {
251                 case CRYPT_SLOT_INVALID:
252                         log_err(cd, _("Key slot %d is invalid, please select between 0 and %d.\n"),
253                                 *keyslot, LUKS_NUMKEYS - 1);
254                         return -EINVAL;
255                 case CRYPT_SLOT_INACTIVE:
256                         break;
257                 default:
258                         log_err(cd, _("Key slot %d is full, please select another one.\n"),
259                                 *keyslot);
260                         return -EINVAL;
261         }
262
263         return 0;
264 }
265
266 /*
267  * compares UUIDs returned by device-mapper (striped by cryptsetup) and uuid in header
268  */
269 static int crypt_uuid_cmp(const char *dm_uuid, const char *hdr_uuid)
270 {
271         int i, j;
272         char *str;
273
274         if (!dm_uuid || !hdr_uuid)
275                 return -EINVAL;
276
277         str = strchr(dm_uuid, '-');
278         if (!str)
279                 return -EINVAL;
280
281         for (i = 0, j = 1; hdr_uuid[i]; i++) {
282                 if (hdr_uuid[i] == '-')
283                         continue;
284
285                 if (!str[j] || str[j] == '-')
286                         return -EINVAL;
287
288                 if (str[j] != hdr_uuid[i])
289                         return -EINVAL;
290                 j++;
291         }
292
293         return 0;
294 }
295
296 int PLAIN_activate(struct crypt_device *cd,
297                      const char *name,
298                      struct volume_key *vk,
299                      uint64_t size,
300                      uint32_t flags)
301 {
302         int r;
303         char *dm_cipher = NULL;
304         enum devcheck device_check;
305         struct crypt_dm_active_device dmd = {
306                 .target = DM_CRYPT,
307                 .uuid   = crypt_get_uuid(cd),
308                 .size   = size,
309                 .flags  = flags,
310                 .data_device = crypt_get_device_name(cd),
311                 .u.crypt  = {
312                         .cipher = NULL,
313                         .vk     = vk,
314                         .offset = crypt_get_data_offset(cd),
315                         .iv_offset = crypt_get_iv_offset(cd),
316                 }
317         };
318
319         if (dmd.flags & CRYPT_ACTIVATE_SHARED)
320                 device_check = DEV_SHARED;
321         else
322                 device_check = DEV_EXCL;
323
324         r = device_check_and_adjust(cd, dmd.data_device, device_check,
325                                     &dmd.size, &dmd.u.crypt.offset, &dmd.flags);
326         if (r)
327                 return r;
328
329         if (crypt_get_cipher_mode(cd))
330                 r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
331         else
332                 r = asprintf(&dm_cipher, "%s", crypt_get_cipher(cd));
333         if (r < 0)
334                 return -ENOMEM;
335
336         dmd.u.crypt.cipher = dm_cipher;
337         log_dbg("Trying to activate PLAIN device %s using cipher %s.",
338                 name, dmd.u.crypt.cipher);
339
340         r = dm_create_device(name, CRYPT_PLAIN, &dmd, 0);
341
342         // FIXME
343         if (!cd->plain_uuid && dm_query_device(name, DM_ACTIVE_UUID, &dmd) >= 0)
344                 cd->plain_uuid = CONST_CAST(char*)dmd.uuid;
345
346         free(dm_cipher);
347         return r;
348 }
349
350 int crypt_confirm(struct crypt_device *cd, const char *msg)
351 {
352         if (!cd || !cd->confirm)
353                 return 1;
354         else
355                 return cd->confirm(msg, cd->confirm_usrptr);
356 }
357
358 static int key_from_terminal(struct crypt_device *cd, char *msg, char **key,
359                               size_t *key_len, int force_verify)
360 {
361         char *prompt = NULL, *device_name;
362         int r;
363
364         *key = NULL;
365         if(!msg) {
366                 if (crypt_loop_device(crypt_get_device_name(cd)))
367                         device_name = crypt_loop_backing_file(crypt_get_device_name(cd));
368                 else
369                         device_name = strdup(crypt_get_device_name(cd));
370                 if (!device_name)
371                         return -ENOMEM;
372                 r = asprintf(&prompt, _("Enter passphrase for %s: "), device_name);
373                 free(device_name);
374                 if (r < 0)
375                         return -ENOMEM;
376                 msg = prompt;
377         }
378
379         if (cd->password) {
380                 *key = crypt_safe_alloc(DEFAULT_PASSPHRASE_SIZE_MAX);
381                 if (!*key) {
382                         r = -ENOMEM;
383                         goto out;
384                 }
385                 r = cd->password(msg, *key, DEFAULT_PASSPHRASE_SIZE_MAX,
386                                  cd->password_usrptr);
387                 if (r < 0) {
388                         crypt_safe_free(*key);
389                         *key = NULL;
390                 } else
391                         *key_len = r;
392         } else
393                 r = crypt_get_key(msg, key, key_len, 0, 0, NULL, cd->timeout,
394                                   (force_verify || cd->password_verify), cd);
395 out:
396         free(prompt);
397         return (r < 0) ? r: 0;
398 }
399
400 static int volume_key_by_terminal_passphrase(struct crypt_device *cd, int keyslot,
401                                              struct volume_key **vk)
402 {
403         char *passphrase_read = NULL;
404         size_t passphrase_size_read;
405         int r = -EINVAL, eperm = 0, tries = cd->tries;
406
407         *vk = NULL;
408         do {
409                 crypt_free_volume_key(*vk);
410                 *vk = NULL;
411
412                 r = key_from_terminal(cd, NULL, &passphrase_read,
413                                       &passphrase_size_read, 0);
414                 /* Continue if it is just passphrase verify mismatch */
415                 if (r == -EPERM)
416                         continue;
417                 if(r < 0)
418                         goto out;
419
420                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase_read,
421                                            passphrase_size_read, &cd->hdr, vk, cd);
422                 if (r == -EPERM)
423                         eperm = 1;
424                 crypt_safe_free(passphrase_read);
425                 passphrase_read = NULL;
426         } while (r == -EPERM && (--tries > 0));
427 out:
428         if (r < 0) {
429                 crypt_free_volume_key(*vk);
430                 *vk = NULL;
431
432                 /* Report wrong passphrase if at least one try failed */
433                 if (eperm && r == -EPIPE)
434                         r = -EPERM;
435         }
436
437         crypt_safe_free(passphrase_read);
438         return r;
439 }
440
441 static int key_from_file(struct crypt_device *cd, char *msg,
442                           char **key, size_t *key_len,
443                           const char *key_file, size_t key_offset,
444                           size_t key_size)
445 {
446         return crypt_get_key(msg, key, key_len, key_offset, key_size, key_file,
447                              cd->timeout, 0, cd);
448 }
449
450 void crypt_set_log_callback(struct crypt_device *cd,
451         void (*log)(int level, const char *msg, void *usrptr),
452         void *usrptr)
453 {
454         if (!cd)
455                 _default_log = log;
456         else {
457                 cd->log = log;
458                 cd->log_usrptr = usrptr;
459         }
460 }
461
462 void crypt_set_confirm_callback(struct crypt_device *cd,
463         int (*confirm)(const char *msg, void *usrptr),
464         void *usrptr)
465 {
466         cd->confirm = confirm;
467         cd->confirm_usrptr = usrptr;
468 }
469
470 void crypt_set_password_callback(struct crypt_device *cd,
471         int (*password)(const char *msg, char *buf, size_t length, void *usrptr),
472         void *usrptr)
473 {
474         cd->password = password;
475         cd->password_usrptr = usrptr;
476 }
477
478 static void _get_error(char *error, char *buf, size_t size)
479 {
480         if (!buf || size < 1)
481                 error[0] = '\0';
482         else if (*error) {
483                 strncpy(buf, error, size - 1);
484                 buf[size - 1] = '\0';
485                 error[0] = '\0';
486         } else
487                 buf[0] = '\0';
488 }
489
490 void crypt_last_error(struct crypt_device *cd, char *buf, size_t size)
491 {
492         if (cd)
493                 return _get_error(cd->error, buf, size);
494 }
495
496 /* Deprecated global error interface */
497 void crypt_get_error(char *buf, size_t size)
498 {
499         return _get_error(global_error, buf, size);
500 }
501
502 const char *crypt_get_dir(void)
503 {
504         return dm_get_dir();
505 }
506
507 static int set_device_or_loop(const char *device_org, char **device, int *loop_fd)
508 {
509         int r, readonly = 0;
510
511         if (!device_org)
512                 return 0;
513
514         r = device_ready(NULL, device_org, O_RDONLY);
515         if (r == -ENOTBLK) {
516                 *device = crypt_loop_get_device();
517                 log_dbg("Not a block device, %s%s.", *device ?
518                         "using free loop device " : "no free loop device found",
519                         *device ?: "");
520                 if (!*device) {
521                         log_err(NULL, _("Cannot find a free loopback device.\n"));
522                         return -ENOSYS;
523                 }
524
525                 /* Keep the loop open, dettached on last close. */
526                 *loop_fd = crypt_loop_attach(*device, device_org, 0, 1, &readonly);
527                 if (*loop_fd == -1) {
528                         log_err(NULL, _("Attaching loopback device failed "
529                                 "(loop device with autoclear flag is required).\n"));
530                         return -EINVAL;
531                 }
532
533                 r = device_ready(NULL, *device, O_RDONLY);
534         }
535
536         if (r < 0)
537                 return -ENOTBLK;
538
539         if (!*device && device_org && !(*device = strdup(device_org)))
540                 return -ENOMEM;
541
542         return 0;
543 }
544
545 int crypt_init(struct crypt_device **cd, const char *device)
546 {
547         struct crypt_device *h = NULL;
548         int r;
549
550         if (!cd)
551                 return -EINVAL;
552
553         log_dbg("Allocating crypt device %s context.", device);
554
555         if (!(h = malloc(sizeof(struct crypt_device))))
556                 return -ENOMEM;
557
558         memset(h, 0, sizeof(*h));
559         h->loop_device_fd = -1;
560         h->loop_metadata_device_fd = -1;
561
562         r = set_device_or_loop(device, &h->device, &h->loop_device_fd);
563         if (r < 0)
564                 goto bad;
565
566         if (dm_init(h, 1) < 0) {
567                 r = -ENOSYS;
568                 goto bad;
569         }
570
571         h->iteration_time = 1000;
572         h->password_verify = 0;
573         h->tries = 3;
574         h->rng_type = crypt_random_default_key_rng();
575         *cd = h;
576         return 0;
577 bad:
578
579         if (h) {
580                 if (h->loop_device_fd != -1)
581                         close(h->loop_device_fd);
582                 free(h->device);
583         }
584         free(h);
585         return r;
586 }
587
588 static int crypt_check_data_device_size(struct crypt_device *cd)
589 {
590         int r;
591         uint64_t size, size_min;
592
593         /* Check data device size, require at least one sector */
594         size_min = crypt_get_data_offset(cd) << SECTOR_SHIFT ?: SECTOR_SIZE;
595
596         r = device_size(crypt_get_device_name(cd), &size);
597         if (r < 0)
598                 return r;
599
600         if (size < size_min) {
601                 log_err(cd, _("LUKS header detected but device %s is too small.\n"),
602                         crypt_get_device_name(cd));
603                 return -EINVAL;
604         }
605
606         return r;
607 }
608
609 int crypt_set_data_device(struct crypt_device *cd, const char *device)
610 {
611         char *data_device = NULL;
612         int r, loop_fd = -1;
613
614         log_dbg("Setting ciphertext data device to %s.", device ?: "(none)");
615
616         if (!isLUKS(cd->type) && !isVERITY(cd->type)) {
617                 log_err(cd, _("This operation is not supported for this device type.\n"));
618                 return  -EINVAL;
619         }
620
621         /* metadata device must be set */
622         if (!cd->device || !device)
623                 return -EINVAL;
624
625         r = set_device_or_loop(device, &data_device, &loop_fd);
626         if (r < 0)
627                 return r;
628
629         if (!cd->metadata_device) {
630                 cd->metadata_device = cd->device;
631                 cd->loop_metadata_device_fd = cd->loop_device_fd;
632         } else {
633                 free(cd->device);
634                 if (cd->loop_device_fd != -1)
635                         close(cd->loop_device_fd);
636         }
637
638         cd->device = data_device;
639         cd->loop_device_fd = loop_fd;
640
641         return crypt_check_data_device_size(cd);
642 }
643
644 static int _crypt_load_luks1(struct crypt_device *cd, int require_header, int repair)
645 {
646         struct luks_phdr hdr;
647         int r;
648
649         r = init_crypto(cd);
650         if (r < 0)
651                 return r;
652
653         r = LUKS_read_phdr(mdata_device(cd), &hdr, require_header, repair, cd);
654         if (r < 0)
655                 return r;
656
657         if (!cd->type && !(cd->type = strdup(CRYPT_LUKS1)))
658                 return -ENOMEM;
659
660         memcpy(&cd->hdr, &hdr, sizeof(hdr));
661
662         return r;
663 }
664
665 static int _crypt_load_verity(struct crypt_device *cd, struct crypt_params_verity *params)
666 {
667         int r;
668         size_t sb_offset = 0;
669
670         r = init_crypto(cd);
671         if (r < 0)
672                 return r;
673
674         if (params->flags & CRYPT_VERITY_NO_HEADER)
675                 return -EINVAL;
676
677         if (params)
678                 sb_offset = params->hash_area_offset;
679
680         r = VERITY_read_sb(cd, mdata_device(cd), sb_offset,
681                            &cd->verity_uuid, &cd->verity_hdr);
682         if (r < 0)
683                 return r;
684
685         if (params)
686                 cd->verity_hdr.flags = params->flags;
687
688         if (params && params->data_device &&
689             (r = crypt_set_data_device(cd, params->data_device)) < 0)
690                 return r;
691
692         cd->verity_root_hash_size = crypt_hash_size(cd->verity_hdr.hash_name);
693
694         if (!cd->type && !(cd->type = strdup(CRYPT_VERITY)))
695                 return -ENOMEM;
696
697         return r;
698 }
699
700 static int _init_by_name_crypt(struct crypt_device *cd, const char *name)
701 {
702         struct crypt_dm_active_device dmd = {};
703         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
704         int key_nums, r;
705
706         r = dm_query_device(name, DM_ACTIVE_DEVICE |
707                                    DM_ACTIVE_UUID |
708                                    DM_ACTIVE_CRYPT_CIPHER |
709                                    DM_ACTIVE_CRYPT_KEYSIZE, &dmd);
710         if (r < 0)
711                 goto out;
712
713         if (isPLAIN(cd->type)) {
714                 cd->plain_uuid = dmd.uuid ? strdup(dmd.uuid) : NULL;
715                 cd->plain_hdr.hash = NULL; /* no way to get this */
716                 cd->plain_hdr.offset = dmd.u.crypt.offset;
717                 cd->plain_hdr.skip = dmd.u.crypt.iv_offset;
718                 cd->plain_key_size = dmd.u.crypt.vk->keylength;
719
720                 r = crypt_parse_name_and_mode(dmd.u.crypt.cipher, cipher, NULL, cipher_mode);
721                 if (!r) {
722                         cd->plain_cipher = strdup(cipher);
723                         cd->plain_cipher_mode = strdup(cipher_mode);
724                 }
725         } else if (isLOOPAES(cd->type)) {
726                 cd->loopaes_uuid = dmd.uuid ? strdup(dmd.uuid) : NULL;
727                 cd->loopaes_hdr.offset = dmd.u.crypt.offset;
728
729                 r = crypt_parse_name_and_mode(dmd.u.crypt.cipher, cipher,
730                                               &key_nums, cipher_mode);
731                 if (!r) {
732                         cd->loopaes_cipher = strdup(cipher);
733                         cd->loopaes_cipher_mode = strdup(cipher_mode);
734                         /* version 3 uses last key for IV */
735                         if (dmd.u.crypt.vk->keylength % key_nums)
736                                 key_nums++;
737                         cd->loopaes_key_size = dmd.u.crypt.vk->keylength / key_nums;
738                 }
739         } else if (isLUKS(cd->type)) {
740                 if (mdata_device(cd)) {
741                         r = _crypt_load_luks1(cd, 0, 0);
742                         if (r < 0) {
743                                 log_dbg("LUKS device header does not match active device.");
744                                 free(cd->type);
745                                 cd->type = NULL;
746                                 r = 0;
747                                 goto out;
748                         }
749                         /* check whether UUIDs match each other */
750                         r = crypt_uuid_cmp(dmd.uuid, cd->hdr.uuid);
751                         if (r < 0) {
752                                 log_dbg("LUKS device header uuid: %s mismatches DM returned uuid %s",
753                                         cd->hdr.uuid, dmd.uuid);
754                                 free(cd->type);
755                                 cd->type = NULL;
756                                 r = 0;
757                                 goto out;
758                         }
759                 }
760         }
761 out:
762         crypt_free_volume_key(dmd.u.crypt.vk);
763         free(CONST_CAST(void*)dmd.u.crypt.cipher);
764         free(CONST_CAST(void*)dmd.data_device);
765         free(CONST_CAST(void*)dmd.uuid);
766         return r;
767 }
768
769 static int _init_by_name_verity(struct crypt_device *cd, const char *name)
770 {
771         struct crypt_params_verity params = {};
772         struct crypt_dm_active_device dmd = {
773                 .target = DM_VERITY,
774                 .u.verity.vp = &params,
775         };
776         int r;
777
778         r = dm_query_device(name, DM_ACTIVE_DEVICE |
779                                    DM_ACTIVE_UUID |
780                                    DM_ACTIVE_VERITY_HASH_DEVICE |
781                                    DM_ACTIVE_VERITY_PARAMS, &dmd);
782         if (r < 0)
783                 goto out;
784
785         if (isVERITY(cd->type)) {
786                 cd->verity_uuid = dmd.uuid ? strdup(dmd.uuid) : NULL;
787                 cd->verity_hdr.flags = CRYPT_VERITY_NO_HEADER; //FIXME
788                 cd->verity_hdr.data_size = params.data_size;
789                 cd->verity_root_hash_size = dmd.u.verity.root_hash_size;
790                 cd->verity_root_hash = NULL;
791                 cd->verity_hdr.hash_name = params.hash_name;
792                 cd->verity_hdr.data_device = NULL;
793                 cd->verity_hdr.hash_device = NULL;
794                 cd->verity_hdr.data_block_size = params.data_block_size;
795                 cd->verity_hdr.hash_block_size = params.hash_block_size;
796                 cd->verity_hdr.hash_area_offset = dmd.u.verity.hash_offset;
797                 cd->verity_hdr.hash_type = params.hash_type;
798                 cd->verity_hdr.flags = params.flags;
799                 cd->verity_hdr.salt_size = params.salt_size;
800                 cd->verity_hdr.salt = params.salt;
801                 if (!(cd->metadata_device = strdup(dmd.u.verity.hash_device)))
802                         r = -ENOMEM;
803         }
804 out:
805         free(CONST_CAST(void*)dmd.u.verity.hash_device);
806         free(CONST_CAST(void*)dmd.data_device);
807         free(CONST_CAST(void*)dmd.uuid);
808         return r;
809 }
810
811 int crypt_init_by_name_and_header(struct crypt_device **cd,
812                                   const char *name,
813                                   const char *header_device)
814 {
815         crypt_status_info ci;
816         struct crypt_dm_active_device dmd;
817         int r;
818
819         log_dbg("Allocating crypt device context by device %s.", name);
820
821         ci = crypt_status(NULL, name);
822         if (ci == CRYPT_INVALID)
823                 return -ENODEV;
824
825         if (ci < CRYPT_ACTIVE) {
826                 log_err(NULL, _("Device %s is not active.\n"), name);
827                 return -ENODEV;
828         }
829
830         r = dm_query_device(name, DM_ACTIVE_DEVICE | DM_ACTIVE_UUID, &dmd);
831         if (r < 0)
832                 goto out;
833
834         *cd = NULL;
835
836         if (header_device) {
837                 r = crypt_init(cd, header_device);
838         } else {
839                 r = crypt_init(cd, dmd.data_device);
840
841                 /* Underlying device disappeared but mapping still active */
842                 if (!dmd.data_device || r == -ENOTBLK)
843                         log_verbose(NULL, _("Underlying device for crypt device %s disappeared.\n"),
844                                     name);
845
846                 /* Underlying device is not readable but crypt mapping exists */
847                 if (r == -ENOTBLK) {
848                         free(CONST_CAST(void*)dmd.data_device);
849                         dmd.data_device = NULL;
850                         r = crypt_init(cd, NULL);
851                 }
852         }
853
854         if (r < 0)
855                 goto out;
856
857         if (dmd.uuid) {
858                 if (!strncmp(CRYPT_PLAIN, dmd.uuid, sizeof(CRYPT_PLAIN)-1))
859                         (*cd)->type = strdup(CRYPT_PLAIN);
860                 else if (!strncmp(CRYPT_LOOPAES, dmd.uuid, sizeof(CRYPT_LOOPAES)-1))
861                         (*cd)->type = strdup(CRYPT_LOOPAES);
862                 else if (!strncmp(CRYPT_LUKS1, dmd.uuid, sizeof(CRYPT_LUKS1)-1))
863                         (*cd)->type = strdup(CRYPT_LUKS1);
864                 else if (!strncmp(CRYPT_VERITY, dmd.uuid, sizeof(CRYPT_VERITY)-1))
865                         (*cd)->type = strdup(CRYPT_VERITY);
866                 else
867                         log_dbg("Unknown UUID set, some parameters are not set.");
868         } else
869                 log_dbg("Active device has no UUID set, some parameters are not set.");
870
871         if (header_device) {
872                 r = crypt_set_data_device(*cd, dmd.data_device);
873                 if (r < 0)
874                         goto out;
875         }
876
877         /* Try to initialise basic parameters from active device */
878
879         if (dmd.target == DM_CRYPT)
880                 r = _init_by_name_crypt(*cd, name);
881         else if (dmd.target == DM_VERITY)
882                 r = _init_by_name_verity(*cd, name);
883 out:
884         if (r < 0) {
885                 crypt_free(*cd);
886                 *cd = NULL;
887         }
888         free(CONST_CAST(void*)dmd.data_device);
889         free(CONST_CAST(void*)dmd.uuid);
890         return r;
891 }
892
893 int crypt_init_by_name(struct crypt_device **cd, const char *name)
894 {
895         return crypt_init_by_name_and_header(cd, name, NULL);
896 }
897
898 static int _crypt_format_plain(struct crypt_device *cd,
899                                const char *cipher,
900                                const char *cipher_mode,
901                                const char *uuid,
902                                size_t volume_key_size,
903                                struct crypt_params_plain *params)
904 {
905         if (!cipher || !cipher_mode) {
906                 log_err(cd, _("Invalid plain crypt parameters.\n"));
907                 return -EINVAL;
908         }
909
910         if (volume_key_size > 1024) {
911                 log_err(cd, _("Invalid key size.\n"));
912                 return -EINVAL;
913         }
914
915         cd->plain_key_size = volume_key_size;
916         cd->volume_key = crypt_alloc_volume_key(volume_key_size, NULL);
917         if (!cd->volume_key)
918                 return -ENOMEM;
919
920         cd->plain_cipher = strdup(cipher);
921         cd->plain_cipher_mode = strdup(cipher_mode);
922
923         if (uuid)
924                 cd->plain_uuid = strdup(uuid);
925
926         if (params && params->hash)
927                 cd->plain_hdr.hash = strdup(params->hash);
928
929         cd->plain_hdr.offset = params ? params->offset : 0;
930         cd->plain_hdr.skip = params ? params->skip : 0;
931         cd->plain_hdr.size = params ? params->size : 0;
932
933         if (!cd->plain_cipher || !cd->plain_cipher_mode)
934                 return -ENOMEM;
935
936         return 0;
937 }
938
939 static int _crypt_format_luks1(struct crypt_device *cd,
940                                const char *cipher,
941                                const char *cipher_mode,
942                                const char *uuid,
943                                const char *volume_key,
944                                size_t volume_key_size,
945                                struct crypt_params_luks1 *params)
946 {
947         int r;
948         unsigned long required_alignment = DEFAULT_DISK_ALIGNMENT;
949         unsigned long alignment_offset = 0;
950
951         if (!mdata_device(cd)) {
952                 log_err(cd, _("Can't format LUKS without device.\n"));
953                 return -EINVAL;
954         }
955
956         if (volume_key)
957                 cd->volume_key = crypt_alloc_volume_key(volume_key_size,
958                                                       volume_key);
959         else
960                 cd->volume_key = crypt_generate_volume_key(cd, volume_key_size);
961
962         if(!cd->volume_key)
963                 return -ENOMEM;
964
965         if (params && params->data_device) {
966                 cd->metadata_device = cd->device;
967                 if (!(cd->device = strdup(params->data_device)))
968                         return -ENOMEM;
969                 required_alignment = params->data_alignment * SECTOR_SIZE;
970         } else if (params && params->data_alignment) {
971                 required_alignment = params->data_alignment * SECTOR_SIZE;
972         } else
973                 get_topology_alignment(cd->device, &required_alignment,
974                                        &alignment_offset, DEFAULT_DISK_ALIGNMENT);
975
976         r = LUKS_generate_phdr(&cd->hdr, cd->volume_key, cipher, cipher_mode,
977                                (params && params->hash) ? params->hash : "sha1",
978                                uuid, LUKS_STRIPES,
979                                required_alignment / SECTOR_SIZE,
980                                alignment_offset / SECTOR_SIZE,
981                                cd->iteration_time, &cd->PBKDF2_per_sec,
982                                cd->metadata_device, cd);
983         if(r < 0)
984                 return r;
985
986         /* Wipe first 8 sectors - fs magic numbers etc. */
987         r = crypt_wipe(mdata_device(cd), 0, 8 * SECTOR_SIZE, CRYPT_WIPE_ZERO, 1);
988         if(r < 0) {
989                 if (r == -EBUSY)
990                         log_err(cd, _("Cannot format device %s which is still in use.\n"),
991                                 mdata_device(cd));
992                 else
993                         log_err(cd, _("Cannot wipe header on device %s.\n"),
994                                 mdata_device(cd));
995
996                 return r;
997         }
998
999         r = LUKS_write_phdr(mdata_device(cd), &cd->hdr, cd);
1000
1001         return r;
1002 }
1003
1004 static int _crypt_format_loopaes(struct crypt_device *cd,
1005                                  const char *cipher,
1006                                  const char *uuid,
1007                                  size_t volume_key_size,
1008                                  struct crypt_params_loopaes *params)
1009 {
1010         if (!mdata_device(cd)) {
1011                 log_err(cd, _("Can't format LOOPAES without device.\n"));
1012                 return -EINVAL;
1013         }
1014
1015         if (volume_key_size > 1024) {
1016                 log_err(cd, _("Invalid key size.\n"));
1017                 return -EINVAL;
1018         }
1019
1020         cd->loopaes_key_size = volume_key_size;
1021
1022         cd->loopaes_cipher = strdup(cipher ?: DEFAULT_LOOPAES_CIPHER);
1023
1024         if (uuid)
1025                 cd->loopaes_uuid = strdup(uuid);
1026
1027         if (params && params->hash)
1028                 cd->loopaes_hdr.hash = strdup(params->hash);
1029
1030         cd->loopaes_hdr.offset = params ? params->offset : 0;
1031         cd->loopaes_hdr.skip = params ? params->skip : 0;
1032
1033         return 0;
1034 }
1035
1036 static int _crypt_format_verity(struct crypt_device *cd,
1037                                  const char *uuid,
1038                                  struct crypt_params_verity *params)
1039 {
1040         int r = 0;
1041         uint64_t data_device_size;
1042
1043         if (!mdata_device(cd)) {
1044                 log_err(cd, _("Can't format VERITY without device.\n"));
1045                 return -EINVAL;
1046         }
1047
1048         if (!params || !params->data_device)
1049                 return -EINVAL;
1050
1051         /* set data device */
1052         cd->type = CRYPT_VERITY;
1053         r = crypt_set_data_device(cd, params->data_device);
1054         cd->type = NULL;
1055         if (r)
1056                 return r;
1057         if (!params->data_size) {
1058                 r = device_size(params->data_device, &data_device_size);
1059                 if (r < 0)
1060                         return r;
1061
1062                 cd->verity_hdr.data_size = data_device_size / params->data_block_size;
1063         } else
1064                 cd->verity_hdr.data_size = params->data_size;
1065
1066         cd->verity_root_hash_size = crypt_hash_size(params->hash_name);
1067         if (!cd->verity_root_hash_size)
1068                 return -EINVAL;
1069
1070         cd->verity_root_hash = malloc(cd->verity_root_hash_size);
1071         if (!cd->verity_root_hash)
1072                 return -ENOMEM;
1073
1074         cd->verity_hdr.flags = params->flags;
1075         cd->verity_hdr.hash_name = strdup(params->hash_name);
1076         cd->verity_hdr.data_device = NULL;
1077         cd->verity_hdr.data_block_size = params->data_block_size;
1078         cd->verity_hdr.hash_block_size = params->hash_block_size;
1079         cd->verity_hdr.hash_area_offset = params->hash_area_offset;
1080         cd->verity_hdr.hash_type = params->hash_type;
1081         cd->verity_hdr.flags = params->flags;
1082         cd->verity_hdr.salt_size = params->salt_size;
1083         cd->verity_hdr.salt = malloc(params->salt_size);
1084         if (params->salt)
1085                 memcpy(CONST_CAST(char*)cd->verity_hdr.salt, params->salt,
1086                        params->salt_size);
1087         else
1088                 r = crypt_random_get(cd, CONST_CAST(char*)cd->verity_hdr.salt,
1089                                      params->salt_size, CRYPT_RND_SALT);
1090         if (r)
1091                 return r;
1092
1093         if (params->flags & CRYPT_VERITY_CREATE_HASH) {
1094                 r = VERITY_create(cd, &cd->verity_hdr, cd->device, mdata_device(cd),
1095                                   cd->verity_root_hash, cd->verity_root_hash_size);
1096                 if (r)
1097                         return r;
1098         }
1099
1100         if (!(params->flags & CRYPT_VERITY_NO_HEADER)) {
1101                 if (uuid)
1102                         cd->verity_uuid = strdup(uuid);
1103                 else {
1104                         r = VERITY_UUID_generate(cd, &cd->verity_uuid);
1105                         if (r)
1106                                 return r;
1107                 }
1108
1109                 r = VERITY_write_sb(cd, mdata_device(cd),
1110                                     cd->verity_hdr.hash_area_offset,
1111                                     cd->verity_uuid,
1112                                     &cd->verity_hdr);
1113         }
1114         return r;
1115 }
1116
1117 int crypt_format(struct crypt_device *cd,
1118         const char *type,
1119         const char *cipher,
1120         const char *cipher_mode,
1121         const char *uuid,
1122         const char *volume_key,
1123         size_t volume_key_size,
1124         void *params)
1125 {
1126         int r;
1127
1128         if (!type)
1129                 return -EINVAL;
1130
1131         if (cd->type) {
1132                 log_dbg("Context already formatted as %s.", cd->type);
1133                 return -EINVAL;
1134         }
1135
1136         log_dbg("Formatting device %s as type %s.", mdata_device(cd) ?: "(none)", type);
1137
1138         r = init_crypto(cd);
1139         if (r < 0)
1140                 return r;
1141
1142         if (isPLAIN(type))
1143                 r = _crypt_format_plain(cd, cipher, cipher_mode,
1144                                         uuid, volume_key_size, params);
1145         else if (isLUKS(type))
1146                 r = _crypt_format_luks1(cd, cipher, cipher_mode,
1147                                         uuid, volume_key, volume_key_size, params);
1148         else if (isLOOPAES(type))
1149                 r = _crypt_format_loopaes(cd, cipher, uuid, volume_key_size, params);
1150         else if (isVERITY(type))
1151                 r = _crypt_format_verity(cd, uuid, params);
1152         else {
1153                 log_err(cd, _("Unknown crypt device type %s requested.\n"), type);
1154                 r = -EINVAL;
1155         }
1156
1157         if (!r && !(cd->type = strdup(type)))
1158                 r = -ENOMEM;
1159
1160         if (r < 0) {
1161                 crypt_free_volume_key(cd->volume_key);
1162                 cd->volume_key = NULL;
1163         }
1164
1165         return r;
1166 }
1167
1168 int crypt_load(struct crypt_device *cd,
1169                const char *requested_type,
1170                void *params)
1171 {
1172         int r;
1173
1174         log_dbg("Trying to load %s crypt type from device %s.",
1175                 requested_type ?: "any", mdata_device(cd) ?: "(none)");
1176
1177         if (!mdata_device(cd))
1178                 return -EINVAL;
1179
1180         if (!requested_type || isLUKS(requested_type)) {
1181                 if (cd->type && !isLUKS(cd->type)) {
1182                         log_dbg("Context is already initialised to type %s", cd->type);
1183                         return -EINVAL;
1184                 }
1185
1186                 r = _crypt_load_luks1(cd, 1, 0);
1187         } else if (isVERITY(requested_type)) {
1188                 if (cd->type && !isVERITY(cd->type)) {
1189                         log_dbg("Context is already initialised to type %s", cd->type);
1190                         return -EINVAL;
1191                 }
1192                 r = _crypt_load_verity(cd, params);
1193         } else
1194                 return -EINVAL;
1195
1196         if (r < 0)
1197                 return r;
1198
1199         /* cd->type and header must be set in context */
1200         r = crypt_check_data_device_size(cd);
1201         if (r < 0) {
1202                 free(cd->type);
1203                 cd->type = NULL;
1204         }
1205
1206         return r;
1207 }
1208
1209 int crypt_repair(struct crypt_device *cd,
1210                  const char *requested_type,
1211                  void *params __attribute__((unused)))
1212 {
1213         int r;
1214
1215         log_dbg("Trying to repair %s crypt type from device %s.",
1216                 requested_type ?: "any", mdata_device(cd) ?: "(none)");
1217
1218         if (!mdata_device(cd))
1219                 return -EINVAL;
1220
1221         if (requested_type && !isLUKS(requested_type))
1222                 return -EINVAL;
1223
1224
1225         /* Load with repair */
1226         r = _crypt_load_luks1(cd, 1, 1);
1227         if (r < 0)
1228                 return r;
1229
1230         /* cd->type and header must be set in context */
1231         r = crypt_check_data_device_size(cd);
1232         if (r < 0) {
1233                 free(cd->type);
1234                 cd->type = NULL;
1235         }
1236
1237         return r;
1238 }
1239
1240 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
1241 {
1242         struct crypt_dm_active_device dmd;
1243         int r;
1244
1245         /* Device context type must be initialised */
1246         if (!cd->type || !crypt_get_uuid(cd))
1247                 return -EINVAL;
1248
1249         log_dbg("Resizing device %s to %" PRIu64 " sectors.", name, new_size);
1250
1251         r = dm_query_device(name, DM_ACTIVE_DEVICE | DM_ACTIVE_CRYPT_CIPHER |
1252                                   DM_ACTIVE_UUID | DM_ACTIVE_CRYPT_KEYSIZE |
1253                                   DM_ACTIVE_CRYPT_KEY, &dmd);
1254         if (r < 0) {
1255                 log_err(NULL, _("Device %s is not active.\n"), name);
1256                 return -EINVAL;
1257         }
1258
1259         if (!dmd.uuid || dmd.target != DM_CRYPT) {
1260                 r = -EINVAL;
1261                 goto out;
1262         }
1263
1264         r = device_check_and_adjust(cd, dmd.data_device, DEV_OK, &new_size,
1265                                     &dmd.u.crypt.offset, &dmd.flags);
1266         if (r)
1267                 goto out;
1268
1269         if (new_size == dmd.size) {
1270                 log_dbg("Device has already requested size %" PRIu64
1271                         " sectors.", dmd.size);
1272                 r = 0;
1273         } else {
1274                 dmd.size = new_size;
1275                 r = dm_create_device(name, cd->type, &dmd, 1);
1276         }
1277 out:
1278         if (dmd.target == DM_CRYPT) {
1279                 crypt_free_volume_key(dmd.u.crypt.vk);
1280                 free(CONST_CAST(void*)dmd.u.crypt.cipher);
1281         }
1282         free(CONST_CAST(void*)dmd.data_device);
1283         free(CONST_CAST(void*)dmd.uuid);
1284
1285         return r;
1286 }
1287
1288 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
1289 {
1290         if (!isLUKS(cd->type)) {
1291                 log_err(cd, _("This operation is not supported for this device type.\n"));
1292                 return  -EINVAL;
1293         }
1294
1295         if (uuid && !strncmp(uuid, cd->hdr.uuid, sizeof(cd->hdr.uuid))) {
1296                 log_dbg("UUID is the same as requested (%s) for device %s.",
1297                         uuid, mdata_device(cd));
1298                 return 0;
1299         }
1300
1301         if (uuid)
1302                 log_dbg("Requested new UUID change to %s for %s.", uuid, mdata_device(cd));
1303         else
1304                 log_dbg("Requested new UUID refresh for %s.", mdata_device(cd));
1305
1306         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
1307                 return -EPERM;
1308
1309         return LUKS_hdr_uuid_set(mdata_device(cd), &cd->hdr, uuid, cd);
1310 }
1311
1312 int crypt_header_backup(struct crypt_device *cd,
1313                         const char *requested_type,
1314                         const char *backup_file)
1315 {
1316         int r;
1317
1318         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
1319                 return -EINVAL;
1320
1321         r = init_crypto(cd);
1322         if (r < 0)
1323                 return r;
1324
1325         log_dbg("Requested header backup of device %s (%s) to "
1326                 "file %s.", mdata_device(cd), requested_type, backup_file);
1327
1328         return LUKS_hdr_backup(backup_file, mdata_device(cd), &cd->hdr, cd);
1329 }
1330
1331 int crypt_header_restore(struct crypt_device *cd,
1332                          const char *requested_type,
1333                          const char *backup_file)
1334 {
1335         int r;
1336
1337         if (requested_type && !isLUKS(requested_type))
1338                 return -EINVAL;
1339
1340         r = init_crypto(cd);
1341         if (r < 0)
1342                 return r;
1343
1344         log_dbg("Requested header restore to device %s (%s) from "
1345                 "file %s.", mdata_device(cd), requested_type, backup_file);
1346
1347         return LUKS_hdr_restore(backup_file, mdata_device(cd), &cd->hdr, cd);
1348 }
1349
1350 void crypt_free(struct crypt_device *cd)
1351 {
1352         if (cd) {
1353                 log_dbg("Releasing crypt device %s context.", mdata_device(cd));
1354
1355                 if (cd->loop_device_fd != -1)
1356                         close(cd->loop_device_fd);
1357                 if (cd->loop_metadata_device_fd != -1)
1358                         close(cd->loop_metadata_device_fd);
1359
1360                 dm_exit();
1361                 crypt_free_volume_key(cd->volume_key);
1362
1363                 free(cd->device);
1364                 free(cd->metadata_device);
1365                 free(cd->type);
1366
1367                 /* used in plain device only */
1368                 free(CONST_CAST(void*)cd->plain_hdr.hash);
1369                 free(cd->plain_cipher);
1370                 free(cd->plain_cipher_mode);
1371                 free(cd->plain_uuid);
1372
1373                 /* used in loop-AES device only */
1374                 free(CONST_CAST(void*)cd->loopaes_hdr.hash);
1375                 free(cd->loopaes_cipher);
1376                 free(cd->loopaes_uuid);
1377
1378                 /* used in verity device only */
1379                 free(CONST_CAST(void*)cd->verity_hdr.hash_name);
1380                 free(CONST_CAST(void*)cd->verity_hdr.salt);
1381                 free(cd->verity_root_hash);
1382                 free(cd->verity_uuid);
1383
1384                 free(cd);
1385         }
1386 }
1387
1388 int crypt_suspend(struct crypt_device *cd,
1389                   const char *name)
1390 {
1391         crypt_status_info ci;
1392         int r;
1393
1394         log_dbg("Suspending volume %s.", name);
1395
1396         if (!isLUKS(cd->type)) {
1397                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1398                 r = -EINVAL;
1399                 goto out;
1400         }
1401
1402         ci = crypt_status(NULL, name);
1403         if (ci < CRYPT_ACTIVE) {
1404                 log_err(cd, _("Volume %s is not active.\n"), name);
1405                 return -EINVAL;
1406         }
1407
1408         if (!cd && dm_init(NULL, 1) < 0)
1409                 return -ENOSYS;
1410
1411         r = dm_status_suspended(name);
1412         if (r < 0)
1413                 goto out;
1414
1415         if (r) {
1416                 log_err(cd, _("Volume %s is already suspended.\n"), name);
1417                 r = -EINVAL;
1418                 goto out;
1419         }
1420
1421         r = dm_suspend_and_wipe_key(name);
1422         if (r == -ENOTSUP)
1423                 log_err(cd, "Suspend is not supported for device %s.\n", name);
1424         else if (r)
1425                 log_err(cd, "Error during suspending device %s.\n", name);
1426 out:
1427         if (!cd)
1428                 dm_exit();
1429         return r;
1430 }
1431
1432 int crypt_resume_by_passphrase(struct crypt_device *cd,
1433                                const char *name,
1434                                int keyslot,
1435                                const char *passphrase,
1436                                size_t passphrase_size)
1437 {
1438         struct volume_key *vk = NULL;
1439         int r;
1440
1441         log_dbg("Resuming volume %s.", name);
1442
1443         if (!isLUKS(cd->type)) {
1444                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1445                 r = -EINVAL;
1446                 goto out;
1447         }
1448
1449         r = dm_status_suspended(name);
1450         if (r < 0)
1451                 return r;
1452
1453         if (!r) {
1454                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1455                 return -EINVAL;
1456         }
1457
1458         if (passphrase) {
1459                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
1460                                            passphrase_size, &cd->hdr, &vk, cd);
1461         } else
1462                 r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1463
1464         if (r >= 0) {
1465                 keyslot = r;
1466                 r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1467                 if (r == -ENOTSUP)
1468                         log_err(cd, "Resume is not supported for device %s.\n", name);
1469                 else if (r)
1470                         log_err(cd, "Error during resuming device %s.\n", name);
1471         } else
1472                 r = keyslot;
1473 out:
1474         crypt_free_volume_key(vk);
1475         return r < 0 ? r : keyslot;
1476 }
1477
1478 int crypt_resume_by_keyfile_offset(struct crypt_device *cd,
1479                                    const char *name,
1480                                    int keyslot,
1481                                    const char *keyfile,
1482                                    size_t keyfile_size,
1483                                    size_t keyfile_offset)
1484 {
1485         struct volume_key *vk = NULL;
1486         char *passphrase_read = NULL;
1487         size_t passphrase_size_read;
1488         int r;
1489
1490         log_dbg("Resuming volume %s.", name);
1491
1492         if (!isLUKS(cd->type)) {
1493                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1494                 r = -EINVAL;
1495                 goto out;
1496         }
1497
1498         r = dm_status_suspended(name);
1499         if (r < 0)
1500                 return r;
1501
1502         if (!r) {
1503                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1504                 return -EINVAL;
1505         }
1506
1507         if (!keyfile)
1508                 return -EINVAL;
1509
1510         r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1511                           &passphrase_size_read, keyfile, keyfile_offset,
1512                           keyfile_size);
1513         if (r < 0)
1514                 goto out;
1515
1516         r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase_read,
1517                                    passphrase_size_read, &cd->hdr, &vk, cd);
1518         if (r < 0)
1519                 goto out;
1520
1521         keyslot = r;
1522         r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1523         if (r)
1524                 log_err(cd, "Error during resuming device %s.\n", name);
1525 out:
1526         crypt_safe_free(passphrase_read);
1527         crypt_free_volume_key(vk);
1528         return r < 0 ? r : keyslot;
1529 }
1530
1531 int crypt_resume_by_keyfile(struct crypt_device *cd,
1532                             const char *name,
1533                             int keyslot,
1534                             const char *keyfile,
1535                             size_t keyfile_size)
1536 {
1537         return crypt_resume_by_keyfile_offset(cd, name, keyslot,
1538                                               keyfile, keyfile_size, 0);
1539 }
1540
1541 // slot manipulation
1542 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1543         int keyslot, // -1 any
1544         const char *passphrase, // NULL -> terminal
1545         size_t passphrase_size,
1546         const char *new_passphrase, // NULL -> terminal
1547         size_t new_passphrase_size)
1548 {
1549         struct volume_key *vk = NULL;
1550         char *password = NULL, *new_password = NULL;
1551         size_t passwordLen, new_passwordLen;
1552         int r;
1553
1554         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1555                 "new passphrase %sprovided.",
1556                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1557
1558         if (!isLUKS(cd->type)) {
1559                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1560                 return -EINVAL;
1561         }
1562
1563         r = keyslot_verify_or_find_empty(cd, &keyslot);
1564         if (r)
1565                 return r;
1566
1567         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1568                 /* No slots used, try to use pre-generated key in header */
1569                 if (cd->volume_key) {
1570                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1571                         r = vk ? 0 : -ENOMEM;
1572                 } else {
1573                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1574                         return -EINVAL;
1575                 }
1576         } else if (passphrase) {
1577                 /* Passphrase provided, use it to unlock existing keyslot */
1578                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, passphrase,
1579                                            passphrase_size, &cd->hdr, &vk, cd);
1580         } else {
1581                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1582                 r = key_from_terminal(cd, _("Enter any passphrase: "),
1583                                       &password, &passwordLen, 0);
1584                 if (r < 0)
1585                         goto out;
1586
1587                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, password,
1588                                            passwordLen, &cd->hdr, &vk, cd);
1589                 crypt_safe_free(password);
1590         }
1591
1592         if(r < 0)
1593                 goto out;
1594
1595         if (new_passphrase) {
1596                 new_password = CONST_CAST(char*)new_passphrase;
1597                 new_passwordLen = new_passphrase_size;
1598         } else {
1599                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1600                                       &new_password, &new_passwordLen, 1);
1601                 if(r < 0)
1602                         goto out;
1603         }
1604
1605         r = LUKS_set_key(mdata_device(cd), keyslot, new_password, new_passwordLen,
1606                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1607         if(r < 0) goto out;
1608
1609         r = 0;
1610 out:
1611         if (!new_passphrase)
1612                 crypt_safe_free(new_password);
1613         crypt_free_volume_key(vk);
1614         return r ?: keyslot;
1615 }
1616
1617 int crypt_keyslot_add_by_keyfile_offset(struct crypt_device *cd,
1618         int keyslot,
1619         const char *keyfile,
1620         size_t keyfile_size,
1621         size_t keyfile_offset,
1622         const char *new_keyfile,
1623         size_t new_keyfile_size,
1624         size_t new_keyfile_offset)
1625 {
1626         struct volume_key *vk = NULL;
1627         char *password = NULL; size_t passwordLen;
1628         char *new_password = NULL; size_t new_passwordLen;
1629         int r;
1630
1631         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1632                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1633
1634         if (!isLUKS(cd->type)) {
1635                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1636                 return -EINVAL;
1637         }
1638
1639         r = keyslot_verify_or_find_empty(cd, &keyslot);
1640         if (r)
1641                 return r;
1642
1643         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1644                 /* No slots used, try to use pre-generated key in header */
1645                 if (cd->volume_key) {
1646                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1647                         r = vk ? 0 : -ENOMEM;
1648                 } else {
1649                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1650                         return -EINVAL;
1651                 }
1652         } else {
1653                 /* Read password from file of (if NULL) from terminal */
1654                 if (keyfile)
1655                         r = key_from_file(cd, _("Enter any passphrase: "),
1656                                           &password, &passwordLen,
1657                                           keyfile, keyfile_offset, keyfile_size);
1658                 else
1659                         r = key_from_terminal(cd, _("Enter any passphrase: "),
1660                                               &password, &passwordLen, 0);
1661                 if (r < 0)
1662                         goto out;
1663
1664                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, password, passwordLen,
1665                                            &cd->hdr, &vk, cd);
1666         }
1667
1668         if(r < 0)
1669                 goto out;
1670
1671         if (new_keyfile)
1672                 r = key_from_file(cd, _("Enter new passphrase for key slot: "),
1673                                   &new_password, &new_passwordLen, new_keyfile,
1674                                   new_keyfile_offset, new_keyfile_size);
1675         else
1676                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1677                                       &new_password, &new_passwordLen, 1);
1678         if (r < 0)
1679                 goto out;
1680
1681         r = LUKS_set_key(mdata_device(cd), keyslot, new_password, new_passwordLen,
1682                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1683 out:
1684         crypt_safe_free(password);
1685         crypt_safe_free(new_password);
1686         crypt_free_volume_key(vk);
1687         return r < 0 ? r : keyslot;
1688 }
1689
1690 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1691         int keyslot,
1692         const char *keyfile,
1693         size_t keyfile_size,
1694         const char *new_keyfile,
1695         size_t new_keyfile_size)
1696 {
1697         return crypt_keyslot_add_by_keyfile_offset(cd, keyslot,
1698                                 keyfile, keyfile_size, 0,
1699                                 new_keyfile, new_keyfile_size, 0);
1700 }
1701
1702 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1703         int keyslot,
1704         const char *volume_key,
1705         size_t volume_key_size,
1706         const char *passphrase,
1707         size_t passphrase_size)
1708 {
1709         struct volume_key *vk = NULL;
1710         int r = -EINVAL;
1711         char *new_password = NULL; size_t new_passwordLen;
1712
1713         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1714
1715         if (!isLUKS(cd->type)) {
1716                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1717                 return -EINVAL;
1718         }
1719
1720         if (volume_key)
1721                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1722         else if (cd->volume_key)
1723                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1724
1725         if (!vk)
1726                 return -ENOMEM;
1727
1728         r = LUKS_verify_volume_key(&cd->hdr, vk);
1729         if (r < 0) {
1730                 log_err(cd, _("Volume key does not match the volume.\n"));
1731                 goto out;
1732         }
1733
1734         r = keyslot_verify_or_find_empty(cd, &keyslot);
1735         if (r)
1736                 goto out;
1737
1738         if (!passphrase) {
1739                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1740                                       &new_password, &new_passwordLen, 1);
1741                 if (r < 0)
1742                         goto out;
1743                 passphrase = new_password;
1744                 passphrase_size = new_passwordLen;
1745         }
1746
1747         r = LUKS_set_key(mdata_device(cd), keyslot, passphrase, passphrase_size,
1748                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1749 out:
1750         crypt_safe_free(new_password);
1751         crypt_free_volume_key(vk);
1752         return (r < 0) ? r : keyslot;
1753 }
1754
1755 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1756 {
1757         crypt_keyslot_info ki;
1758
1759         log_dbg("Destroying keyslot %d.", keyslot);
1760
1761         if (!isLUKS(cd->type)) {
1762                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1763                 return -EINVAL;
1764         }
1765
1766         ki = crypt_keyslot_status(cd, keyslot);
1767         if (ki == CRYPT_SLOT_INVALID) {
1768                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1769                 return -EINVAL;
1770         }
1771
1772         if (ki == CRYPT_SLOT_INACTIVE) {
1773                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1774                 return -EINVAL;
1775         }
1776
1777         return LUKS_del_key(mdata_device(cd), keyslot, &cd->hdr, cd);
1778 }
1779
1780 // activation/deactivation of device mapping
1781 int crypt_activate_by_passphrase(struct crypt_device *cd,
1782         const char *name,
1783         int keyslot,
1784         const char *passphrase,
1785         size_t passphrase_size,
1786         uint32_t flags)
1787 {
1788         crypt_status_info ci;
1789         struct volume_key *vk = NULL;
1790         char *read_passphrase = NULL;
1791         size_t passphraseLen = 0;
1792         int r;
1793
1794         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1795                 name ? "Activating" : "Checking", name ?: "",
1796                 keyslot, passphrase ? "" : "[none] ");
1797
1798         if (name) {
1799                 ci = crypt_status(NULL, name);
1800                 if (ci == CRYPT_INVALID)
1801                         return -EINVAL;
1802                 else if (ci >= CRYPT_ACTIVE) {
1803                         log_err(cd, _("Device %s already exists.\n"), name);
1804                         return -EEXIST;
1805                 }
1806         }
1807
1808         /* plain, use hashed passphrase */
1809         if (isPLAIN(cd->type)) {
1810                 if (!name)
1811                         return -EINVAL;
1812
1813                 if (!passphrase) {
1814                         r = key_from_terminal(cd, NULL, &read_passphrase,
1815                                               &passphraseLen, 0);
1816                         if (r < 0)
1817                                 goto out;
1818                         passphrase = read_passphrase;
1819                         passphrase_size = passphraseLen;
1820                 }
1821
1822                 r = process_key(cd, cd->plain_hdr.hash,
1823                                 cd->plain_key_size,
1824                                 passphrase, passphrase_size, &vk);
1825                 if (r < 0)
1826                         goto out;
1827
1828                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1829                 keyslot = 0;
1830         } else if (isLUKS(cd->type)) {
1831                 /* provided passphrase, do not retry */
1832                 if (passphrase) {
1833                         r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
1834                                                    passphrase_size, &cd->hdr, &vk, cd);
1835                 } else
1836                         r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1837
1838                 if (r >= 0) {
1839                         keyslot = r;
1840                         if (name)
1841                                 r = LUKS1_activate(cd, name, vk, flags);
1842                 }
1843         } else
1844                 r = -EINVAL;
1845 out:
1846         crypt_safe_free(read_passphrase);
1847         crypt_free_volume_key(vk);
1848
1849         return r < 0  ? r : keyslot;
1850 }
1851
1852 int crypt_activate_by_keyfile_offset(struct crypt_device *cd,
1853         const char *name,
1854         int keyslot,
1855         const char *keyfile,
1856         size_t keyfile_size,
1857         size_t keyfile_offset,
1858         uint32_t flags)
1859 {
1860         crypt_status_info ci;
1861         struct volume_key *vk = NULL;
1862         char *passphrase_read = NULL;
1863         size_t passphrase_size_read;
1864         unsigned int key_count = 0;
1865         int r;
1866
1867         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1868                 name ?: "", keyslot, keyfile ?: "[none]");
1869
1870         if (name) {
1871                 ci = crypt_status(NULL, name);
1872                 if (ci == CRYPT_INVALID)
1873                         return -EINVAL;
1874                 else if (ci >= CRYPT_ACTIVE) {
1875                         log_err(cd, _("Device %s already exists.\n"), name);
1876                         return -EEXIST;
1877                 }
1878         }
1879
1880         if (!keyfile)
1881                 return -EINVAL;
1882
1883         if (isPLAIN(cd->type)) {
1884                 if (!name)
1885                         return -EINVAL;
1886
1887                 r = key_from_file(cd, _("Enter passphrase: "),
1888                                   &passphrase_read, &passphrase_size_read,
1889                                   keyfile, keyfile_offset, keyfile_size);
1890                 if (r < 0)
1891                         goto out;
1892
1893                 r = process_key(cd, cd->plain_hdr.hash,
1894                                 cd->plain_key_size,
1895                                 passphrase_read, passphrase_size_read, &vk);
1896                 if (r < 0)
1897                         goto out;
1898
1899                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1900         } else if (isLUKS(cd->type)) {
1901                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1902                           &passphrase_size_read, keyfile, keyfile_offset, keyfile_size);
1903                 if (r < 0)
1904                         goto out;
1905                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase_read,
1906                                            passphrase_size_read, &cd->hdr, &vk, cd);
1907                 if (r < 0)
1908                         goto out;
1909                 keyslot = r;
1910
1911                 if (name) {
1912                         r = LUKS1_activate(cd, name, vk, flags);
1913                         if (r < 0)
1914                                 goto out;
1915                 }
1916                 r = keyslot;
1917         } else if (isLOOPAES(cd->type)) {
1918                 r = key_from_file(cd, NULL, &passphrase_read, &passphrase_size_read,
1919                                   keyfile, keyfile_offset, keyfile_size);
1920                 if (r < 0)
1921                         goto out;
1922                 r = LOOPAES_parse_keyfile(cd, &vk, cd->loopaes_hdr.hash, &key_count,
1923                                           passphrase_read, passphrase_size_read);
1924                 if (r < 0)
1925                         goto out;
1926                 if (name)
1927                         r = LOOPAES_activate(cd, name, cd->loopaes_cipher,
1928                                              key_count, vk, flags);
1929         } else
1930                 r = -EINVAL;
1931
1932 out:
1933         crypt_safe_free(passphrase_read);
1934         crypt_free_volume_key(vk);
1935
1936         return r;
1937 }
1938
1939 int crypt_activate_by_keyfile(struct crypt_device *cd,
1940         const char *name,
1941         int keyslot,
1942         const char *keyfile,
1943         size_t keyfile_size,
1944         uint32_t flags)
1945 {
1946         return crypt_activate_by_keyfile_offset(cd, name, keyslot, keyfile,
1947                                                 keyfile_size, 0, flags);
1948 }
1949
1950 int crypt_activate_by_volume_key(struct crypt_device *cd,
1951         const char *name,
1952         const char *volume_key,
1953         size_t volume_key_size,
1954         uint32_t flags)
1955 {
1956         crypt_status_info ci;
1957         struct volume_key *vk = NULL;
1958         int r = -EINVAL;
1959
1960         log_dbg("Activating volume %s by volume key.", name ?: "[none]");
1961
1962         if (name) {
1963                 ci = crypt_status(NULL, name);
1964                 if (ci == CRYPT_INVALID)
1965                         return -EINVAL;
1966                 else if (ci >= CRYPT_ACTIVE) {
1967                         log_err(cd, _("Device %s already exists.\n"), name);
1968                         return -EEXIST;
1969                 }
1970         }
1971
1972         /* use key directly, no hash */
1973         if (isPLAIN(cd->type)) {
1974                 if (!name)
1975                         return -EINVAL;
1976
1977                 if (!volume_key || !volume_key_size || volume_key_size != cd->plain_key_size) {
1978                         log_err(cd, _("Incorrect volume key specified for plain device.\n"));
1979                         return -EINVAL;
1980                 }
1981
1982                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1983                 if (!vk)
1984                         return -ENOMEM;
1985
1986                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1987         } else if (isLUKS(cd->type)) {
1988                 /* If key is not provided, try to use internal key */
1989                 if (!volume_key) {
1990                         if (!cd->volume_key) {
1991                                 log_err(cd, _("Volume key does not match the volume.\n"));
1992                                 return -EINVAL;
1993                         }
1994                         volume_key_size = cd->volume_key->keylength;
1995                         volume_key = cd->volume_key->key;
1996                 }
1997
1998                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1999                 if (!vk)
2000                         return -ENOMEM;
2001                 r = LUKS_verify_volume_key(&cd->hdr, vk);
2002
2003                 if (r == -EPERM)
2004                         log_err(cd, _("Volume key does not match the volume.\n"));
2005
2006                 if (!r && name)
2007                         r = LUKS1_activate(cd, name, vk, flags);
2008         } else if (isVERITY(cd->type)) {
2009                 /* volume_key == root hash */
2010                 if (!volume_key || !volume_key_size) {
2011                         log_err(cd, _("Incorrect root hash specified for verity device.\n"));
2012                         return -EINVAL;
2013                 }
2014
2015                 r = VERITY_activate(cd, name, mdata_device(cd),
2016                                     volume_key, volume_key_size,
2017                                     &cd->verity_hdr, CRYPT_ACTIVATE_READONLY);
2018
2019                 if (r == -EPERM) {
2020                         free(cd->verity_root_hash);
2021                         cd->verity_root_hash = NULL;
2022                 } if (!r) {
2023                         cd->verity_root_hash_size = volume_key_size;
2024                         if (!cd->verity_root_hash)
2025                                 cd->verity_root_hash = malloc(volume_key_size);
2026                         if (cd->verity_root_hash)
2027                                 memcpy(cd->verity_root_hash, volume_key, volume_key_size);
2028                 }
2029         } else
2030                 log_err(cd, _("Device type is not properly initialised.\n"));
2031
2032         crypt_free_volume_key(vk);
2033
2034         return r;
2035 }
2036
2037 int crypt_deactivate(struct crypt_device *cd, const char *name)
2038 {
2039         int r;
2040
2041         if (!name)
2042                 return -EINVAL;
2043
2044         log_dbg("Deactivating volume %s.", name);
2045
2046         if (!cd && dm_init(NULL, 1) < 0)
2047                 return -ENOSYS;
2048
2049         switch (crypt_status(cd, name)) {
2050                 case CRYPT_ACTIVE:
2051                 case CRYPT_BUSY:
2052                         r = dm_remove_device(name, 0, 0);
2053                         break;
2054                 case CRYPT_INACTIVE:
2055                         log_err(cd, _("Device %s is not active.\n"), name);
2056                         r = -ENODEV;
2057                         break;
2058                 default:
2059                         log_err(cd, _("Invalid device %s.\n"), name);
2060                         r = -EINVAL;
2061         }
2062
2063         if (!cd)
2064                 dm_exit();
2065
2066         return r;
2067 }
2068
2069 int crypt_volume_key_get(struct crypt_device *cd,
2070         int keyslot,
2071         char *volume_key,
2072         size_t *volume_key_size,
2073         const char *passphrase,
2074         size_t passphrase_size)
2075 {
2076         struct volume_key *vk = NULL;
2077         unsigned key_len;
2078         int r = -EINVAL;
2079
2080         if (crypt_fips_mode()) {
2081                 log_err(cd, "Function not available in FIPS mode.\n");
2082                 return -EACCES;
2083         }
2084
2085         key_len = crypt_get_volume_key_size(cd);
2086         if (key_len > *volume_key_size) {
2087                 log_err(cd, _("Volume key buffer too small.\n"));
2088                 return -ENOMEM;
2089         }
2090
2091         if (isPLAIN(cd->type) && cd->plain_hdr.hash) {
2092                 r = process_key(cd, cd->plain_hdr.hash, key_len,
2093                                 passphrase, passphrase_size, &vk);
2094                 if (r < 0)
2095                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
2096         } else if (isLUKS(cd->type)) {
2097                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
2098                                         passphrase_size, &cd->hdr, &vk, cd);
2099
2100         } else
2101                 log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
2102
2103         if (r >= 0) {
2104                 memcpy(volume_key, vk->key, vk->keylength);
2105                 *volume_key_size = vk->keylength;
2106         }
2107
2108         crypt_free_volume_key(vk);
2109         return r;
2110 }
2111
2112 int crypt_volume_key_verify(struct crypt_device *cd,
2113         const char *volume_key,
2114         size_t volume_key_size)
2115 {
2116         struct volume_key *vk;
2117         int r;
2118
2119         if (!isLUKS(cd->type)) {
2120                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2121                 return -EINVAL;
2122         }
2123
2124         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2125         if (!vk)
2126                 return -ENOMEM;
2127
2128         r = LUKS_verify_volume_key(&cd->hdr, vk);
2129
2130         if (r == -EPERM)
2131                 log_err(cd, _("Volume key does not match the volume.\n"));
2132
2133         crypt_free_volume_key(vk);
2134
2135         return r;
2136 }
2137
2138 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
2139 {
2140         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
2141         cd->timeout = timeout_sec;
2142 }
2143
2144 void crypt_set_password_retry(struct crypt_device *cd, int tries)
2145 {
2146         log_dbg("Password retry count set to %d.", tries);
2147         cd->tries = tries;
2148 }
2149
2150 void crypt_set_iteration_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2151 {
2152         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
2153         cd->iteration_time = iteration_time_ms;
2154 }
2155 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2156 {
2157         crypt_set_iteration_time(cd, iteration_time_ms);
2158 }
2159
2160 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
2161 {
2162         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
2163         cd->password_verify = password_verify ? 1 : 0;
2164 }
2165
2166 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
2167 {
2168         switch (rng_type) {
2169         case CRYPT_RNG_URANDOM:
2170         case CRYPT_RNG_RANDOM:
2171                 log_dbg("RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
2172                 cd->rng_type = rng_type;
2173         }
2174 }
2175
2176 int crypt_get_rng_type(struct crypt_device *cd)
2177 {
2178         if (!cd)
2179                 return -EINVAL;
2180
2181         return cd->rng_type;
2182 }
2183
2184 int crypt_memory_lock(struct crypt_device *cd, int lock)
2185 {
2186         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
2187 }
2188
2189 // reporting
2190 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
2191 {
2192         int r;
2193
2194         if (!cd && dm_init(NULL, 1) < 0)
2195                 return CRYPT_INVALID;
2196
2197         r = dm_status_device(name);
2198
2199         if (!cd)
2200                 dm_exit();
2201
2202         if (r < 0 && r != -ENODEV)
2203                 return CRYPT_INVALID;
2204
2205         if (r == 0)
2206                 return CRYPT_ACTIVE;
2207
2208         if (r > 0)
2209                 return CRYPT_BUSY;
2210
2211         return CRYPT_INACTIVE;
2212 }
2213
2214 static void hexprint(struct crypt_device *cd, const char *d, int n, const char *sep)
2215 {
2216         int i;
2217         for(i = 0; i < n; i++)
2218                 log_std(cd, "%02hhx%s", (const char)d[i], sep);
2219 }
2220
2221 static int _luks_dump(struct crypt_device *cd)
2222 {
2223         int i;
2224
2225         log_std(cd, "LUKS header information for %s\n\n", mdata_device(cd));
2226         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
2227         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
2228         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
2229         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
2230         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
2231         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
2232         log_std(cd, "MK digest:     \t");
2233         hexprint(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE, " ");
2234         log_std(cd, "\n");
2235         log_std(cd, "MK salt:       \t");
2236         hexprint(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2, " ");
2237         log_std(cd, "\n               \t");
2238         hexprint(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
2239         log_std(cd, "\n");
2240         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
2241         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
2242         for(i = 0; i < LUKS_NUMKEYS; i++) {
2243                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
2244                         log_std(cd, "Key Slot %d: ENABLED\n",i);
2245                         log_std(cd, "\tIterations:         \t%d\n",
2246                                 cd->hdr.keyblock[i].passwordIterations);
2247                         log_std(cd, "\tSalt:               \t");
2248                         hexprint(cd, cd->hdr.keyblock[i].passwordSalt,
2249                                  LUKS_SALTSIZE/2, " ");
2250                         log_std(cd, "\n\t                      \t");
2251                         hexprint(cd, cd->hdr.keyblock[i].passwordSalt +
2252                                  LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
2253                         log_std(cd, "\n");
2254
2255                         log_std(cd, "\tKey material offset:\t%d\n",
2256                                 cd->hdr.keyblock[i].keyMaterialOffset);
2257                         log_std(cd, "\tAF stripes:            \t%d\n",
2258                                 cd->hdr.keyblock[i].stripes);
2259                 }
2260                 else 
2261                         log_std(cd, "Key Slot %d: DISABLED\n", i);
2262         }
2263         return 0;
2264 }
2265
2266 static int _verity_dump(struct crypt_device *cd)
2267 {
2268         log_std(cd, "VERITY header information for %s\n", mdata_device(cd));
2269         log_std(cd, "UUID:            \t%s\n", cd->verity_uuid ?: "");
2270         log_std(cd, "Hash type:       \t%u\n", cd->verity_hdr.hash_type);
2271         log_std(cd, "Data blocks:     \t%" PRIu64 "\n", cd->verity_hdr.data_size);
2272         log_std(cd, "Data block size: \t%u\n", cd->verity_hdr.data_block_size);
2273         log_std(cd, "Hash block size: \t%u\n", cd->verity_hdr.hash_block_size);
2274         log_std(cd, "Hash algorithm:  \t%s\n", cd->verity_hdr.hash_name);
2275         log_std(cd, "Salt:            \t");
2276         if (cd->verity_hdr.salt_size)
2277                 hexprint(cd, cd->verity_hdr.salt, cd->verity_hdr.salt_size, "");
2278         else
2279                 log_std(cd, "-");
2280         log_std(cd, "\n");
2281         if (cd->verity_root_hash) {
2282                 log_std(cd, "Root hash:      \t");
2283                 hexprint(cd, cd->verity_root_hash, cd->verity_root_hash_size, "");
2284                 log_std(cd, "\n");
2285         }
2286         return 0;
2287 }
2288
2289 int crypt_dump(struct crypt_device *cd)
2290 {
2291         if (isLUKS(cd->type))
2292                 return _luks_dump(cd);
2293         else if (isVERITY(cd->type))
2294                 return _verity_dump(cd);
2295
2296         log_err(cd, _("Dump operation is not supported for this device type.\n"));
2297         return -EINVAL;
2298 }
2299
2300 const char *crypt_get_cipher(struct crypt_device *cd)
2301 {
2302         if (isPLAIN(cd->type))
2303                 return cd->plain_cipher;
2304
2305         if (isLUKS(cd->type))
2306                 return cd->hdr.cipherName;
2307
2308         if (isLOOPAES(cd->type))
2309                 return cd->loopaes_cipher;
2310
2311         return NULL;
2312 }
2313
2314 const char *crypt_get_cipher_mode(struct crypt_device *cd)
2315 {
2316         if (isPLAIN(cd->type))
2317                 return cd->plain_cipher_mode;
2318
2319         if (isLUKS(cd->type))
2320                 return cd->hdr.cipherMode;
2321
2322         if (isLOOPAES(cd->type))
2323                 return cd->loopaes_cipher_mode;
2324
2325         return NULL;
2326 }
2327
2328 const char *crypt_get_uuid(struct crypt_device *cd)
2329 {
2330         if (isLUKS(cd->type))
2331                 return cd->hdr.uuid;
2332
2333         if (isPLAIN(cd->type))
2334                 return cd->plain_uuid;
2335
2336         if (isLOOPAES(cd->type))
2337                 return cd->loopaes_uuid;
2338
2339         if (isVERITY(cd->type))
2340                 return cd->verity_uuid;
2341
2342         return NULL;
2343 }
2344
2345 const char *crypt_get_device_name(struct crypt_device *cd)
2346 {
2347         return cd->device;
2348 }
2349
2350 int crypt_get_volume_key_size(struct crypt_device *cd)
2351 {
2352         if (isPLAIN(cd->type))
2353                 return cd->plain_key_size;
2354
2355         if (isLUKS(cd->type))
2356                 return cd->hdr.keyBytes;
2357
2358         if (isLOOPAES(cd->type))
2359                 return cd->loopaes_key_size;
2360
2361         if (isVERITY(cd->type))
2362                 return cd->verity_root_hash_size;
2363
2364         return 0;
2365 }
2366
2367 uint64_t crypt_get_data_offset(struct crypt_device *cd)
2368 {
2369         if (isPLAIN(cd->type))
2370                 return cd->plain_hdr.offset;
2371
2372         if (isLUKS(cd->type))
2373                 return cd->hdr.payloadOffset;
2374
2375         if (isLOOPAES(cd->type))
2376                 return cd->loopaes_hdr.offset;
2377
2378         return 0;
2379 }
2380
2381 uint64_t crypt_get_iv_offset(struct crypt_device *cd)
2382 {
2383         if (isPLAIN(cd->type))
2384                 return cd->plain_hdr.skip;
2385
2386         if (isLUKS(cd->type))
2387                 return 0;
2388
2389         if (isLOOPAES(cd->type))
2390                 return cd->loopaes_hdr.skip;
2391
2392         return 0;
2393 }
2394
2395 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
2396 {
2397         if (!isLUKS(cd->type)) {
2398                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2399                 return CRYPT_SLOT_INVALID;
2400         }
2401
2402         return LUKS_keyslot_info(&cd->hdr, keyslot);
2403 }
2404
2405 int crypt_keyslot_max(const char *type)
2406 {
2407         if (type && isLUKS(type))
2408                 return LUKS_NUMKEYS;
2409
2410         return -EINVAL;
2411 }
2412
2413 const char *crypt_get_type(struct crypt_device *cd)
2414 {
2415         return cd->type;
2416 }
2417
2418 int crypt_get_verity_info(struct crypt_device *cd,
2419         struct crypt_params_verity *vp)
2420 {
2421         if (!isVERITY(cd->type) || !vp)
2422                 return -EINVAL;
2423
2424         vp->data_device = cd->device;
2425         vp->hash_device = mdata_device(cd);
2426         vp->hash_name = cd->verity_hdr.hash_name;
2427         vp->salt = cd->verity_hdr.salt;
2428         vp->salt_size = cd->verity_hdr.salt_size;
2429         vp->data_block_size = cd->verity_hdr.data_block_size;
2430         vp->hash_block_size = cd->verity_hdr.hash_block_size;
2431         vp->data_size = cd->verity_hdr.data_size;
2432         vp->hash_area_offset = cd->verity_hdr.hash_area_offset;
2433         vp->hash_type = cd->verity_hdr.hash_type;
2434         vp->flags = cd->verity_hdr.flags & CRYPT_VERITY_NO_HEADER;
2435         return 0;
2436 }
2437
2438 int crypt_get_active_device(struct crypt_device *cd __attribute__((unused)),
2439                             const char *name,
2440                             struct crypt_active_device *cad)
2441 {
2442         struct crypt_dm_active_device dmd;
2443         int r;
2444
2445         r = dm_query_device(name, 0, &dmd);
2446         if (r < 0)
2447                 return r;
2448
2449         if (dmd.target != DM_CRYPT && dmd.target != DM_VERITY)
2450                 return -ENOTSUP;
2451
2452         cad->offset     = dmd.u.crypt.offset;
2453         cad->iv_offset  = dmd.u.crypt.iv_offset;
2454         cad->size       = dmd.size;
2455         cad->flags      = dmd.flags;
2456
2457         return 0;
2458 }