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