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