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