Add verity uuid specification.
[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                 /* FIXME: allow plugins here? */
1145                 log_err(cd, _("Unknown crypt device type %s requested.\n"), type);
1146                 r = -EINVAL;
1147         }
1148
1149         if (!r && !(cd->type = strdup(type)))
1150                 r = -ENOMEM;
1151
1152         if (r < 0) {
1153                 crypt_free_volume_key(cd->volume_key);
1154                 cd->volume_key = NULL;
1155         }
1156
1157         return r;
1158 }
1159
1160 int crypt_load(struct crypt_device *cd,
1161                const char *requested_type,
1162                void *params)
1163 {
1164         int r;
1165
1166         log_dbg("Trying to load %s crypt type from device %s.",
1167                 requested_type ?: "any", mdata_device(cd) ?: "(none)");
1168
1169         if (!mdata_device(cd))
1170                 return -EINVAL;
1171
1172         if (!requested_type || isLUKS(requested_type)) {
1173                 if (cd->type && !isLUKS(cd->type)) {
1174                         log_dbg("Context is already initialised to type %s", cd->type);
1175                         return -EINVAL;
1176                 }
1177
1178                 r = _crypt_load_luks1(cd, 1, 0);
1179         } else if (isVERITY(requested_type)) {
1180                 if (cd->type && !isVERITY(cd->type)) {
1181                         log_dbg("Context is already initialised to type %s", cd->type);
1182                         return -EINVAL;
1183                 }
1184                 r = _crypt_load_verity(cd, params);
1185         } else
1186                 return -EINVAL;
1187
1188         if (r < 0)
1189                 return r;
1190
1191         /* cd->type and header must be set in context */
1192         r = crypt_check_data_device_size(cd);
1193         if (r < 0) {
1194                 free(cd->type);
1195                 cd->type = NULL;
1196         }
1197
1198         return r;
1199 }
1200
1201 int crypt_repair(struct crypt_device *cd,
1202                  const char *requested_type,
1203                  void *params __attribute__((unused)))
1204 {
1205         int r;
1206
1207         log_dbg("Trying to repair %s crypt type from device %s.",
1208                 requested_type ?: "any", mdata_device(cd) ?: "(none)");
1209
1210         if (!mdata_device(cd))
1211                 return -EINVAL;
1212
1213         if (requested_type && !isLUKS(requested_type))
1214                 return -EINVAL;
1215
1216
1217         /* Load with repair */
1218         r = _crypt_load_luks1(cd, 1, 1);
1219         if (r < 0)
1220                 return r;
1221
1222         /* cd->type and header must be set in context */
1223         r = crypt_check_data_device_size(cd);
1224         if (r < 0) {
1225                 free(cd->type);
1226                 cd->type = NULL;
1227         }
1228
1229         return r;
1230 }
1231
1232 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
1233 {
1234         struct crypt_dm_active_device dmd;
1235         int r;
1236
1237         /* Device context type must be initialised */
1238         if (!cd->type || !crypt_get_uuid(cd))
1239                 return -EINVAL;
1240
1241         log_dbg("Resizing device %s to %" PRIu64 " sectors.", name, new_size);
1242
1243         r = dm_query_device(name, DM_ACTIVE_DEVICE | DM_ACTIVE_CRYPT_CIPHER |
1244                                   DM_ACTIVE_UUID | DM_ACTIVE_CRYPT_KEYSIZE |
1245                                   DM_ACTIVE_CRYPT_KEY, &dmd);
1246         if (r < 0) {
1247                 log_err(NULL, _("Device %s is not active.\n"), name);
1248                 return -EINVAL;
1249         }
1250
1251         if (!dmd.uuid || dmd.target != DM_CRYPT) {
1252                 r = -EINVAL;
1253                 goto out;
1254         }
1255
1256         r = device_check_and_adjust(cd, dmd.data_device, DEV_OK, &new_size,
1257                                     &dmd.u.crypt.offset, &dmd.flags);
1258         if (r)
1259                 goto out;
1260
1261         if (new_size == dmd.size) {
1262                 log_dbg("Device has already requested size %" PRIu64
1263                         " sectors.", dmd.size);
1264                 r = 0;
1265         } else {
1266                 dmd.size = new_size;
1267                 r = dm_create_device(name, cd->type, &dmd, 1);
1268         }
1269 out:
1270         if (dmd.target == DM_CRYPT) {
1271                 crypt_free_volume_key(dmd.u.crypt.vk);
1272                 free(CONST_CAST(void*)dmd.u.crypt.cipher);
1273         }
1274         free(CONST_CAST(void*)dmd.data_device);
1275         free(CONST_CAST(void*)dmd.uuid);
1276
1277         return r;
1278 }
1279
1280 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
1281 {
1282         if (!isLUKS(cd->type)) {
1283                 log_err(cd, _("This operation is not supported for this device type.\n"));
1284                 return  -EINVAL;
1285         }
1286
1287         if (uuid && !strncmp(uuid, cd->hdr.uuid, sizeof(cd->hdr.uuid))) {
1288                 log_dbg("UUID is the same as requested (%s) for device %s.",
1289                         uuid, mdata_device(cd));
1290                 return 0;
1291         }
1292
1293         if (uuid)
1294                 log_dbg("Requested new UUID change to %s for %s.", uuid, mdata_device(cd));
1295         else
1296                 log_dbg("Requested new UUID refresh for %s.", mdata_device(cd));
1297
1298         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
1299                 return -EPERM;
1300
1301         return LUKS_hdr_uuid_set(mdata_device(cd), &cd->hdr, uuid, cd);
1302 }
1303
1304 int crypt_header_backup(struct crypt_device *cd,
1305                         const char *requested_type,
1306                         const char *backup_file)
1307 {
1308         int r;
1309
1310         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
1311                 return -EINVAL;
1312
1313         r = init_crypto(cd);
1314         if (r < 0)
1315                 return r;
1316
1317         log_dbg("Requested header backup of device %s (%s) to "
1318                 "file %s.", mdata_device(cd), requested_type, backup_file);
1319
1320         return LUKS_hdr_backup(backup_file, mdata_device(cd), &cd->hdr, cd);
1321 }
1322
1323 int crypt_header_restore(struct crypt_device *cd,
1324                          const char *requested_type,
1325                          const char *backup_file)
1326 {
1327         int r;
1328
1329         if (requested_type && !isLUKS(requested_type))
1330                 return -EINVAL;
1331
1332         r = init_crypto(cd);
1333         if (r < 0)
1334                 return r;
1335
1336         log_dbg("Requested header restore to device %s (%s) from "
1337                 "file %s.", mdata_device(cd), requested_type, backup_file);
1338
1339         return LUKS_hdr_restore(backup_file, mdata_device(cd), &cd->hdr, cd);
1340 }
1341
1342 void crypt_free(struct crypt_device *cd)
1343 {
1344         if (cd) {
1345                 log_dbg("Releasing crypt device %s context.", mdata_device(cd));
1346
1347                 if (cd->loop_fd != -1)
1348                         close(cd->loop_fd);
1349
1350                 dm_exit();
1351                 crypt_free_volume_key(cd->volume_key);
1352
1353                 free(cd->device);
1354                 free(cd->metadata_device);
1355                 free(cd->backing_file);
1356                 free(cd->type);
1357
1358                 /* used in plain device only */
1359                 free(CONST_CAST(void*)cd->plain_hdr.hash);
1360                 free(cd->plain_cipher);
1361                 free(cd->plain_cipher_mode);
1362                 free(cd->plain_uuid);
1363
1364                 /* used in loop-AES device only */
1365                 free(CONST_CAST(void*)cd->loopaes_hdr.hash);
1366                 free(cd->loopaes_cipher);
1367                 free(cd->loopaes_uuid);
1368
1369                 /* used in verity device only */
1370                 free(CONST_CAST(void*)cd->verity_hdr.hash_name);
1371                 free(CONST_CAST(void*)cd->verity_hdr.salt);
1372                 free(cd->verity_root_hash);
1373                 free(cd->verity_uuid);
1374
1375                 free(cd);
1376         }
1377 }
1378
1379 int crypt_suspend(struct crypt_device *cd,
1380                   const char *name)
1381 {
1382         crypt_status_info ci;
1383         int r;
1384
1385         log_dbg("Suspending volume %s.", name);
1386
1387         if (!isLUKS(cd->type)) {
1388                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1389                 r = -EINVAL;
1390                 goto out;
1391         }
1392
1393         ci = crypt_status(NULL, name);
1394         if (ci < CRYPT_ACTIVE) {
1395                 log_err(cd, _("Volume %s is not active.\n"), name);
1396                 return -EINVAL;
1397         }
1398
1399         if (!cd && dm_init(NULL, 1) < 0)
1400                 return -ENOSYS;
1401
1402         r = dm_status_suspended(name);
1403         if (r < 0)
1404                 goto out;
1405
1406         if (r) {
1407                 log_err(cd, _("Volume %s is already suspended.\n"), name);
1408                 r = -EINVAL;
1409                 goto out;
1410         }
1411
1412         r = dm_suspend_and_wipe_key(name);
1413         if (r == -ENOTSUP)
1414                 log_err(cd, "Suspend is not supported for device %s.\n", name);
1415         else if (r)
1416                 log_err(cd, "Error during suspending device %s.\n", name);
1417 out:
1418         if (!cd)
1419                 dm_exit();
1420         return r;
1421 }
1422
1423 int crypt_resume_by_passphrase(struct crypt_device *cd,
1424                                const char *name,
1425                                int keyslot,
1426                                const char *passphrase,
1427                                size_t passphrase_size)
1428 {
1429         struct volume_key *vk = NULL;
1430         int r;
1431
1432         log_dbg("Resuming volume %s.", name);
1433
1434         if (!isLUKS(cd->type)) {
1435                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1436                 r = -EINVAL;
1437                 goto out;
1438         }
1439
1440         r = dm_status_suspended(name);
1441         if (r < 0)
1442                 return r;
1443
1444         if (!r) {
1445                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1446                 return -EINVAL;
1447         }
1448
1449         if (passphrase) {
1450                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
1451                                            passphrase_size, &cd->hdr, &vk, cd);
1452         } else
1453                 r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1454
1455         if (r >= 0) {
1456                 keyslot = r;
1457                 r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1458                 if (r == -ENOTSUP)
1459                         log_err(cd, "Resume is not supported for device %s.\n", name);
1460                 else if (r)
1461                         log_err(cd, "Error during resuming device %s.\n", name);
1462         } else
1463                 r = keyslot;
1464 out:
1465         crypt_free_volume_key(vk);
1466         return r < 0 ? r : keyslot;
1467 }
1468
1469 int crypt_resume_by_keyfile_offset(struct crypt_device *cd,
1470                                    const char *name,
1471                                    int keyslot,
1472                                    const char *keyfile,
1473                                    size_t keyfile_size,
1474                                    size_t keyfile_offset)
1475 {
1476         struct volume_key *vk = NULL;
1477         char *passphrase_read = NULL;
1478         size_t passphrase_size_read;
1479         int r;
1480
1481         log_dbg("Resuming volume %s.", name);
1482
1483         if (!isLUKS(cd->type)) {
1484                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1485                 r = -EINVAL;
1486                 goto out;
1487         }
1488
1489         r = dm_status_suspended(name);
1490         if (r < 0)
1491                 return r;
1492
1493         if (!r) {
1494                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1495                 return -EINVAL;
1496         }
1497
1498         if (!keyfile)
1499                 return -EINVAL;
1500
1501         r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1502                           &passphrase_size_read, keyfile, keyfile_offset,
1503                           keyfile_size);
1504         if (r < 0)
1505                 goto out;
1506
1507         r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase_read,
1508                                    passphrase_size_read, &cd->hdr, &vk, cd);
1509         if (r < 0)
1510                 goto out;
1511
1512         keyslot = r;
1513         r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1514         if (r)
1515                 log_err(cd, "Error during resuming device %s.\n", name);
1516 out:
1517         crypt_safe_free(passphrase_read);
1518         crypt_free_volume_key(vk);
1519         return r < 0 ? r : keyslot;
1520 }
1521
1522 int crypt_resume_by_keyfile(struct crypt_device *cd,
1523                             const char *name,
1524                             int keyslot,
1525                             const char *keyfile,
1526                             size_t keyfile_size)
1527 {
1528         return crypt_resume_by_keyfile_offset(cd, name, keyslot,
1529                                               keyfile, keyfile_size, 0);
1530 }
1531
1532 // slot manipulation
1533 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1534         int keyslot, // -1 any
1535         const char *passphrase, // NULL -> terminal
1536         size_t passphrase_size,
1537         const char *new_passphrase, // NULL -> terminal
1538         size_t new_passphrase_size)
1539 {
1540         struct volume_key *vk = NULL;
1541         char *password = NULL, *new_password = NULL;
1542         size_t passwordLen, new_passwordLen;
1543         int r;
1544
1545         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1546                 "new passphrase %sprovided.",
1547                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1548
1549         if (!isLUKS(cd->type)) {
1550                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1551                 return -EINVAL;
1552         }
1553
1554         r = keyslot_verify_or_find_empty(cd, &keyslot);
1555         if (r)
1556                 return r;
1557
1558         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1559                 /* No slots used, try to use pre-generated key in header */
1560                 if (cd->volume_key) {
1561                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1562                         r = vk ? 0 : -ENOMEM;
1563                 } else {
1564                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1565                         return -EINVAL;
1566                 }
1567         } else if (passphrase) {
1568                 /* Passphrase provided, use it to unlock existing keyslot */
1569                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, passphrase,
1570                                            passphrase_size, &cd->hdr, &vk, cd);
1571         } else {
1572                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1573                 r = key_from_terminal(cd, _("Enter any passphrase: "),
1574                                       &password, &passwordLen, 0);
1575                 if (r < 0)
1576                         goto out;
1577
1578                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, password,
1579                                            passwordLen, &cd->hdr, &vk, cd);
1580                 crypt_safe_free(password);
1581         }
1582
1583         if(r < 0)
1584                 goto out;
1585
1586         if (new_passphrase) {
1587                 new_password = CONST_CAST(char*)new_passphrase;
1588                 new_passwordLen = new_passphrase_size;
1589         } else {
1590                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1591                                       &new_password, &new_passwordLen, 1);
1592                 if(r < 0)
1593                         goto out;
1594         }
1595
1596         r = LUKS_set_key(mdata_device(cd), keyslot, new_password, new_passwordLen,
1597                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1598         if(r < 0) goto out;
1599
1600         r = 0;
1601 out:
1602         if (!new_passphrase)
1603                 crypt_safe_free(new_password);
1604         crypt_free_volume_key(vk);
1605         return r ?: keyslot;
1606 }
1607
1608 int crypt_keyslot_add_by_keyfile_offset(struct crypt_device *cd,
1609         int keyslot,
1610         const char *keyfile,
1611         size_t keyfile_size,
1612         size_t keyfile_offset,
1613         const char *new_keyfile,
1614         size_t new_keyfile_size,
1615         size_t new_keyfile_offset)
1616 {
1617         struct volume_key *vk = NULL;
1618         char *password = NULL; size_t passwordLen;
1619         char *new_password = NULL; size_t new_passwordLen;
1620         int r;
1621
1622         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1623                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1624
1625         if (!isLUKS(cd->type)) {
1626                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1627                 return -EINVAL;
1628         }
1629
1630         r = keyslot_verify_or_find_empty(cd, &keyslot);
1631         if (r)
1632                 return r;
1633
1634         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1635                 /* No slots used, try to use pre-generated key in header */
1636                 if (cd->volume_key) {
1637                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1638                         r = vk ? 0 : -ENOMEM;
1639                 } else {
1640                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1641                         return -EINVAL;
1642                 }
1643         } else {
1644                 /* Read password from file of (if NULL) from terminal */
1645                 if (keyfile)
1646                         r = key_from_file(cd, _("Enter any passphrase: "),
1647                                           &password, &passwordLen,
1648                                           keyfile, keyfile_offset, keyfile_size);
1649                 else
1650                         r = key_from_terminal(cd, _("Enter any passphrase: "),
1651                                               &password, &passwordLen, 0);
1652                 if (r < 0)
1653                         goto out;
1654
1655                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, password, passwordLen,
1656                                            &cd->hdr, &vk, cd);
1657         }
1658
1659         if(r < 0)
1660                 goto out;
1661
1662         if (new_keyfile)
1663                 r = key_from_file(cd, _("Enter new passphrase for key slot: "),
1664                                   &new_password, &new_passwordLen, new_keyfile,
1665                                   new_keyfile_offset, new_keyfile_size);
1666         else
1667                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1668                                       &new_password, &new_passwordLen, 1);
1669         if (r < 0)
1670                 goto out;
1671
1672         r = LUKS_set_key(mdata_device(cd), keyslot, new_password, new_passwordLen,
1673                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1674 out:
1675         crypt_safe_free(password);
1676         crypt_safe_free(new_password);
1677         crypt_free_volume_key(vk);
1678         return r < 0 ? r : keyslot;
1679 }
1680
1681 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1682         int keyslot,
1683         const char *keyfile,
1684         size_t keyfile_size,
1685         const char *new_keyfile,
1686         size_t new_keyfile_size)
1687 {
1688         return crypt_keyslot_add_by_keyfile_offset(cd, keyslot,
1689                                 keyfile, keyfile_size, 0,
1690                                 new_keyfile, new_keyfile_size, 0);
1691 }
1692
1693 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1694         int keyslot,
1695         const char *volume_key,
1696         size_t volume_key_size,
1697         const char *passphrase,
1698         size_t passphrase_size)
1699 {
1700         struct volume_key *vk = NULL;
1701         int r = -EINVAL;
1702         char *new_password = NULL; size_t new_passwordLen;
1703
1704         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1705
1706         if (!isLUKS(cd->type)) {
1707                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1708                 return -EINVAL;
1709         }
1710
1711         if (volume_key)
1712                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1713         else if (cd->volume_key)
1714                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1715
1716         if (!vk)
1717                 return -ENOMEM;
1718
1719         r = LUKS_verify_volume_key(&cd->hdr, vk);
1720         if (r < 0) {
1721                 log_err(cd, _("Volume key does not match the volume.\n"));
1722                 goto out;
1723         }
1724
1725         r = keyslot_verify_or_find_empty(cd, &keyslot);
1726         if (r)
1727                 goto out;
1728
1729         if (!passphrase) {
1730                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1731                                       &new_password, &new_passwordLen, 1);
1732                 if (r < 0)
1733                         goto out;
1734                 passphrase = new_password;
1735                 passphrase_size = new_passwordLen;
1736         }
1737
1738         r = LUKS_set_key(mdata_device(cd), keyslot, passphrase, passphrase_size,
1739                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1740 out:
1741         crypt_safe_free(new_password);
1742         crypt_free_volume_key(vk);
1743         return (r < 0) ? r : keyslot;
1744 }
1745
1746 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1747 {
1748         crypt_keyslot_info ki;
1749
1750         log_dbg("Destroying keyslot %d.", keyslot);
1751
1752         if (!isLUKS(cd->type)) {
1753                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1754                 return -EINVAL;
1755         }
1756
1757         ki = crypt_keyslot_status(cd, keyslot);
1758         if (ki == CRYPT_SLOT_INVALID) {
1759                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1760                 return -EINVAL;
1761         }
1762
1763         if (ki == CRYPT_SLOT_INACTIVE) {
1764                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1765                 return -EINVAL;
1766         }
1767
1768         return LUKS_del_key(mdata_device(cd), keyslot, &cd->hdr, cd);
1769 }
1770
1771 // activation/deactivation of device mapping
1772 int crypt_activate_by_passphrase(struct crypt_device *cd,
1773         const char *name,
1774         int keyslot,
1775         const char *passphrase,
1776         size_t passphrase_size,
1777         uint32_t flags)
1778 {
1779         crypt_status_info ci;
1780         struct volume_key *vk = NULL;
1781         char *read_passphrase = NULL;
1782         size_t passphraseLen = 0;
1783         int r;
1784
1785         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1786                 name ? "Activating" : "Checking", name ?: "",
1787                 keyslot, passphrase ? "" : "[none] ");
1788
1789         if (name) {
1790                 ci = crypt_status(NULL, name);
1791                 if (ci == CRYPT_INVALID)
1792                         return -EINVAL;
1793                 else if (ci >= CRYPT_ACTIVE) {
1794                         log_err(cd, _("Device %s already exists.\n"), name);
1795                         return -EEXIST;
1796                 }
1797         }
1798
1799         /* plain, use hashed passphrase */
1800         if (isPLAIN(cd->type)) {
1801                 if (!name)
1802                         return -EINVAL;
1803
1804                 if (!passphrase) {
1805                         r = key_from_terminal(cd, NULL, &read_passphrase,
1806                                               &passphraseLen, 0);
1807                         if (r < 0)
1808                                 goto out;
1809                         passphrase = read_passphrase;
1810                         passphrase_size = passphraseLen;
1811                 }
1812
1813                 r = process_key(cd, cd->plain_hdr.hash,
1814                                 cd->plain_key_size,
1815                                 passphrase, passphrase_size, &vk);
1816                 if (r < 0)
1817                         goto out;
1818
1819                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1820                 keyslot = 0;
1821         } else if (isLUKS(cd->type)) {
1822                 /* provided passphrase, do not retry */
1823                 if (passphrase) {
1824                         r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
1825                                                    passphrase_size, &cd->hdr, &vk, cd);
1826                 } else
1827                         r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1828
1829                 if (r >= 0) {
1830                         keyslot = r;
1831                         if (name)
1832                                 r = LUKS1_activate(cd, name, vk, flags);
1833                 }
1834         } else
1835                 r = -EINVAL;
1836 out:
1837         crypt_safe_free(read_passphrase);
1838         crypt_free_volume_key(vk);
1839
1840         return r < 0  ? r : keyslot;
1841 }
1842
1843 int crypt_activate_by_keyfile_offset(struct crypt_device *cd,
1844         const char *name,
1845         int keyslot,
1846         const char *keyfile,
1847         size_t keyfile_size,
1848         size_t keyfile_offset,
1849         uint32_t flags)
1850 {
1851         crypt_status_info ci;
1852         struct volume_key *vk = NULL;
1853         char *passphrase_read = NULL;
1854         size_t passphrase_size_read;
1855         unsigned int key_count = 0;
1856         int r;
1857
1858         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1859                 name ?: "", keyslot, keyfile ?: "[none]");
1860
1861         if (name) {
1862                 ci = crypt_status(NULL, name);
1863                 if (ci == CRYPT_INVALID)
1864                         return -EINVAL;
1865                 else if (ci >= CRYPT_ACTIVE) {
1866                         log_err(cd, _("Device %s already exists.\n"), name);
1867                         return -EEXIST;
1868                 }
1869         }
1870
1871         if (!keyfile)
1872                 return -EINVAL;
1873
1874         if (isPLAIN(cd->type)) {
1875                 if (!name)
1876                         return -EINVAL;
1877
1878                 r = key_from_file(cd, _("Enter passphrase: "),
1879                                   &passphrase_read, &passphrase_size_read,
1880                                   keyfile, keyfile_offset, keyfile_size);
1881                 if (r < 0)
1882                         goto out;
1883
1884                 r = process_key(cd, cd->plain_hdr.hash,
1885                                 cd->plain_key_size,
1886                                 passphrase_read, passphrase_size_read, &vk);
1887                 if (r < 0)
1888                         goto out;
1889
1890                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1891         } else if (isLUKS(cd->type)) {
1892                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1893                           &passphrase_size_read, keyfile, keyfile_offset, keyfile_size);
1894                 if (r < 0)
1895                         goto out;
1896                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase_read,
1897                                            passphrase_size_read, &cd->hdr, &vk, cd);
1898                 if (r < 0)
1899                         goto out;
1900                 keyslot = r;
1901
1902                 if (name) {
1903                         r = LUKS1_activate(cd, name, vk, flags);
1904                         if (r < 0)
1905                                 goto out;
1906                 }
1907                 r = keyslot;
1908         } else if (isLOOPAES(cd->type)) {
1909                 r = key_from_file(cd, NULL, &passphrase_read, &passphrase_size_read,
1910                                   keyfile, keyfile_offset, keyfile_size);
1911                 if (r < 0)
1912                         goto out;
1913                 r = LOOPAES_parse_keyfile(cd, &vk, cd->loopaes_hdr.hash, &key_count,
1914                                           passphrase_read, passphrase_size_read);
1915                 if (r < 0)
1916                         goto out;
1917                 if (name)
1918                         r = LOOPAES_activate(cd, name, cd->loopaes_cipher,
1919                                              key_count, vk, flags);
1920         } else
1921                 r = -EINVAL;
1922
1923 out:
1924         crypt_safe_free(passphrase_read);
1925         crypt_free_volume_key(vk);
1926
1927         return r;
1928 }
1929
1930 int crypt_activate_by_keyfile(struct crypt_device *cd,
1931         const char *name,
1932         int keyslot,
1933         const char *keyfile,
1934         size_t keyfile_size,
1935         uint32_t flags)
1936 {
1937         return crypt_activate_by_keyfile_offset(cd, name, keyslot, keyfile,
1938                                                 keyfile_size, 0, flags);
1939 }
1940
1941 int crypt_activate_by_volume_key(struct crypt_device *cd,
1942         const char *name,
1943         const char *volume_key,
1944         size_t volume_key_size,
1945         uint32_t flags)
1946 {
1947         crypt_status_info ci;
1948         struct volume_key *vk = NULL;
1949         int r = -EINVAL;
1950
1951         log_dbg("Activating volume %s by volume key.", name ?: "[none]");
1952
1953         if (name) {
1954                 ci = crypt_status(NULL, name);
1955                 if (ci == CRYPT_INVALID)
1956                         return -EINVAL;
1957                 else if (ci >= CRYPT_ACTIVE) {
1958                         log_err(cd, _("Device %s already exists.\n"), name);
1959                         return -EEXIST;
1960                 }
1961         }
1962
1963         /* use key directly, no hash */
1964         if (isPLAIN(cd->type)) {
1965                 if (!name)
1966                         return -EINVAL;
1967
1968                 if (!volume_key || !volume_key_size || volume_key_size != cd->plain_key_size) {
1969                         log_err(cd, _("Incorrect volume key specified for plain device.\n"));
1970                         return -EINVAL;
1971                 }
1972
1973                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1974                 if (!vk)
1975                         return -ENOMEM;
1976
1977                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1978         } else if (isLUKS(cd->type)) {
1979                 /* If key is not provided, try to use internal key */
1980                 if (!volume_key) {
1981                         if (!cd->volume_key) {
1982                                 log_err(cd, _("Volume key does not match the volume.\n"));
1983                                 return -EINVAL;
1984                         }
1985                         volume_key_size = cd->volume_key->keylength;
1986                         volume_key = cd->volume_key->key;
1987                 }
1988
1989                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1990                 if (!vk)
1991                         return -ENOMEM;
1992                 r = LUKS_verify_volume_key(&cd->hdr, vk);
1993
1994                 if (r == -EPERM)
1995                         log_err(cd, _("Volume key does not match the volume.\n"));
1996
1997                 if (!r && name)
1998                         r = LUKS1_activate(cd, name, vk, flags);
1999         } else if (isVERITY(cd->type)) {
2000                 /* volume_key == root hash */
2001                 if (!volume_key || !volume_key_size) {
2002                         log_err(cd, _("Incorrect root hash specified for verity device.\n"));
2003                         return -EINVAL;
2004                 }
2005
2006                 r = VERITY_activate(cd, name, mdata_device(cd),
2007                                     volume_key, volume_key_size,
2008                                     &cd->verity_hdr, CRYPT_ACTIVATE_READONLY);
2009
2010                 if (r == -EPERM) {
2011                         free(cd->verity_root_hash);
2012                         cd->verity_root_hash = NULL;
2013                 } if (!r) {
2014                         cd->verity_root_hash_size = volume_key_size;
2015                         if (!cd->verity_root_hash)
2016                                 cd->verity_root_hash = malloc(volume_key_size);
2017                         if (cd->verity_root_hash)
2018                                 memcpy(cd->verity_root_hash, volume_key, volume_key_size);
2019                 }
2020         } else
2021                 log_err(cd, _("Device type is not properly initialised.\n"));
2022
2023         crypt_free_volume_key(vk);
2024
2025         return r;
2026 }
2027
2028 int crypt_deactivate(struct crypt_device *cd, const char *name)
2029 {
2030         int r;
2031
2032         if (!name)
2033                 return -EINVAL;
2034
2035         log_dbg("Deactivating volume %s.", name);
2036
2037         if (!cd && dm_init(NULL, 1) < 0)
2038                 return -ENOSYS;
2039
2040         switch (crypt_status(cd, name)) {
2041                 case CRYPT_ACTIVE:
2042                 case CRYPT_BUSY:
2043                         r = dm_remove_device(name, 0, 0);
2044                         break;
2045                 case CRYPT_INACTIVE:
2046                         log_err(cd, _("Device %s is not active.\n"), name);
2047                         r = -ENODEV;
2048                         break;
2049                 default:
2050                         log_err(cd, _("Invalid device %s.\n"), name);
2051                         r = -EINVAL;
2052         }
2053
2054         if (!cd)
2055                 dm_exit();
2056
2057         return r;
2058 }
2059
2060 int crypt_volume_key_get(struct crypt_device *cd,
2061         int keyslot,
2062         char *volume_key,
2063         size_t *volume_key_size,
2064         const char *passphrase,
2065         size_t passphrase_size)
2066 {
2067         struct volume_key *vk = NULL;
2068         unsigned key_len;
2069         int r = -EINVAL;
2070
2071         if (crypt_fips_mode()) {
2072                 log_err(cd, "Function not available in FIPS mode.\n");
2073                 return -EACCES;
2074         }
2075
2076         key_len = crypt_get_volume_key_size(cd);
2077         if (key_len > *volume_key_size) {
2078                 log_err(cd, _("Volume key buffer too small.\n"));
2079                 return -ENOMEM;
2080         }
2081
2082         if (isPLAIN(cd->type) && cd->plain_hdr.hash) {
2083                 r = process_key(cd, cd->plain_hdr.hash, key_len,
2084                                 passphrase, passphrase_size, &vk);
2085                 if (r < 0)
2086                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
2087         } else if (isLUKS(cd->type)) {
2088                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
2089                                         passphrase_size, &cd->hdr, &vk, cd);
2090
2091         } else
2092                 log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
2093
2094         if (r >= 0) {
2095                 memcpy(volume_key, vk->key, vk->keylength);
2096                 *volume_key_size = vk->keylength;
2097         }
2098
2099         crypt_free_volume_key(vk);
2100         return r;
2101 }
2102
2103 int crypt_volume_key_verify(struct crypt_device *cd,
2104         const char *volume_key,
2105         size_t volume_key_size)
2106 {
2107         struct volume_key *vk;
2108         int r;
2109
2110         if (!isLUKS(cd->type)) {
2111                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2112                 return -EINVAL;
2113         }
2114
2115         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2116         if (!vk)
2117                 return -ENOMEM;
2118
2119         r = LUKS_verify_volume_key(&cd->hdr, vk);
2120
2121         if (r == -EPERM)
2122                 log_err(cd, _("Volume key does not match the volume.\n"));
2123
2124         crypt_free_volume_key(vk);
2125
2126         return r;
2127 }
2128
2129 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
2130 {
2131         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
2132         cd->timeout = timeout_sec;
2133 }
2134
2135 void crypt_set_password_retry(struct crypt_device *cd, int tries)
2136 {
2137         log_dbg("Password retry count set to %d.", tries);
2138         cd->tries = tries;
2139 }
2140
2141 void crypt_set_iteration_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2142 {
2143         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
2144         cd->iteration_time = iteration_time_ms;
2145 }
2146 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2147 {
2148         crypt_set_iteration_time(cd, iteration_time_ms);
2149 }
2150
2151 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
2152 {
2153         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
2154         cd->password_verify = password_verify ? 1 : 0;
2155 }
2156
2157 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
2158 {
2159         switch (rng_type) {
2160         case CRYPT_RNG_URANDOM:
2161         case CRYPT_RNG_RANDOM:
2162                 log_dbg("RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
2163                 cd->rng_type = rng_type;
2164         }
2165 }
2166
2167 int crypt_get_rng_type(struct crypt_device *cd)
2168 {
2169         if (!cd)
2170                 return -EINVAL;
2171
2172         return cd->rng_type;
2173 }
2174
2175 int crypt_memory_lock(struct crypt_device *cd, int lock)
2176 {
2177         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
2178 }
2179
2180 // reporting
2181 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
2182 {
2183         int r;
2184
2185         if (!cd && dm_init(NULL, 1) < 0)
2186                 return CRYPT_INVALID;
2187
2188         r = dm_status_device(name);
2189
2190         if (!cd)
2191                 dm_exit();
2192
2193         if (r < 0 && r != -ENODEV)
2194                 return CRYPT_INVALID;
2195
2196         if (r == 0)
2197                 return CRYPT_ACTIVE;
2198
2199         if (r > 0)
2200                 return CRYPT_BUSY;
2201
2202         return CRYPT_INACTIVE;
2203 }
2204
2205 static void hexprint(struct crypt_device *cd, const char *d, int n, const char *sep)
2206 {
2207         int i;
2208         for(i = 0; i < n; i++)
2209                 log_std(cd, "%02hhx%s", (const char)d[i], sep);
2210 }
2211
2212 static int _luks_dump(struct crypt_device *cd)
2213 {
2214         int i;
2215
2216         log_std(cd, "LUKS header information for %s\n\n", mdata_device(cd));
2217         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
2218         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
2219         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
2220         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
2221         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
2222         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
2223         log_std(cd, "MK digest:     \t");
2224         hexprint(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE, " ");
2225         log_std(cd, "\n");
2226         log_std(cd, "MK salt:       \t");
2227         hexprint(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2, " ");
2228         log_std(cd, "\n               \t");
2229         hexprint(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
2230         log_std(cd, "\n");
2231         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
2232         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
2233         for(i = 0; i < LUKS_NUMKEYS; i++) {
2234                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
2235                         log_std(cd, "Key Slot %d: ENABLED\n",i);
2236                         log_std(cd, "\tIterations:         \t%d\n",
2237                                 cd->hdr.keyblock[i].passwordIterations);
2238                         log_std(cd, "\tSalt:               \t");
2239                         hexprint(cd, cd->hdr.keyblock[i].passwordSalt,
2240                                  LUKS_SALTSIZE/2, " ");
2241                         log_std(cd, "\n\t                      \t");
2242                         hexprint(cd, cd->hdr.keyblock[i].passwordSalt +
2243                                  LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
2244                         log_std(cd, "\n");
2245
2246                         log_std(cd, "\tKey material offset:\t%d\n",
2247                                 cd->hdr.keyblock[i].keyMaterialOffset);
2248                         log_std(cd, "\tAF stripes:            \t%d\n",
2249                                 cd->hdr.keyblock[i].stripes);
2250                 }
2251                 else 
2252                         log_std(cd, "Key Slot %d: DISABLED\n", i);
2253         }
2254         return 0;
2255 }
2256
2257 static int _verity_dump(struct crypt_device *cd)
2258 {
2259         log_std(cd, "VERITY header information for %s\n", mdata_device(cd));
2260         log_std(cd, "UUID:            \t%s\n", cd->verity_uuid ?: "");
2261         log_std(cd, "Hash type:       \t%u\n", cd->verity_hdr.hash_type);
2262         log_std(cd, "Data blocks:     \t%" PRIu64 "\n", cd->verity_hdr.data_size);
2263         log_std(cd, "Data block size: \t%u\n", cd->verity_hdr.data_block_size);
2264         log_std(cd, "Hash block size: \t%u\n", cd->verity_hdr.hash_block_size);
2265         log_std(cd, "Hash algorithm:  \t%s\n", cd->verity_hdr.hash_name);
2266         log_std(cd, "Salt:            \t");
2267         if (cd->verity_hdr.salt_size)
2268                 hexprint(cd, cd->verity_hdr.salt, cd->verity_hdr.salt_size, "");
2269         else
2270                 log_std(cd, "-");
2271         log_std(cd, "\n");
2272         if (cd->verity_root_hash) {
2273                 log_std(cd, "Root hash:      \t");
2274                 hexprint(cd, cd->verity_root_hash, cd->verity_root_hash_size, "");
2275                 log_std(cd, "\n");
2276         }
2277         return 0;
2278 }
2279
2280 int crypt_dump(struct crypt_device *cd)
2281 {
2282         if (isLUKS(cd->type))
2283                 return _luks_dump(cd);
2284         else if (isVERITY(cd->type))
2285                 return _verity_dump(cd);
2286
2287         log_err(cd, _("Dump operation is not supported for this device type.\n"));
2288         return -EINVAL;
2289 }
2290
2291 const char *crypt_get_cipher(struct crypt_device *cd)
2292 {
2293         if (isPLAIN(cd->type))
2294                 return cd->plain_cipher;
2295
2296         if (isLUKS(cd->type))
2297                 return cd->hdr.cipherName;
2298
2299         if (isLOOPAES(cd->type))
2300                 return cd->loopaes_cipher;
2301
2302         return NULL;
2303 }
2304
2305 const char *crypt_get_cipher_mode(struct crypt_device *cd)
2306 {
2307         if (isPLAIN(cd->type))
2308                 return cd->plain_cipher_mode;
2309
2310         if (isLUKS(cd->type))
2311                 return cd->hdr.cipherMode;
2312
2313         if (isLOOPAES(cd->type))
2314                 return cd->loopaes_cipher_mode;
2315
2316         return NULL;
2317 }
2318
2319 const char *crypt_get_uuid(struct crypt_device *cd)
2320 {
2321         if (isLUKS(cd->type))
2322                 return cd->hdr.uuid;
2323
2324         if (isPLAIN(cd->type))
2325                 return cd->plain_uuid;
2326
2327         if (isLOOPAES(cd->type))
2328                 return cd->loopaes_uuid;
2329
2330         if (isVERITY(cd->type))
2331                 return cd->verity_uuid;
2332
2333         return NULL;
2334 }
2335
2336 const char *crypt_get_device_name(struct crypt_device *cd)
2337 {
2338         return cd->device;
2339 }
2340
2341 int crypt_get_volume_key_size(struct crypt_device *cd)
2342 {
2343         if (isPLAIN(cd->type))
2344                 return cd->plain_key_size;
2345
2346         if (isLUKS(cd->type))
2347                 return cd->hdr.keyBytes;
2348
2349         if (isLOOPAES(cd->type))
2350                 return cd->loopaes_key_size;
2351
2352         if (isVERITY(cd->type))
2353                 return cd->verity_root_hash_size;
2354
2355         return 0;
2356 }
2357
2358 uint64_t crypt_get_data_offset(struct crypt_device *cd)
2359 {
2360         if (isPLAIN(cd->type))
2361                 return cd->plain_hdr.offset;
2362
2363         if (isLUKS(cd->type))
2364                 return cd->hdr.payloadOffset;
2365
2366         if (isLOOPAES(cd->type))
2367                 return cd->loopaes_hdr.offset;
2368
2369         return 0;
2370 }
2371
2372 uint64_t crypt_get_iv_offset(struct crypt_device *cd)
2373 {
2374         if (isPLAIN(cd->type))
2375                 return cd->plain_hdr.skip;
2376
2377         if (isLUKS(cd->type))
2378                 return 0;
2379
2380         if (isLOOPAES(cd->type))
2381                 return cd->loopaes_hdr.skip;
2382
2383         return 0;
2384 }
2385
2386 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
2387 {
2388         if (!isLUKS(cd->type)) {
2389                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2390                 return CRYPT_SLOT_INVALID;
2391         }
2392
2393         return LUKS_keyslot_info(&cd->hdr, keyslot);
2394 }
2395
2396 int crypt_keyslot_max(const char *type)
2397 {
2398         if (type && isLUKS(type))
2399                 return LUKS_NUMKEYS;
2400
2401         return -EINVAL;
2402 }
2403
2404 const char *crypt_get_type(struct crypt_device *cd)
2405 {
2406         return cd->type;
2407 }
2408
2409 int crypt_get_verity_info(struct crypt_device *cd,
2410         struct crypt_params_verity *vp)
2411 {
2412         if (!isVERITY(cd->type) || !vp)
2413                 return -EINVAL;
2414
2415         vp->data_device = cd->device;
2416         vp->hash_device = mdata_device(cd);
2417         vp->hash_name = cd->verity_hdr.hash_name;
2418         vp->salt = cd->verity_hdr.salt;
2419         vp->salt_size = cd->verity_hdr.salt_size;
2420         vp->data_block_size = cd->verity_hdr.data_block_size;
2421         vp->hash_block_size = cd->verity_hdr.hash_block_size;
2422         vp->data_size = cd->verity_hdr.data_size;
2423         vp->hash_area_offset = cd->verity_hdr.hash_area_offset;
2424         vp->hash_type = cd->verity_hdr.hash_type;
2425         vp->flags = cd->verity_hdr.flags & CRYPT_VERITY_NO_HEADER;
2426         return 0;
2427 }
2428
2429 int crypt_get_active_device(struct crypt_device *cd __attribute__((unused)),
2430                             const char *name,
2431                             struct crypt_active_device *cad)
2432 {
2433         struct crypt_dm_active_device dmd;
2434         int r;
2435
2436         r = dm_query_device(name, 0, &dmd);
2437         if (r < 0)
2438                 return r;
2439
2440         if (dmd.target != DM_CRYPT && dmd.target != DM_VERITY)
2441                 return -ENOTSUP;
2442
2443         cad->offset     = dmd.u.crypt.offset;
2444         cad->iv_offset  = dmd.u.crypt.iv_offset;
2445         cad->size       = dmd.size;
2446         cad->flags      = dmd.flags;
2447
2448         return 0;
2449 }