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