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