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