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