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