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