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