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