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