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