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