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