Fix some problems found by Coverity static analysis.
[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(cd, name, CRYPT_PLAIN, &dmd, 0);
348
349         // FIXME
350         if (!cd->plain_uuid && dm_query_device(cd, 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         dm_backend_init();
534
535         h->iteration_time = 1000;
536         h->password_verify = 0;
537         h->tries = 3;
538         h->rng_type = crypt_random_default_key_rng();
539         *cd = h;
540         return 0;
541 bad:
542         device_free(h->device);
543         free(h);
544         return r;
545 }
546
547 static int crypt_check_data_device_size(struct crypt_device *cd)
548 {
549         int r;
550         uint64_t size, size_min;
551
552         /* Check data device size, require at least one sector */
553         size_min = crypt_get_data_offset(cd) << SECTOR_SHIFT ?: SECTOR_SIZE;
554
555         r = device_size(cd->device, &size);
556         if (r < 0)
557                 return r;
558
559         if (size < size_min) {
560                 log_err(cd, _("Header detected but device %s is too small.\n"),
561                         device_path(cd->device));
562                 return -EINVAL;
563         }
564
565         return r;
566 }
567
568 int crypt_set_data_device(struct crypt_device *cd, const char *device)
569 {
570         struct device *dev = NULL;
571         int r;
572
573         log_dbg("Setting ciphertext data device to %s.", device ?: "(none)");
574
575         if (!isLUKS(cd->type) && !isVERITY(cd->type)) {
576                 log_err(cd, _("This operation is not supported for this device type.\n"));
577                 return  -EINVAL;
578         }
579
580         /* metadata device must be set */
581         if (!cd->device || !device)
582                 return -EINVAL;
583
584         r = device_alloc(&dev, device);
585         if (r < 0)
586                 return r;
587
588         if (!cd->metadata_device) {
589                 cd->metadata_device = cd->device;
590         } else
591                 device_free(cd->device);
592
593         cd->device = dev;
594
595         return crypt_check_data_device_size(cd);
596 }
597
598 static int _crypt_load_luks1(struct crypt_device *cd, int require_header, int repair)
599 {
600         struct luks_phdr hdr;
601         int r;
602
603         r = init_crypto(cd);
604         if (r < 0)
605                 return r;
606
607         r = LUKS_read_phdr(&hdr, require_header, repair, cd);
608         if (r < 0)
609                 return r;
610
611         if (!cd->type && !(cd->type = strdup(CRYPT_LUKS1)))
612                 return -ENOMEM;
613
614         memcpy(&cd->hdr, &hdr, sizeof(hdr));
615
616         return r;
617 }
618
619 static int _crypt_load_verity(struct crypt_device *cd, struct crypt_params_verity *params)
620 {
621         int r;
622         size_t sb_offset = 0;
623
624         r = init_crypto(cd);
625         if (r < 0)
626                 return r;
627
628         if (params && params->flags & CRYPT_VERITY_NO_HEADER)
629                 return -EINVAL;
630
631         if (params)
632                 sb_offset = params->hash_area_offset;
633
634         r = VERITY_read_sb(cd, sb_offset, &cd->verity_uuid, &cd->verity_hdr);
635         if (r < 0)
636                 return r;
637
638         if (params)
639                 cd->verity_hdr.flags = params->flags;
640
641         /* Hash availability checked in sb load */
642         cd->verity_root_hash_size = crypt_hash_size(cd->verity_hdr.hash_name);
643         if (cd->verity_root_hash_size > 4096)
644                 return -EINVAL;
645
646         if (!cd->type && !(cd->type = strdup(CRYPT_VERITY)))
647                 return -ENOMEM;
648
649         if (params && params->data_device &&
650             (r = crypt_set_data_device(cd, params->data_device)) < 0)
651                 return r;
652
653         return r;
654 }
655
656 static int _init_by_name_crypt(struct crypt_device *cd, const char *name)
657 {
658         struct crypt_dm_active_device dmd = {};
659         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
660         int key_nums, r;
661
662         r = dm_query_device(cd, name,
663                         DM_ACTIVE_DEVICE |
664                         DM_ACTIVE_UUID |
665                         DM_ACTIVE_CRYPT_CIPHER |
666                         DM_ACTIVE_CRYPT_KEYSIZE, &dmd);
667         if (r < 0)
668                 goto out;
669
670         if (isPLAIN(cd->type)) {
671                 cd->plain_uuid = dmd.uuid ? strdup(dmd.uuid) : NULL;
672                 cd->plain_hdr.hash = NULL; /* no way to get this */
673                 cd->plain_hdr.offset = dmd.u.crypt.offset;
674                 cd->plain_hdr.skip = dmd.u.crypt.iv_offset;
675                 cd->plain_key_size = dmd.u.crypt.vk->keylength;
676
677                 r = crypt_parse_name_and_mode(dmd.u.crypt.cipher, cipher, NULL, cipher_mode);
678                 if (!r) {
679                         cd->plain_cipher = strdup(cipher);
680                         cd->plain_cipher_mode = strdup(cipher_mode);
681                 }
682         } else if (isLOOPAES(cd->type)) {
683                 cd->loopaes_uuid = dmd.uuid ? strdup(dmd.uuid) : NULL;
684                 cd->loopaes_hdr.offset = dmd.u.crypt.offset;
685
686                 r = crypt_parse_name_and_mode(dmd.u.crypt.cipher, cipher,
687                                               &key_nums, cipher_mode);
688                 if (!r) {
689                         cd->loopaes_cipher = strdup(cipher);
690                         cd->loopaes_cipher_mode = strdup(cipher_mode);
691                         /* version 3 uses last key for IV */
692                         if (dmd.u.crypt.vk->keylength % key_nums)
693                                 key_nums++;
694                         cd->loopaes_key_size = dmd.u.crypt.vk->keylength / key_nums;
695                 }
696         } else if (isLUKS(cd->type)) {
697                 if (crypt_metadata_device(cd)) {
698                         r = _crypt_load_luks1(cd, 0, 0);
699                         if (r < 0) {
700                                 log_dbg("LUKS device header does not match active device.");
701                                 free(cd->type);
702                                 cd->type = NULL;
703                                 r = 0;
704                                 goto out;
705                         }
706                         /* check whether UUIDs match each other */
707                         r = crypt_uuid_cmp(dmd.uuid, cd->hdr.uuid);
708                         if (r < 0) {
709                                 log_dbg("LUKS device header uuid: %s mismatches DM returned uuid %s",
710                                         cd->hdr.uuid, dmd.uuid);
711                                 free(cd->type);
712                                 cd->type = NULL;
713                                 r = 0;
714                                 goto out;
715                         }
716                 }
717         }
718 out:
719         crypt_free_volume_key(dmd.u.crypt.vk);
720         device_free(dmd.data_device);
721         free(CONST_CAST(void*)dmd.u.crypt.cipher);
722         free(CONST_CAST(void*)dmd.uuid);
723         return r;
724 }
725
726 static int _init_by_name_verity(struct crypt_device *cd, const char *name)
727 {
728         struct crypt_params_verity params = {};
729         struct crypt_dm_active_device dmd = {
730                 .target = DM_VERITY,
731                 .u.verity.vp = &params,
732         };
733         int r;
734
735         r = dm_query_device(cd, name,
736                                 DM_ACTIVE_DEVICE |
737                                 DM_ACTIVE_UUID |
738                                 DM_ACTIVE_VERITY_HASH_DEVICE |
739                                 DM_ACTIVE_VERITY_PARAMS, &dmd);
740         if (r < 0)
741                 goto out;
742
743         if (isVERITY(cd->type)) {
744                 cd->verity_uuid = dmd.uuid ? strdup(dmd.uuid) : NULL;
745                 cd->verity_hdr.flags = CRYPT_VERITY_NO_HEADER; //FIXME
746                 cd->verity_hdr.data_size = params.data_size;
747                 cd->verity_root_hash_size = dmd.u.verity.root_hash_size;
748                 cd->verity_root_hash = NULL;
749                 cd->verity_hdr.hash_name = params.hash_name;
750                 cd->verity_hdr.data_device = NULL;
751                 cd->verity_hdr.hash_device = NULL;
752                 cd->verity_hdr.data_block_size = params.data_block_size;
753                 cd->verity_hdr.hash_block_size = params.hash_block_size;
754                 cd->verity_hdr.hash_area_offset = dmd.u.verity.hash_offset;
755                 cd->verity_hdr.hash_type = params.hash_type;
756                 cd->verity_hdr.flags = params.flags;
757                 cd->verity_hdr.salt_size = params.salt_size;
758                 cd->verity_hdr.salt = params.salt;
759                 cd->metadata_device = dmd.u.verity.hash_device;
760         }
761 out:
762         device_free(dmd.data_device);
763         free(CONST_CAST(void*)dmd.uuid);
764         return r;
765 }
766
767 int crypt_init_by_name_and_header(struct crypt_device **cd,
768                                   const char *name,
769                                   const char *header_device)
770 {
771         crypt_status_info ci;
772         struct crypt_dm_active_device dmd;
773         int r;
774
775         log_dbg("Allocating crypt device context by device %s.", name);
776
777         ci = crypt_status(NULL, name);
778         if (ci == CRYPT_INVALID)
779                 return -ENODEV;
780
781         if (ci < CRYPT_ACTIVE) {
782                 log_err(NULL, _("Device %s is not active.\n"), name);
783                 return -ENODEV;
784         }
785
786         r = dm_query_device(NULL, name, DM_ACTIVE_DEVICE | DM_ACTIVE_UUID, &dmd);
787         if (r < 0)
788                 goto out;
789
790         *cd = NULL;
791
792         if (header_device) {
793                 r = crypt_init(cd, header_device);
794         } else {
795                 r = crypt_init(cd, device_path(dmd.data_device));
796
797                 /* Underlying device disappeared but mapping still active */
798                 if (!dmd.data_device || r == -ENOTBLK)
799                         log_verbose(NULL, _("Underlying device for crypt device %s disappeared.\n"),
800                                     name);
801
802                 /* Underlying device is not readable but crypt mapping exists */
803                 if (r == -ENOTBLK) {
804                         device_free(dmd.data_device);
805                         dmd.data_device = NULL;
806                         r = crypt_init(cd, NULL);
807                 }
808         }
809
810         if (r < 0)
811                 goto out;
812
813         if (dmd.uuid) {
814                 if (!strncmp(CRYPT_PLAIN, dmd.uuid, sizeof(CRYPT_PLAIN)-1))
815                         (*cd)->type = strdup(CRYPT_PLAIN);
816                 else if (!strncmp(CRYPT_LOOPAES, dmd.uuid, sizeof(CRYPT_LOOPAES)-1))
817                         (*cd)->type = strdup(CRYPT_LOOPAES);
818                 else if (!strncmp(CRYPT_LUKS1, dmd.uuid, sizeof(CRYPT_LUKS1)-1))
819                         (*cd)->type = strdup(CRYPT_LUKS1);
820                 else if (!strncmp(CRYPT_VERITY, dmd.uuid, sizeof(CRYPT_VERITY)-1))
821                         (*cd)->type = strdup(CRYPT_VERITY);
822                 else
823                         log_dbg("Unknown UUID set, some parameters are not set.");
824         } else
825                 log_dbg("Active device has no UUID set, some parameters are not set.");
826
827         if (header_device) {
828                 r = crypt_set_data_device(*cd, device_path(dmd.data_device));
829                 if (r < 0)
830                         goto out;
831         }
832
833         /* Try to initialise basic parameters from active device */
834
835         if (dmd.target == DM_CRYPT)
836                 r = _init_by_name_crypt(*cd, name);
837         else if (dmd.target == DM_VERITY)
838                 r = _init_by_name_verity(*cd, name);
839 out:
840         if (r < 0) {
841                 crypt_free(*cd);
842                 *cd = NULL;
843         }
844         device_free(dmd.data_device);
845         free(CONST_CAST(void*)dmd.uuid);
846         return r;
847 }
848
849 int crypt_init_by_name(struct crypt_device **cd, const char *name)
850 {
851         return crypt_init_by_name_and_header(cd, name, NULL);
852 }
853
854 static int _crypt_format_plain(struct crypt_device *cd,
855                                const char *cipher,
856                                const char *cipher_mode,
857                                const char *uuid,
858                                size_t volume_key_size,
859                                struct crypt_params_plain *params)
860 {
861         if (!cipher || !cipher_mode) {
862                 log_err(cd, _("Invalid plain crypt parameters.\n"));
863                 return -EINVAL;
864         }
865
866         if (volume_key_size > 1024) {
867                 log_err(cd, _("Invalid key size.\n"));
868                 return -EINVAL;
869         }
870
871         if (!(cd->type = strdup(CRYPT_PLAIN)))
872                 return -ENOMEM;
873
874         cd->plain_key_size = volume_key_size;
875         cd->volume_key = crypt_alloc_volume_key(volume_key_size, NULL);
876         if (!cd->volume_key)
877                 return -ENOMEM;
878
879         cd->plain_cipher = strdup(cipher);
880         cd->plain_cipher_mode = strdup(cipher_mode);
881
882         if (uuid)
883                 cd->plain_uuid = strdup(uuid);
884
885         if (params && params->hash)
886                 cd->plain_hdr.hash = strdup(params->hash);
887
888         cd->plain_hdr.offset = params ? params->offset : 0;
889         cd->plain_hdr.skip = params ? params->skip : 0;
890         cd->plain_hdr.size = params ? params->size : 0;
891
892         if (!cd->plain_cipher || !cd->plain_cipher_mode)
893                 return -ENOMEM;
894
895         return 0;
896 }
897
898 static int _crypt_format_luks1(struct crypt_device *cd,
899                                const char *cipher,
900                                const char *cipher_mode,
901                                const char *uuid,
902                                const char *volume_key,
903                                size_t volume_key_size,
904                                struct crypt_params_luks1 *params)
905 {
906         int r;
907         unsigned long required_alignment = DEFAULT_DISK_ALIGNMENT;
908         unsigned long alignment_offset = 0;
909
910         if (!crypt_metadata_device(cd)) {
911                 log_err(cd, _("Can't format LUKS without device.\n"));
912                 return -EINVAL;
913         }
914
915         if (!(cd->type = strdup(CRYPT_LUKS1)))
916                 return -ENOMEM;
917
918         if (volume_key)
919                 cd->volume_key = crypt_alloc_volume_key(volume_key_size,
920                                                       volume_key);
921         else
922                 cd->volume_key = crypt_generate_volume_key(cd, volume_key_size);
923
924         if(!cd->volume_key)
925                 return -ENOMEM;
926
927         if (params && params->data_device) {
928                 cd->metadata_device = cd->device;
929                 cd->device = NULL;
930                 if (device_alloc(&cd->device, params->data_device) < 0)
931                         return -ENOMEM;
932                 required_alignment = params->data_alignment * SECTOR_SIZE;
933         } else if (params && params->data_alignment) {
934                 required_alignment = params->data_alignment * SECTOR_SIZE;
935         } else
936                 device_topology_alignment(cd->device,
937                                        &required_alignment,
938                                        &alignment_offset, DEFAULT_DISK_ALIGNMENT);
939
940         /* Check early if we cannot allocate block device for key slot access */
941         r = device_block_adjust(cd, cd->device, DEV_OK, 0, NULL, NULL);
942         if(r < 0)
943                 return r;
944
945         r = LUKS_generate_phdr(&cd->hdr, cd->volume_key, cipher, cipher_mode,
946                                (params && params->hash) ? params->hash : "sha1",
947                                uuid, LUKS_STRIPES,
948                                required_alignment / SECTOR_SIZE,
949                                alignment_offset / SECTOR_SIZE,
950                                cd->iteration_time, &cd->PBKDF2_per_sec,
951                                cd->metadata_device ? 1 : 0, cd);
952         if(r < 0)
953                 return r;
954
955         /* Wipe first 8 sectors - fs magic numbers etc. */
956         r = crypt_wipe(crypt_metadata_device(cd), 0, 8 * SECTOR_SIZE, CRYPT_WIPE_ZERO, 1);
957         if(r < 0) {
958                 if (r == -EBUSY)
959                         log_err(cd, _("Cannot format device %s which is still in use.\n"),
960                                 mdata_device_path(cd));
961                 else if (r == -EACCES) {
962                         log_err(cd, _("Cannot format device %s, permission denied.\n"),
963                                 mdata_device_path(cd));
964                         r = -EINVAL;
965                 } else
966                         log_err(cd, _("Cannot wipe header on device %s.\n"),
967                                 mdata_device_path(cd));
968
969                 return r;
970         }
971
972         r = LUKS_write_phdr(&cd->hdr, cd);
973
974         return r;
975 }
976
977 static int _crypt_format_loopaes(struct crypt_device *cd,
978                                  const char *cipher,
979                                  const char *uuid,
980                                  size_t volume_key_size,
981                                  struct crypt_params_loopaes *params)
982 {
983         if (!crypt_metadata_device(cd)) {
984                 log_err(cd, _("Can't format LOOPAES without device.\n"));
985                 return -EINVAL;
986         }
987
988         if (volume_key_size > 1024) {
989                 log_err(cd, _("Invalid key size.\n"));
990                 return -EINVAL;
991         }
992
993         if (!(cd->type = strdup(CRYPT_LOOPAES)))
994                 return -ENOMEM;
995
996         cd->loopaes_key_size = volume_key_size;
997
998         cd->loopaes_cipher = strdup(cipher ?: DEFAULT_LOOPAES_CIPHER);
999
1000         if (uuid)
1001                 cd->loopaes_uuid = strdup(uuid);
1002
1003         if (params && params->hash)
1004                 cd->loopaes_hdr.hash = strdup(params->hash);
1005
1006         cd->loopaes_hdr.offset = params ? params->offset : 0;
1007         cd->loopaes_hdr.skip = params ? params->skip : 0;
1008
1009         return 0;
1010 }
1011
1012 static int _crypt_format_verity(struct crypt_device *cd,
1013                                  const char *uuid,
1014                                  struct crypt_params_verity *params)
1015 {
1016         int r = 0, hash_size;
1017         uint64_t data_device_size;
1018
1019         if (!crypt_metadata_device(cd)) {
1020                 log_err(cd, _("Can't format VERITY without device.\n"));
1021                 return -EINVAL;
1022         }
1023
1024         if (!params || !params->data_device)
1025                 return -EINVAL;
1026
1027         if (params->hash_type > VERITY_MAX_HASH_TYPE) {
1028                 log_err(cd, _("Unsupported VERITY hash type %d.\n"), params->hash_type);
1029                 return -EINVAL;
1030         }
1031
1032         if (VERITY_BLOCK_SIZE_OK(params->data_block_size) ||
1033             VERITY_BLOCK_SIZE_OK(params->hash_block_size)) {
1034                 log_err(cd, _("Unsupported VERITY block size.\n"));
1035                 return -EINVAL;
1036         }
1037
1038         if (params->hash_area_offset % 512) {
1039                 log_err(cd, _("Unsupported VERITY hash offset.\n"));
1040                 return -EINVAL;
1041         }
1042
1043         if (!(cd->type = strdup(CRYPT_VERITY)))
1044                 return -ENOMEM;
1045
1046         r = crypt_set_data_device(cd, params->data_device);
1047         if (r)
1048                 return r;
1049         if (!params->data_size) {
1050                 r = device_size(cd->device, &data_device_size);
1051                 if (r < 0)
1052                         return r;
1053
1054                 cd->verity_hdr.data_size = data_device_size / params->data_block_size;
1055         } else
1056                 cd->verity_hdr.data_size = params->data_size;
1057
1058         hash_size = crypt_hash_size(params->hash_name);
1059         if (hash_size <= 0) {
1060                 log_err(cd, _("Hash algorithm %s not supported.\n"),
1061                         params->hash_name);
1062                 return -EINVAL;
1063         }
1064         cd->verity_root_hash_size = hash_size;
1065
1066         cd->verity_root_hash = malloc(cd->verity_root_hash_size);
1067         if (!cd->verity_root_hash)
1068                 return -ENOMEM;
1069
1070         cd->verity_hdr.flags = params->flags;
1071         if (!(cd->verity_hdr.hash_name = strdup(params->hash_name)))
1072                 return -ENOMEM;
1073         cd->verity_hdr.data_device = NULL;
1074         cd->verity_hdr.data_block_size = params->data_block_size;
1075         cd->verity_hdr.hash_block_size = params->hash_block_size;
1076         cd->verity_hdr.hash_area_offset = params->hash_area_offset;
1077         cd->verity_hdr.hash_type = params->hash_type;
1078         cd->verity_hdr.flags = params->flags;
1079         cd->verity_hdr.salt_size = params->salt_size;
1080         if (!(cd->verity_hdr.salt = malloc(params->salt_size)))
1081                 return -ENOMEM;
1082
1083         if (params->salt)
1084                 memcpy(CONST_CAST(char*)cd->verity_hdr.salt, params->salt,
1085                        params->salt_size);
1086         else
1087                 r = crypt_random_get(cd, CONST_CAST(char*)cd->verity_hdr.salt,
1088                                      params->salt_size, CRYPT_RND_SALT);
1089         if (r)
1090                 return r;
1091
1092         if (params->flags & CRYPT_VERITY_CREATE_HASH) {
1093                 r = VERITY_create(cd, &cd->verity_hdr,
1094                                   cd->verity_root_hash, cd->verity_root_hash_size);
1095                 if (r)
1096                         return r;
1097         }
1098
1099         if (!(params->flags & CRYPT_VERITY_NO_HEADER)) {
1100                 if (uuid)
1101                         cd->verity_uuid = strdup(uuid);
1102                 else {
1103                         r = VERITY_UUID_generate(cd, &cd->verity_uuid);
1104                         if (r)
1105                                 return r;
1106                 }
1107
1108                 r = VERITY_write_sb(cd, cd->verity_hdr.hash_area_offset,
1109                                     cd->verity_uuid,
1110                                     &cd->verity_hdr);
1111         }
1112         return r;
1113 }
1114
1115 int crypt_format(struct crypt_device *cd,
1116         const char *type,
1117         const char *cipher,
1118         const char *cipher_mode,
1119         const char *uuid,
1120         const char *volume_key,
1121         size_t volume_key_size,
1122         void *params)
1123 {
1124         int r;
1125
1126         if (!type)
1127                 return -EINVAL;
1128
1129         if (cd->type) {
1130                 log_dbg("Context already formatted as %s.", cd->type);
1131                 return -EINVAL;
1132         }
1133
1134         log_dbg("Formatting device %s as type %s.", mdata_device_path(cd) ?: "(none)", type);
1135
1136         r = init_crypto(cd);
1137         if (r < 0)
1138                 return r;
1139
1140         if (isPLAIN(type))
1141                 r = _crypt_format_plain(cd, cipher, cipher_mode,
1142                                         uuid, volume_key_size, params);
1143         else if (isLUKS(type))
1144                 r = _crypt_format_luks1(cd, cipher, cipher_mode,
1145                                         uuid, volume_key, volume_key_size, params);
1146         else if (isLOOPAES(type))
1147                 r = _crypt_format_loopaes(cd, cipher, uuid, volume_key_size, params);
1148         else if (isVERITY(type))
1149                 r = _crypt_format_verity(cd, uuid, params);
1150         else {
1151                 log_err(cd, _("Unknown crypt device type %s requested.\n"), type);
1152                 r = -EINVAL;
1153         }
1154
1155         if (r < 0) {
1156                 free(cd->type);
1157                 cd->type = NULL;
1158                 crypt_free_volume_key(cd->volume_key);
1159                 cd->volume_key = NULL;
1160         }
1161
1162         return r;
1163 }
1164
1165 int crypt_load(struct crypt_device *cd,
1166                const char *requested_type,
1167                void *params)
1168 {
1169         int r;
1170
1171         log_dbg("Trying to load %s crypt type from device %s.",
1172                 requested_type ?: "any", mdata_device_path(cd) ?: "(none)");
1173
1174         if (!crypt_metadata_device(cd))
1175                 return -EINVAL;
1176
1177         if (!requested_type || isLUKS(requested_type)) {
1178                 if (cd->type && !isLUKS(cd->type)) {
1179                         log_dbg("Context is already initialised to type %s", cd->type);
1180                         return -EINVAL;
1181                 }
1182
1183                 r = _crypt_load_luks1(cd, 1, 0);
1184         } else if (isVERITY(requested_type)) {
1185                 if (cd->type && !isVERITY(cd->type)) {
1186                         log_dbg("Context is already initialised to type %s", cd->type);
1187                         return -EINVAL;
1188                 }
1189                 r = _crypt_load_verity(cd, params);
1190         } else
1191                 return -EINVAL;
1192
1193         return r;
1194 }
1195
1196 int crypt_repair(struct crypt_device *cd,
1197                  const char *requested_type,
1198                  void *params __attribute__((unused)))
1199 {
1200         int r;
1201
1202         log_dbg("Trying to repair %s crypt type from device %s.",
1203                 requested_type ?: "any", mdata_device_path(cd) ?: "(none)");
1204
1205         if (!crypt_metadata_device(cd))
1206                 return -EINVAL;
1207
1208         if (requested_type && !isLUKS(requested_type))
1209                 return -EINVAL;
1210
1211
1212         /* Load with repair */
1213         r = _crypt_load_luks1(cd, 1, 1);
1214         if (r < 0)
1215                 return r;
1216
1217         /* cd->type and header must be set in context */
1218         r = crypt_check_data_device_size(cd);
1219         if (r < 0) {
1220                 free(cd->type);
1221                 cd->type = NULL;
1222         }
1223
1224         return r;
1225 }
1226
1227 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
1228 {
1229         struct crypt_dm_active_device dmd;
1230         int r;
1231
1232         /* Device context type must be initialised */
1233         if (!cd->type || !crypt_get_uuid(cd))
1234                 return -EINVAL;
1235
1236         log_dbg("Resizing device %s to %" PRIu64 " sectors.", name, new_size);
1237
1238         r = dm_query_device(cd, name, DM_ACTIVE_DEVICE | DM_ACTIVE_CRYPT_CIPHER |
1239                                   DM_ACTIVE_UUID | DM_ACTIVE_CRYPT_KEYSIZE |
1240                                   DM_ACTIVE_CRYPT_KEY, &dmd);
1241         if (r < 0) {
1242                 log_err(NULL, _("Device %s is not active.\n"), name);
1243                 return -EINVAL;
1244         }
1245
1246         if (!dmd.uuid || dmd.target != DM_CRYPT) {
1247                 r = -EINVAL;
1248                 goto out;
1249         }
1250
1251         r = device_block_adjust(cd, dmd.data_device, DEV_OK,
1252                                 dmd.u.crypt.offset, &new_size, &dmd.flags);
1253         if (r)
1254                 goto out;
1255
1256         if (new_size == dmd.size) {
1257                 log_dbg("Device has already requested size %" PRIu64
1258                         " sectors.", dmd.size);
1259                 r = 0;
1260         } else {
1261                 dmd.size = new_size;
1262                 r = dm_create_device(cd, name, cd->type, &dmd, 1);
1263         }
1264 out:
1265         if (dmd.target == DM_CRYPT) {
1266                 crypt_free_volume_key(dmd.u.crypt.vk);
1267                 free(CONST_CAST(void*)dmd.u.crypt.cipher);
1268         }
1269         free(CONST_CAST(void*)dmd.data_device);
1270         free(CONST_CAST(void*)dmd.uuid);
1271
1272         return r;
1273 }
1274
1275 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
1276 {
1277         if (!isLUKS(cd->type)) {
1278                 log_err(cd, _("This operation is not supported for this device type.\n"));
1279                 return  -EINVAL;
1280         }
1281
1282         if (uuid && !strncmp(uuid, cd->hdr.uuid, sizeof(cd->hdr.uuid))) {
1283                 log_dbg("UUID is the same as requested (%s) for device %s.",
1284                         uuid, mdata_device_path(cd));
1285                 return 0;
1286         }
1287
1288         if (uuid)
1289                 log_dbg("Requested new UUID change to %s for %s.", uuid, mdata_device_path(cd));
1290         else
1291                 log_dbg("Requested new UUID refresh for %s.", mdata_device_path(cd));
1292
1293         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
1294                 return -EPERM;
1295
1296         return LUKS_hdr_uuid_set(&cd->hdr, uuid, cd);
1297 }
1298
1299 int crypt_header_backup(struct crypt_device *cd,
1300                         const char *requested_type,
1301                         const char *backup_file)
1302 {
1303         int r;
1304
1305         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
1306                 return -EINVAL;
1307
1308         r = init_crypto(cd);
1309         if (r < 0)
1310                 return r;
1311
1312         log_dbg("Requested header backup of device %s (%s) to "
1313                 "file %s.", mdata_device_path(cd), requested_type, backup_file);
1314
1315         return LUKS_hdr_backup(backup_file, &cd->hdr, cd);
1316 }
1317
1318 int crypt_header_restore(struct crypt_device *cd,
1319                          const char *requested_type,
1320                          const char *backup_file)
1321 {
1322         int r;
1323
1324         if (requested_type && !isLUKS(requested_type))
1325                 return -EINVAL;
1326
1327         r = init_crypto(cd);
1328         if (r < 0)
1329                 return r;
1330
1331         log_dbg("Requested header restore to device %s (%s) from "
1332                 "file %s.", mdata_device_path(cd), requested_type, backup_file);
1333
1334         return LUKS_hdr_restore(backup_file, &cd->hdr, cd);
1335 }
1336
1337 void crypt_free(struct crypt_device *cd)
1338 {
1339         if (cd) {
1340                 log_dbg("Releasing crypt device %s context.", mdata_device_path(cd));
1341
1342                 dm_backend_exit();
1343                 crypt_free_volume_key(cd->volume_key);
1344
1345                 device_free(cd->device);
1346                 device_free(cd->metadata_device);
1347                 free(cd->type);
1348
1349                 /* used in plain device only */
1350                 free(CONST_CAST(void*)cd->plain_hdr.hash);
1351                 free(cd->plain_cipher);
1352                 free(cd->plain_cipher_mode);
1353                 free(cd->plain_uuid);
1354
1355                 /* used in loop-AES device only */
1356                 free(CONST_CAST(void*)cd->loopaes_hdr.hash);
1357                 free(cd->loopaes_cipher);
1358                 free(cd->loopaes_uuid);
1359
1360                 /* used in verity device only */
1361                 free(CONST_CAST(void*)cd->verity_hdr.hash_name);
1362                 free(CONST_CAST(void*)cd->verity_hdr.salt);
1363                 free(cd->verity_root_hash);
1364                 free(cd->verity_uuid);
1365
1366                 free(cd);
1367         }
1368 }
1369
1370 int crypt_suspend(struct crypt_device *cd,
1371                   const char *name)
1372 {
1373         crypt_status_info ci;
1374         int r;
1375
1376         log_dbg("Suspending volume %s.", name);
1377
1378         if (!cd || !isLUKS(cd->type)) {
1379                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1380                 r = -EINVAL;
1381                 goto out;
1382         }
1383
1384         ci = crypt_status(NULL, name);
1385         if (ci < CRYPT_ACTIVE) {
1386                 log_err(cd, _("Volume %s is not active.\n"), name);
1387                 return -EINVAL;
1388         }
1389
1390         dm_backend_init();
1391
1392         r = dm_status_suspended(cd, name);
1393         if (r < 0)
1394                 goto out;
1395
1396         if (r) {
1397                 log_err(cd, _("Volume %s is already suspended.\n"), name);
1398                 r = -EINVAL;
1399                 goto out;
1400         }
1401
1402         r = dm_suspend_and_wipe_key(cd, name);
1403         if (r == -ENOTSUP)
1404                 log_err(cd, "Suspend is not supported for device %s.\n", name);
1405         else if (r)
1406                 log_err(cd, "Error during suspending device %s.\n", name);
1407 out:
1408         dm_backend_exit();
1409         return r;
1410 }
1411
1412 int crypt_resume_by_passphrase(struct crypt_device *cd,
1413                                const char *name,
1414                                int keyslot,
1415                                const char *passphrase,
1416                                size_t passphrase_size)
1417 {
1418         struct volume_key *vk = NULL;
1419         int r;
1420
1421         log_dbg("Resuming volume %s.", name);
1422
1423         if (!isLUKS(cd->type)) {
1424                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1425                 r = -EINVAL;
1426                 goto out;
1427         }
1428
1429         r = dm_status_suspended(cd, name);
1430         if (r < 0)
1431                 return r;
1432
1433         if (!r) {
1434                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1435                 return -EINVAL;
1436         }
1437
1438         if (passphrase) {
1439                 r = LUKS_open_key_with_hdr(keyslot, passphrase, passphrase_size,
1440                                            &cd->hdr, &vk, cd);
1441         } else
1442                 r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1443
1444         if (r >= 0) {
1445                 keyslot = r;
1446                 r = dm_resume_and_reinstate_key(cd, name, vk->keylength, vk->key);
1447                 if (r == -ENOTSUP)
1448                         log_err(cd, "Resume is not supported for device %s.\n", name);
1449                 else if (r)
1450                         log_err(cd, "Error during resuming device %s.\n", name);
1451         } else
1452                 r = keyslot;
1453 out:
1454         crypt_free_volume_key(vk);
1455         return r < 0 ? r : keyslot;
1456 }
1457
1458 int crypt_resume_by_keyfile_offset(struct crypt_device *cd,
1459                                    const char *name,
1460                                    int keyslot,
1461                                    const char *keyfile,
1462                                    size_t keyfile_size,
1463                                    size_t keyfile_offset)
1464 {
1465         struct volume_key *vk = NULL;
1466         char *passphrase_read = NULL;
1467         size_t passphrase_size_read;
1468         int r;
1469
1470         log_dbg("Resuming volume %s.", name);
1471
1472         if (!isLUKS(cd->type)) {
1473                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1474                 r = -EINVAL;
1475                 goto out;
1476         }
1477
1478         r = dm_status_suspended(cd, name);
1479         if (r < 0)
1480                 return r;
1481
1482         if (!r) {
1483                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1484                 return -EINVAL;
1485         }
1486
1487         if (!keyfile)
1488                 return -EINVAL;
1489
1490         r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1491                           &passphrase_size_read, keyfile, keyfile_offset,
1492                           keyfile_size);
1493         if (r < 0)
1494                 goto out;
1495
1496         r = LUKS_open_key_with_hdr(keyslot, passphrase_read,
1497                                    passphrase_size_read, &cd->hdr, &vk, cd);
1498         if (r < 0)
1499                 goto out;
1500
1501         keyslot = r;
1502         r = dm_resume_and_reinstate_key(cd, name, vk->keylength, vk->key);
1503         if (r)
1504                 log_err(cd, "Error during resuming device %s.\n", name);
1505 out:
1506         crypt_safe_free(passphrase_read);
1507         crypt_free_volume_key(vk);
1508         return r < 0 ? r : keyslot;
1509 }
1510
1511 int crypt_resume_by_keyfile(struct crypt_device *cd,
1512                             const char *name,
1513                             int keyslot,
1514                             const char *keyfile,
1515                             size_t keyfile_size)
1516 {
1517         return crypt_resume_by_keyfile_offset(cd, name, keyslot,
1518                                               keyfile, keyfile_size, 0);
1519 }
1520
1521 // slot manipulation
1522 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1523         int keyslot, // -1 any
1524         const char *passphrase, // NULL -> terminal
1525         size_t passphrase_size,
1526         const char *new_passphrase, // NULL -> terminal
1527         size_t new_passphrase_size)
1528 {
1529         struct volume_key *vk = NULL;
1530         char *password = NULL, *new_password = NULL;
1531         size_t passwordLen, new_passwordLen;
1532         int r;
1533
1534         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1535                 "new passphrase %sprovided.",
1536                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1537
1538         if (!isLUKS(cd->type)) {
1539                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1540                 return -EINVAL;
1541         }
1542
1543         r = keyslot_verify_or_find_empty(cd, &keyslot);
1544         if (r)
1545                 return r;
1546
1547         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1548                 /* No slots used, try to use pre-generated key in header */
1549                 if (cd->volume_key) {
1550                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1551                         r = vk ? 0 : -ENOMEM;
1552                 } else {
1553                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1554                         return -EINVAL;
1555                 }
1556         } else if (passphrase) {
1557                 /* Passphrase provided, use it to unlock existing keyslot */
1558                 r = LUKS_open_key_with_hdr(CRYPT_ANY_SLOT, passphrase,
1559                                            passphrase_size, &cd->hdr, &vk, cd);
1560         } else {
1561                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1562                 r = key_from_terminal(cd, _("Enter any passphrase: "),
1563                                       &password, &passwordLen, 0);
1564                 if (r < 0)
1565                         goto out;
1566
1567                 r = LUKS_open_key_with_hdr(CRYPT_ANY_SLOT, password,
1568                                            passwordLen, &cd->hdr, &vk, cd);
1569                 crypt_safe_free(password);
1570         }
1571
1572         if(r < 0)
1573                 goto out;
1574
1575         if (new_passphrase) {
1576                 new_password = CONST_CAST(char*)new_passphrase;
1577                 new_passwordLen = new_passphrase_size;
1578         } else {
1579                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1580                                       &new_password, &new_passwordLen, 1);
1581                 if(r < 0)
1582                         goto out;
1583         }
1584
1585         r = LUKS_set_key(keyslot, new_password, new_passwordLen,
1586                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1587         if(r < 0) goto out;
1588
1589         r = 0;
1590 out:
1591         if (!new_passphrase)
1592                 crypt_safe_free(new_password);
1593         crypt_free_volume_key(vk);
1594         return r ?: keyslot;
1595 }
1596
1597 int crypt_keyslot_add_by_keyfile_offset(struct crypt_device *cd,
1598         int keyslot,
1599         const char *keyfile,
1600         size_t keyfile_size,
1601         size_t keyfile_offset,
1602         const char *new_keyfile,
1603         size_t new_keyfile_size,
1604         size_t new_keyfile_offset)
1605 {
1606         struct volume_key *vk = NULL;
1607         char *password = NULL; size_t passwordLen;
1608         char *new_password = NULL; size_t new_passwordLen;
1609         int r;
1610
1611         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1612                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1613
1614         if (!isLUKS(cd->type)) {
1615                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1616                 return -EINVAL;
1617         }
1618
1619         r = keyslot_verify_or_find_empty(cd, &keyslot);
1620         if (r)
1621                 return r;
1622
1623         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1624                 /* No slots used, try to use pre-generated key in header */
1625                 if (cd->volume_key) {
1626                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1627                         r = vk ? 0 : -ENOMEM;
1628                 } else {
1629                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1630                         return -EINVAL;
1631                 }
1632         } else {
1633                 /* Read password from file of (if NULL) from terminal */
1634                 if (keyfile)
1635                         r = key_from_file(cd, _("Enter any passphrase: "),
1636                                           &password, &passwordLen,
1637                                           keyfile, keyfile_offset, keyfile_size);
1638                 else
1639                         r = key_from_terminal(cd, _("Enter any passphrase: "),
1640                                               &password, &passwordLen, 0);
1641                 if (r < 0)
1642                         goto out;
1643
1644                 r = LUKS_open_key_with_hdr(CRYPT_ANY_SLOT, password, passwordLen,
1645                                            &cd->hdr, &vk, cd);
1646         }
1647
1648         if(r < 0)
1649                 goto out;
1650
1651         if (new_keyfile)
1652                 r = key_from_file(cd, _("Enter new passphrase for key slot: "),
1653                                   &new_password, &new_passwordLen, new_keyfile,
1654                                   new_keyfile_offset, new_keyfile_size);
1655         else
1656                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1657                                       &new_password, &new_passwordLen, 1);
1658         if (r < 0)
1659                 goto out;
1660
1661         r = LUKS_set_key(keyslot, new_password, new_passwordLen,
1662                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1663 out:
1664         crypt_safe_free(password);
1665         crypt_safe_free(new_password);
1666         crypt_free_volume_key(vk);
1667         return r < 0 ? r : keyslot;
1668 }
1669
1670 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1671         int keyslot,
1672         const char *keyfile,
1673         size_t keyfile_size,
1674         const char *new_keyfile,
1675         size_t new_keyfile_size)
1676 {
1677         return crypt_keyslot_add_by_keyfile_offset(cd, keyslot,
1678                                 keyfile, keyfile_size, 0,
1679                                 new_keyfile, new_keyfile_size, 0);
1680 }
1681
1682 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1683         int keyslot,
1684         const char *volume_key,
1685         size_t volume_key_size,
1686         const char *passphrase,
1687         size_t passphrase_size)
1688 {
1689         struct volume_key *vk = NULL;
1690         int r = -EINVAL;
1691         char *new_password = NULL; size_t new_passwordLen;
1692
1693         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1694
1695         if (!isLUKS(cd->type)) {
1696                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1697                 return -EINVAL;
1698         }
1699
1700         if (volume_key)
1701                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1702         else if (cd->volume_key)
1703                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1704
1705         if (!vk)
1706                 return -ENOMEM;
1707
1708         r = LUKS_verify_volume_key(&cd->hdr, vk);
1709         if (r < 0) {
1710                 log_err(cd, _("Volume key does not match the volume.\n"));
1711                 goto out;
1712         }
1713
1714         r = keyslot_verify_or_find_empty(cd, &keyslot);
1715         if (r)
1716                 goto out;
1717
1718         if (!passphrase) {
1719                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1720                                       &new_password, &new_passwordLen, 1);
1721                 if (r < 0)
1722                         goto out;
1723                 passphrase = new_password;
1724                 passphrase_size = new_passwordLen;
1725         }
1726
1727         r = LUKS_set_key(keyslot, passphrase, passphrase_size,
1728                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1729 out:
1730         crypt_safe_free(new_password);
1731         crypt_free_volume_key(vk);
1732         return (r < 0) ? r : keyslot;
1733 }
1734
1735 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1736 {
1737         crypt_keyslot_info ki;
1738
1739         log_dbg("Destroying keyslot %d.", keyslot);
1740
1741         if (!isLUKS(cd->type)) {
1742                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1743                 return -EINVAL;
1744         }
1745
1746         ki = crypt_keyslot_status(cd, keyslot);
1747         if (ki == CRYPT_SLOT_INVALID) {
1748                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1749                 return -EINVAL;
1750         }
1751
1752         if (ki == CRYPT_SLOT_INACTIVE) {
1753                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1754                 return -EINVAL;
1755         }
1756
1757         return LUKS_del_key(keyslot, &cd->hdr, cd);
1758 }
1759
1760 // activation/deactivation of device mapping
1761 int crypt_activate_by_passphrase(struct crypt_device *cd,
1762         const char *name,
1763         int keyslot,
1764         const char *passphrase,
1765         size_t passphrase_size,
1766         uint32_t flags)
1767 {
1768         crypt_status_info ci;
1769         struct volume_key *vk = NULL;
1770         char *read_passphrase = NULL;
1771         size_t passphraseLen = 0;
1772         int r;
1773
1774         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1775                 name ? "Activating" : "Checking", name ?: "",
1776                 keyslot, passphrase ? "" : "[none] ");
1777
1778         if (name) {
1779                 ci = crypt_status(NULL, name);
1780                 if (ci == CRYPT_INVALID)
1781                         return -EINVAL;
1782                 else if (ci >= CRYPT_ACTIVE) {
1783                         log_err(cd, _("Device %s already exists.\n"), name);
1784                         return -EEXIST;
1785                 }
1786         }
1787
1788         /* plain, use hashed passphrase */
1789         if (isPLAIN(cd->type)) {
1790                 if (!name)
1791                         return -EINVAL;
1792
1793                 if (!passphrase) {
1794                         r = key_from_terminal(cd, NULL, &read_passphrase,
1795                                               &passphraseLen, 0);
1796                         if (r < 0)
1797                                 goto out;
1798                         passphrase = read_passphrase;
1799                         passphrase_size = passphraseLen;
1800                 }
1801
1802                 r = process_key(cd, cd->plain_hdr.hash,
1803                                 cd->plain_key_size,
1804                                 passphrase, passphrase_size, &vk);
1805                 if (r < 0)
1806                         goto out;
1807
1808                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1809                 keyslot = 0;
1810         } else if (isLUKS(cd->type)) {
1811                 /* provided passphrase, do not retry */
1812                 if (passphrase) {
1813                         r = LUKS_open_key_with_hdr(keyslot, passphrase,
1814                                                    passphrase_size, &cd->hdr, &vk, cd);
1815                 } else
1816                         r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1817
1818                 if (r >= 0) {
1819                         keyslot = r;
1820                         if (name)
1821                                 r = LUKS1_activate(cd, name, vk, flags);
1822                 }
1823         } else
1824                 r = -EINVAL;
1825 out:
1826         crypt_safe_free(read_passphrase);
1827         crypt_free_volume_key(vk);
1828
1829         return r < 0  ? r : keyslot;
1830 }
1831
1832 int crypt_activate_by_keyfile_offset(struct crypt_device *cd,
1833         const char *name,
1834         int keyslot,
1835         const char *keyfile,
1836         size_t keyfile_size,
1837         size_t keyfile_offset,
1838         uint32_t flags)
1839 {
1840         crypt_status_info ci;
1841         struct volume_key *vk = NULL;
1842         char *passphrase_read = NULL;
1843         size_t passphrase_size_read;
1844         unsigned int key_count = 0;
1845         int r;
1846
1847         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1848                 name ?: "", keyslot, keyfile ?: "[none]");
1849
1850         if (name) {
1851                 ci = crypt_status(NULL, name);
1852                 if (ci == CRYPT_INVALID)
1853                         return -EINVAL;
1854                 else if (ci >= CRYPT_ACTIVE) {
1855                         log_err(cd, _("Device %s already exists.\n"), name);
1856                         return -EEXIST;
1857                 }
1858         }
1859
1860         if (!keyfile)
1861                 return -EINVAL;
1862
1863         if (isPLAIN(cd->type)) {
1864                 if (!name)
1865                         return -EINVAL;
1866
1867                 r = key_from_file(cd, _("Enter passphrase: "),
1868                                   &passphrase_read, &passphrase_size_read,
1869                                   keyfile, keyfile_offset, keyfile_size);
1870                 if (r < 0)
1871                         goto out;
1872
1873                 r = process_key(cd, cd->plain_hdr.hash,
1874                                 cd->plain_key_size,
1875                                 passphrase_read, passphrase_size_read, &vk);
1876                 if (r < 0)
1877                         goto out;
1878
1879                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1880         } else if (isLUKS(cd->type)) {
1881                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1882                           &passphrase_size_read, keyfile, keyfile_offset, keyfile_size);
1883                 if (r < 0)
1884                         goto out;
1885                 r = LUKS_open_key_with_hdr(keyslot, passphrase_read,
1886                                            passphrase_size_read, &cd->hdr, &vk, cd);
1887                 if (r < 0)
1888                         goto out;
1889                 keyslot = r;
1890
1891                 if (name) {
1892                         r = LUKS1_activate(cd, name, vk, flags);
1893                         if (r < 0)
1894                                 goto out;
1895                 }
1896                 r = keyslot;
1897         } else if (isLOOPAES(cd->type)) {
1898                 r = key_from_file(cd, NULL, &passphrase_read, &passphrase_size_read,
1899                                   keyfile, keyfile_offset, keyfile_size);
1900                 if (r < 0)
1901                         goto out;
1902                 r = LOOPAES_parse_keyfile(cd, &vk, cd->loopaes_hdr.hash, &key_count,
1903                                           passphrase_read, passphrase_size_read);
1904                 if (r < 0)
1905                         goto out;
1906                 if (name)
1907                         r = LOOPAES_activate(cd, name, cd->loopaes_cipher,
1908                                              key_count, vk, flags);
1909         } else
1910                 r = -EINVAL;
1911
1912 out:
1913         crypt_safe_free(passphrase_read);
1914         crypt_free_volume_key(vk);
1915
1916         return r;
1917 }
1918
1919 int crypt_activate_by_keyfile(struct crypt_device *cd,
1920         const char *name,
1921         int keyslot,
1922         const char *keyfile,
1923         size_t keyfile_size,
1924         uint32_t flags)
1925 {
1926         return crypt_activate_by_keyfile_offset(cd, name, keyslot, keyfile,
1927                                                 keyfile_size, 0, flags);
1928 }
1929
1930 int crypt_activate_by_volume_key(struct crypt_device *cd,
1931         const char *name,
1932         const char *volume_key,
1933         size_t volume_key_size,
1934         uint32_t flags)
1935 {
1936         crypt_status_info ci;
1937         struct volume_key *vk = NULL;
1938         int r = -EINVAL;
1939
1940         log_dbg("Activating volume %s by volume key.", name ?: "[none]");
1941
1942         if (name) {
1943                 ci = crypt_status(NULL, name);
1944                 if (ci == CRYPT_INVALID)
1945                         return -EINVAL;
1946                 else if (ci >= CRYPT_ACTIVE) {
1947                         log_err(cd, _("Device %s already exists.\n"), name);
1948                         return -EEXIST;
1949                 }
1950         }
1951
1952         /* use key directly, no hash */
1953         if (isPLAIN(cd->type)) {
1954                 if (!name)
1955                         return -EINVAL;
1956
1957                 if (!volume_key || !volume_key_size || volume_key_size != cd->plain_key_size) {
1958                         log_err(cd, _("Incorrect volume key specified for plain device.\n"));
1959                         return -EINVAL;
1960                 }
1961
1962                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1963                 if (!vk)
1964                         return -ENOMEM;
1965
1966                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1967         } else if (isLUKS(cd->type)) {
1968                 /* If key is not provided, try to use internal key */
1969                 if (!volume_key) {
1970                         if (!cd->volume_key) {
1971                                 log_err(cd, _("Volume key does not match the volume.\n"));
1972                                 return -EINVAL;
1973                         }
1974                         volume_key_size = cd->volume_key->keylength;
1975                         volume_key = cd->volume_key->key;
1976                 }
1977
1978                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1979                 if (!vk)
1980                         return -ENOMEM;
1981                 r = LUKS_verify_volume_key(&cd->hdr, vk);
1982
1983                 if (r == -EPERM)
1984                         log_err(cd, _("Volume key does not match the volume.\n"));
1985
1986                 if (!r && name)
1987                         r = LUKS1_activate(cd, name, vk, flags);
1988         } else if (isVERITY(cd->type)) {
1989                 /* volume_key == root hash */
1990                 if (!volume_key || !volume_key_size) {
1991                         log_err(cd, _("Incorrect root hash specified for verity device.\n"));
1992                         return -EINVAL;
1993                 }
1994
1995                 r = VERITY_activate(cd, name, volume_key, volume_key_size,
1996                                     &cd->verity_hdr, CRYPT_ACTIVATE_READONLY);
1997
1998                 if (r == -EPERM) {
1999                         free(cd->verity_root_hash);
2000                         cd->verity_root_hash = NULL;
2001                 } if (!r) {
2002                         cd->verity_root_hash_size = volume_key_size;
2003                         if (!cd->verity_root_hash)
2004                                 cd->verity_root_hash = malloc(volume_key_size);
2005                         if (cd->verity_root_hash)
2006                                 memcpy(cd->verity_root_hash, volume_key, volume_key_size);
2007                 }
2008         } else
2009                 log_err(cd, _("Device type is not properly initialised.\n"));
2010
2011         crypt_free_volume_key(vk);
2012
2013         return r;
2014 }
2015
2016 int crypt_deactivate(struct crypt_device *cd, const char *name)
2017 {
2018         int r;
2019
2020         if (!name)
2021                 return -EINVAL;
2022
2023         log_dbg("Deactivating volume %s.", name);
2024
2025         if (!cd)
2026                 dm_backend_init();
2027
2028         switch (crypt_status(cd, name)) {
2029                 case CRYPT_ACTIVE:
2030                 case CRYPT_BUSY:
2031                         r = dm_remove_device(cd, name, 0, 0);
2032                         break;
2033                 case CRYPT_INACTIVE:
2034                         log_err(cd, _("Device %s is not active.\n"), name);
2035                         r = -ENODEV;
2036                         break;
2037                 default:
2038                         log_err(cd, _("Invalid device %s.\n"), name);
2039                         r = -EINVAL;
2040         }
2041
2042         if (!cd)
2043                 dm_backend_exit();
2044
2045         return r;
2046 }
2047
2048 int crypt_volume_key_get(struct crypt_device *cd,
2049         int keyslot,
2050         char *volume_key,
2051         size_t *volume_key_size,
2052         const char *passphrase,
2053         size_t passphrase_size)
2054 {
2055         struct volume_key *vk = NULL;
2056         unsigned key_len;
2057         int r = -EINVAL;
2058
2059         if (crypt_fips_mode()) {
2060                 log_err(cd, "Function not available in FIPS mode.\n");
2061                 return -EACCES;
2062         }
2063
2064         key_len = crypt_get_volume_key_size(cd);
2065         if (key_len > *volume_key_size) {
2066                 log_err(cd, _("Volume key buffer too small.\n"));
2067                 return -ENOMEM;
2068         }
2069
2070         if (isPLAIN(cd->type) && cd->plain_hdr.hash) {
2071                 r = process_key(cd, cd->plain_hdr.hash, key_len,
2072                                 passphrase, passphrase_size, &vk);
2073                 if (r < 0)
2074                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
2075         } else if (isLUKS(cd->type)) {
2076                 r = LUKS_open_key_with_hdr(keyslot, passphrase,
2077                                         passphrase_size, &cd->hdr, &vk, cd);
2078
2079         } else
2080                 log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
2081
2082         if (r >= 0) {
2083                 memcpy(volume_key, vk->key, vk->keylength);
2084                 *volume_key_size = vk->keylength;
2085         }
2086
2087         crypt_free_volume_key(vk);
2088         return r;
2089 }
2090
2091 int crypt_volume_key_verify(struct crypt_device *cd,
2092         const char *volume_key,
2093         size_t volume_key_size)
2094 {
2095         struct volume_key *vk;
2096         int r;
2097
2098         if (!isLUKS(cd->type)) {
2099                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2100                 return -EINVAL;
2101         }
2102
2103         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2104         if (!vk)
2105                 return -ENOMEM;
2106
2107         r = LUKS_verify_volume_key(&cd->hdr, vk);
2108
2109         if (r == -EPERM)
2110                 log_err(cd, _("Volume key does not match the volume.\n"));
2111
2112         crypt_free_volume_key(vk);
2113
2114         return r;
2115 }
2116
2117 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
2118 {
2119         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
2120         cd->timeout = timeout_sec;
2121 }
2122
2123 void crypt_set_password_retry(struct crypt_device *cd, int tries)
2124 {
2125         log_dbg("Password retry count set to %d.", tries);
2126         cd->tries = tries;
2127 }
2128
2129 void crypt_set_iteration_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2130 {
2131         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
2132         cd->iteration_time = iteration_time_ms;
2133 }
2134 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2135 {
2136         crypt_set_iteration_time(cd, iteration_time_ms);
2137 }
2138
2139 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
2140 {
2141         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
2142         cd->password_verify = password_verify ? 1 : 0;
2143 }
2144
2145 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
2146 {
2147         switch (rng_type) {
2148         case CRYPT_RNG_URANDOM:
2149         case CRYPT_RNG_RANDOM:
2150                 log_dbg("RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
2151                 cd->rng_type = rng_type;
2152         }
2153 }
2154
2155 int crypt_get_rng_type(struct crypt_device *cd)
2156 {
2157         if (!cd)
2158                 return -EINVAL;
2159
2160         return cd->rng_type;
2161 }
2162
2163 int crypt_memory_lock(struct crypt_device *cd, int lock)
2164 {
2165         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
2166 }
2167
2168 // reporting
2169 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
2170 {
2171         int r;
2172
2173         if (!cd)
2174                 dm_backend_init();
2175
2176         r = dm_status_device(cd, name);
2177
2178         if (!cd)
2179                 dm_backend_exit();
2180
2181         if (r < 0 && r != -ENODEV)
2182                 return CRYPT_INVALID;
2183
2184         if (r == 0)
2185                 return CRYPT_ACTIVE;
2186
2187         if (r > 0)
2188                 return CRYPT_BUSY;
2189
2190         return CRYPT_INACTIVE;
2191 }
2192
2193 static void hexprint(struct crypt_device *cd, const char *d, int n, const char *sep)
2194 {
2195         int i;
2196         for(i = 0; i < n; i++)
2197                 log_std(cd, "%02hhx%s", (const char)d[i], sep);
2198 }
2199
2200 static int _luks_dump(struct crypt_device *cd)
2201 {
2202         int i;
2203
2204         log_std(cd, "LUKS header information for %s\n\n", mdata_device_path(cd));
2205         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
2206         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
2207         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
2208         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
2209         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
2210         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
2211         log_std(cd, "MK digest:     \t");
2212         hexprint(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE, " ");
2213         log_std(cd, "\n");
2214         log_std(cd, "MK salt:       \t");
2215         hexprint(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2, " ");
2216         log_std(cd, "\n               \t");
2217         hexprint(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
2218         log_std(cd, "\n");
2219         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
2220         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
2221         for(i = 0; i < LUKS_NUMKEYS; i++) {
2222                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
2223                         log_std(cd, "Key Slot %d: ENABLED\n",i);
2224                         log_std(cd, "\tIterations:         \t%d\n",
2225                                 cd->hdr.keyblock[i].passwordIterations);
2226                         log_std(cd, "\tSalt:               \t");
2227                         hexprint(cd, cd->hdr.keyblock[i].passwordSalt,
2228                                  LUKS_SALTSIZE/2, " ");
2229                         log_std(cd, "\n\t                      \t");
2230                         hexprint(cd, cd->hdr.keyblock[i].passwordSalt +
2231                                  LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
2232                         log_std(cd, "\n");
2233
2234                         log_std(cd, "\tKey material offset:\t%d\n",
2235                                 cd->hdr.keyblock[i].keyMaterialOffset);
2236                         log_std(cd, "\tAF stripes:            \t%d\n",
2237                                 cd->hdr.keyblock[i].stripes);
2238                 }
2239                 else 
2240                         log_std(cd, "Key Slot %d: DISABLED\n", i);
2241         }
2242         return 0;
2243 }
2244
2245 static int _verity_dump(struct crypt_device *cd)
2246 {
2247         log_std(cd, "VERITY header information for %s\n", mdata_device_path(cd));
2248         log_std(cd, "UUID:            \t%s\n", cd->verity_uuid ?: "");
2249         log_std(cd, "Hash type:       \t%u\n", cd->verity_hdr.hash_type);
2250         log_std(cd, "Data blocks:     \t%" PRIu64 "\n", cd->verity_hdr.data_size);
2251         log_std(cd, "Data block size: \t%u\n", cd->verity_hdr.data_block_size);
2252         log_std(cd, "Hash block size: \t%u\n", cd->verity_hdr.hash_block_size);
2253         log_std(cd, "Hash algorithm:  \t%s\n", cd->verity_hdr.hash_name);
2254         log_std(cd, "Salt:            \t");
2255         if (cd->verity_hdr.salt_size)
2256                 hexprint(cd, cd->verity_hdr.salt, cd->verity_hdr.salt_size, "");
2257         else
2258                 log_std(cd, "-");
2259         log_std(cd, "\n");
2260         if (cd->verity_root_hash) {
2261                 log_std(cd, "Root hash:      \t");
2262                 hexprint(cd, cd->verity_root_hash, cd->verity_root_hash_size, "");
2263                 log_std(cd, "\n");
2264         }
2265         return 0;
2266 }
2267
2268 int crypt_dump(struct crypt_device *cd)
2269 {
2270         if (isLUKS(cd->type))
2271                 return _luks_dump(cd);
2272         else if (isVERITY(cd->type))
2273                 return _verity_dump(cd);
2274
2275         log_err(cd, _("Dump operation is not supported for this device type.\n"));
2276         return -EINVAL;
2277 }
2278
2279 const char *crypt_get_cipher(struct crypt_device *cd)
2280 {
2281         if (isPLAIN(cd->type))
2282                 return cd->plain_cipher;
2283
2284         if (isLUKS(cd->type))
2285                 return cd->hdr.cipherName;
2286
2287         if (isLOOPAES(cd->type))
2288                 return cd->loopaes_cipher;
2289
2290         return NULL;
2291 }
2292
2293 const char *crypt_get_cipher_mode(struct crypt_device *cd)
2294 {
2295         if (isPLAIN(cd->type))
2296                 return cd->plain_cipher_mode;
2297
2298         if (isLUKS(cd->type))
2299                 return cd->hdr.cipherMode;
2300
2301         if (isLOOPAES(cd->type))
2302                 return cd->loopaes_cipher_mode;
2303
2304         return NULL;
2305 }
2306
2307 const char *crypt_get_uuid(struct crypt_device *cd)
2308 {
2309         if (isLUKS(cd->type))
2310                 return cd->hdr.uuid;
2311
2312         if (isPLAIN(cd->type))
2313                 return cd->plain_uuid;
2314
2315         if (isLOOPAES(cd->type))
2316                 return cd->loopaes_uuid;
2317
2318         if (isVERITY(cd->type))
2319                 return cd->verity_uuid;
2320
2321         return NULL;
2322 }
2323
2324 const char *crypt_get_device_name(struct crypt_device *cd)
2325 {
2326         const char *path = device_block_path(cd->device);
2327
2328         if (!path)
2329                 path = device_path(cd->device);
2330
2331         return path;
2332 }
2333
2334 int crypt_get_volume_key_size(struct crypt_device *cd)
2335 {
2336         if (isPLAIN(cd->type))
2337                 return cd->plain_key_size;
2338
2339         if (isLUKS(cd->type))
2340                 return cd->hdr.keyBytes;
2341
2342         if (isLOOPAES(cd->type))
2343                 return cd->loopaes_key_size;
2344
2345         if (isVERITY(cd->type))
2346                 return cd->verity_root_hash_size;
2347
2348         return 0;
2349 }
2350
2351 uint64_t crypt_get_data_offset(struct crypt_device *cd)
2352 {
2353         if (isPLAIN(cd->type))
2354                 return cd->plain_hdr.offset;
2355
2356         if (isLUKS(cd->type))
2357                 return cd->hdr.payloadOffset;
2358
2359         if (isLOOPAES(cd->type))
2360                 return cd->loopaes_hdr.offset;
2361
2362         return 0;
2363 }
2364
2365 uint64_t crypt_get_iv_offset(struct crypt_device *cd)
2366 {
2367         if (isPLAIN(cd->type))
2368                 return cd->plain_hdr.skip;
2369
2370         if (isLUKS(cd->type))
2371                 return 0;
2372
2373         if (isLOOPAES(cd->type))
2374                 return cd->loopaes_hdr.skip;
2375
2376         return 0;
2377 }
2378
2379 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
2380 {
2381         if (!isLUKS(cd->type)) {
2382                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2383                 return CRYPT_SLOT_INVALID;
2384         }
2385
2386         return LUKS_keyslot_info(&cd->hdr, keyslot);
2387 }
2388
2389 int crypt_keyslot_max(const char *type)
2390 {
2391         if (type && isLUKS(type))
2392                 return LUKS_NUMKEYS;
2393
2394         return -EINVAL;
2395 }
2396
2397 int crypt_keyslot_area(struct crypt_device *cd,
2398         int keyslot,
2399         uint64_t *offset,
2400         uint64_t *length)
2401 {
2402         if (!isLUKS(cd->type))
2403                 return -EINVAL;
2404
2405         return LUKS_keyslot_area(&cd->hdr, keyslot, offset, length);
2406 }
2407
2408 const char *crypt_get_type(struct crypt_device *cd)
2409 {
2410         return cd->type;
2411 }
2412
2413 int crypt_get_verity_info(struct crypt_device *cd,
2414         struct crypt_params_verity *vp)
2415 {
2416         if (!isVERITY(cd->type) || !vp)
2417                 return -EINVAL;
2418
2419         vp->data_device = device_path(cd->device);
2420         vp->hash_device = mdata_device_path(cd);
2421         vp->hash_name = cd->verity_hdr.hash_name;
2422         vp->salt = cd->verity_hdr.salt;
2423         vp->salt_size = cd->verity_hdr.salt_size;
2424         vp->data_block_size = cd->verity_hdr.data_block_size;
2425         vp->hash_block_size = cd->verity_hdr.hash_block_size;
2426         vp->data_size = cd->verity_hdr.data_size;
2427         vp->hash_area_offset = cd->verity_hdr.hash_area_offset;
2428         vp->hash_type = cd->verity_hdr.hash_type;
2429         vp->flags = cd->verity_hdr.flags & CRYPT_VERITY_NO_HEADER;
2430         return 0;
2431 }
2432
2433 int crypt_get_active_device(struct crypt_device *cd __attribute__((unused)),
2434                             const char *name,
2435                             struct crypt_active_device *cad)
2436 {
2437         struct crypt_dm_active_device dmd;
2438         int r;
2439
2440         r = dm_query_device(cd, name, 0, &dmd);
2441         if (r < 0)
2442                 return r;
2443
2444         if (dmd.target != DM_CRYPT && dmd.target != DM_VERITY)
2445                 return -ENOTSUP;
2446
2447         cad->offset     = dmd.u.crypt.offset;
2448         cad->iv_offset  = dmd.u.crypt.iv_offset;
2449         cad->size       = dmd.size;
2450         cad->flags      = dmd.flags;
2451
2452         return 0;
2453 }