Merge branch 'reenc' of https://code.google.com/p/cryptsetup into reenc
[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, _("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         return r;
1228 }
1229
1230 int crypt_repair(struct crypt_device *cd,
1231                  const char *requested_type,
1232                  void *params __attribute__((unused)))
1233 {
1234         int r;
1235
1236         log_dbg("Trying to repair %s crypt type from device %s.",
1237                 requested_type ?: "any", mdata_device(cd) ?: "(none)");
1238
1239         if (!mdata_device(cd))
1240                 return -EINVAL;
1241
1242         if (requested_type && !isLUKS(requested_type))
1243                 return -EINVAL;
1244
1245
1246         /* Load with repair */
1247         r = _crypt_load_luks1(cd, 1, 1);
1248         if (r < 0)
1249                 return r;
1250
1251         /* cd->type and header must be set in context */
1252         r = crypt_check_data_device_size(cd);
1253         if (r < 0) {
1254                 free(cd->type);
1255                 cd->type = NULL;
1256         }
1257
1258         return r;
1259 }
1260
1261 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
1262 {
1263         struct crypt_dm_active_device dmd;
1264         int r;
1265
1266         /* Device context type must be initialised */
1267         if (!cd->type || !crypt_get_uuid(cd))
1268                 return -EINVAL;
1269
1270         log_dbg("Resizing device %s to %" PRIu64 " sectors.", name, new_size);
1271
1272         r = dm_query_device(name, DM_ACTIVE_DEVICE | DM_ACTIVE_CRYPT_CIPHER |
1273                                   DM_ACTIVE_UUID | DM_ACTIVE_CRYPT_KEYSIZE |
1274                                   DM_ACTIVE_CRYPT_KEY, &dmd);
1275         if (r < 0) {
1276                 log_err(NULL, _("Device %s is not active.\n"), name);
1277                 return -EINVAL;
1278         }
1279
1280         if (!dmd.uuid || dmd.target != DM_CRYPT) {
1281                 r = -EINVAL;
1282                 goto out;
1283         }
1284
1285         r = device_check_and_adjust(cd, dmd.data_device, DEV_OK, &new_size,
1286                                     &dmd.u.crypt.offset, &dmd.flags);
1287         if (r)
1288                 goto out;
1289
1290         if (new_size == dmd.size) {
1291                 log_dbg("Device has already requested size %" PRIu64
1292                         " sectors.", dmd.size);
1293                 r = 0;
1294         } else {
1295                 dmd.size = new_size;
1296                 r = dm_create_device(name, cd->type, &dmd, 1);
1297         }
1298 out:
1299         if (dmd.target == DM_CRYPT) {
1300                 crypt_free_volume_key(dmd.u.crypt.vk);
1301                 free(CONST_CAST(void*)dmd.u.crypt.cipher);
1302         }
1303         free(CONST_CAST(void*)dmd.data_device);
1304         free(CONST_CAST(void*)dmd.uuid);
1305
1306         return r;
1307 }
1308
1309 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
1310 {
1311         if (!isLUKS(cd->type)) {
1312                 log_err(cd, _("This operation is not supported for this device type.\n"));
1313                 return  -EINVAL;
1314         }
1315
1316         if (uuid && !strncmp(uuid, cd->hdr.uuid, sizeof(cd->hdr.uuid))) {
1317                 log_dbg("UUID is the same as requested (%s) for device %s.",
1318                         uuid, mdata_device(cd));
1319                 return 0;
1320         }
1321
1322         if (uuid)
1323                 log_dbg("Requested new UUID change to %s for %s.", uuid, mdata_device(cd));
1324         else
1325                 log_dbg("Requested new UUID refresh for %s.", mdata_device(cd));
1326
1327         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
1328                 return -EPERM;
1329
1330         return LUKS_hdr_uuid_set(mdata_device(cd), &cd->hdr, uuid, cd);
1331 }
1332
1333 int crypt_header_backup(struct crypt_device *cd,
1334                         const char *requested_type,
1335                         const char *backup_file)
1336 {
1337         int r;
1338
1339         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
1340                 return -EINVAL;
1341
1342         r = init_crypto(cd);
1343         if (r < 0)
1344                 return r;
1345
1346         log_dbg("Requested header backup of device %s (%s) to "
1347                 "file %s.", mdata_device(cd), requested_type, backup_file);
1348
1349         return LUKS_hdr_backup(backup_file, mdata_device(cd), &cd->hdr, cd);
1350 }
1351
1352 int crypt_header_restore(struct crypt_device *cd,
1353                          const char *requested_type,
1354                          const char *backup_file)
1355 {
1356         int r;
1357
1358         if (requested_type && !isLUKS(requested_type))
1359                 return -EINVAL;
1360
1361         r = init_crypto(cd);
1362         if (r < 0)
1363                 return r;
1364
1365         log_dbg("Requested header restore to device %s (%s) from "
1366                 "file %s.", mdata_device(cd), requested_type, backup_file);
1367
1368         return LUKS_hdr_restore(backup_file, mdata_device(cd), &cd->hdr, cd);
1369 }
1370
1371 void crypt_free(struct crypt_device *cd)
1372 {
1373         if (cd) {
1374                 log_dbg("Releasing crypt device %s context.", mdata_device(cd));
1375
1376                 if (cd->loop_device_fd != -1)
1377                         close(cd->loop_device_fd);
1378                 if (cd->loop_metadata_device_fd != -1)
1379                         close(cd->loop_metadata_device_fd);
1380
1381                 dm_exit();
1382                 crypt_free_volume_key(cd->volume_key);
1383
1384                 free(cd->device);
1385                 free(cd->metadata_device);
1386                 free(cd->type);
1387
1388                 /* used in plain device only */
1389                 free(CONST_CAST(void*)cd->plain_hdr.hash);
1390                 free(cd->plain_cipher);
1391                 free(cd->plain_cipher_mode);
1392                 free(cd->plain_uuid);
1393
1394                 /* used in loop-AES device only */
1395                 free(CONST_CAST(void*)cd->loopaes_hdr.hash);
1396                 free(cd->loopaes_cipher);
1397                 free(cd->loopaes_uuid);
1398
1399                 /* used in verity device only */
1400                 free(CONST_CAST(void*)cd->verity_hdr.hash_name);
1401                 free(CONST_CAST(void*)cd->verity_hdr.salt);
1402                 free(cd->verity_root_hash);
1403                 free(cd->verity_uuid);
1404
1405                 free(cd);
1406         }
1407 }
1408
1409 int crypt_suspend(struct crypt_device *cd,
1410                   const char *name)
1411 {
1412         crypt_status_info ci;
1413         int r;
1414
1415         log_dbg("Suspending volume %s.", name);
1416
1417         if (!isLUKS(cd->type)) {
1418                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1419                 r = -EINVAL;
1420                 goto out;
1421         }
1422
1423         ci = crypt_status(NULL, name);
1424         if (ci < CRYPT_ACTIVE) {
1425                 log_err(cd, _("Volume %s is not active.\n"), name);
1426                 return -EINVAL;
1427         }
1428
1429         if (!cd && dm_init(NULL, 1) < 0)
1430                 return -ENOSYS;
1431
1432         r = dm_status_suspended(name);
1433         if (r < 0)
1434                 goto out;
1435
1436         if (r) {
1437                 log_err(cd, _("Volume %s is already suspended.\n"), name);
1438                 r = -EINVAL;
1439                 goto out;
1440         }
1441
1442         r = dm_suspend_and_wipe_key(name);
1443         if (r == -ENOTSUP)
1444                 log_err(cd, "Suspend is not supported for device %s.\n", name);
1445         else if (r)
1446                 log_err(cd, "Error during suspending device %s.\n", name);
1447 out:
1448         if (!cd)
1449                 dm_exit();
1450         return r;
1451 }
1452
1453 int crypt_resume_by_passphrase(struct crypt_device *cd,
1454                                const char *name,
1455                                int keyslot,
1456                                const char *passphrase,
1457                                size_t passphrase_size)
1458 {
1459         struct volume_key *vk = NULL;
1460         int r;
1461
1462         log_dbg("Resuming volume %s.", name);
1463
1464         if (!isLUKS(cd->type)) {
1465                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1466                 r = -EINVAL;
1467                 goto out;
1468         }
1469
1470         r = dm_status_suspended(name);
1471         if (r < 0)
1472                 return r;
1473
1474         if (!r) {
1475                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1476                 return -EINVAL;
1477         }
1478
1479         if (passphrase) {
1480                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
1481                                            passphrase_size, &cd->hdr, &vk, cd);
1482         } else
1483                 r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1484
1485         if (r >= 0) {
1486                 keyslot = r;
1487                 r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1488                 if (r == -ENOTSUP)
1489                         log_err(cd, "Resume is not supported for device %s.\n", name);
1490                 else if (r)
1491                         log_err(cd, "Error during resuming device %s.\n", name);
1492         } else
1493                 r = keyslot;
1494 out:
1495         crypt_free_volume_key(vk);
1496         return r < 0 ? r : keyslot;
1497 }
1498
1499 int crypt_resume_by_keyfile_offset(struct crypt_device *cd,
1500                                    const char *name,
1501                                    int keyslot,
1502                                    const char *keyfile,
1503                                    size_t keyfile_size,
1504                                    size_t keyfile_offset)
1505 {
1506         struct volume_key *vk = NULL;
1507         char *passphrase_read = NULL;
1508         size_t passphrase_size_read;
1509         int r;
1510
1511         log_dbg("Resuming volume %s.", name);
1512
1513         if (!isLUKS(cd->type)) {
1514                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1515                 r = -EINVAL;
1516                 goto out;
1517         }
1518
1519         r = dm_status_suspended(name);
1520         if (r < 0)
1521                 return r;
1522
1523         if (!r) {
1524                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1525                 return -EINVAL;
1526         }
1527
1528         if (!keyfile)
1529                 return -EINVAL;
1530
1531         r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1532                           &passphrase_size_read, keyfile, keyfile_offset,
1533                           keyfile_size);
1534         if (r < 0)
1535                 goto out;
1536
1537         r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase_read,
1538                                    passphrase_size_read, &cd->hdr, &vk, cd);
1539         if (r < 0)
1540                 goto out;
1541
1542         keyslot = r;
1543         r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1544         if (r)
1545                 log_err(cd, "Error during resuming device %s.\n", name);
1546 out:
1547         crypt_safe_free(passphrase_read);
1548         crypt_free_volume_key(vk);
1549         return r < 0 ? r : keyslot;
1550 }
1551
1552 int crypt_resume_by_keyfile(struct crypt_device *cd,
1553                             const char *name,
1554                             int keyslot,
1555                             const char *keyfile,
1556                             size_t keyfile_size)
1557 {
1558         return crypt_resume_by_keyfile_offset(cd, name, keyslot,
1559                                               keyfile, keyfile_size, 0);
1560 }
1561
1562 // slot manipulation
1563 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1564         int keyslot, // -1 any
1565         const char *passphrase, // NULL -> terminal
1566         size_t passphrase_size,
1567         const char *new_passphrase, // NULL -> terminal
1568         size_t new_passphrase_size)
1569 {
1570         struct volume_key *vk = NULL;
1571         char *password = NULL, *new_password = NULL;
1572         size_t passwordLen, new_passwordLen;
1573         int r;
1574
1575         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1576                 "new passphrase %sprovided.",
1577                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1578
1579         if (!isLUKS(cd->type)) {
1580                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1581                 return -EINVAL;
1582         }
1583
1584         r = keyslot_verify_or_find_empty(cd, &keyslot);
1585         if (r)
1586                 return r;
1587
1588         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1589                 /* No slots used, try to use pre-generated key in header */
1590                 if (cd->volume_key) {
1591                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1592                         r = vk ? 0 : -ENOMEM;
1593                 } else {
1594                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1595                         return -EINVAL;
1596                 }
1597         } else if (passphrase) {
1598                 /* Passphrase provided, use it to unlock existing keyslot */
1599                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, passphrase,
1600                                            passphrase_size, &cd->hdr, &vk, cd);
1601         } else {
1602                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1603                 r = key_from_terminal(cd, _("Enter any passphrase: "),
1604                                       &password, &passwordLen, 0);
1605                 if (r < 0)
1606                         goto out;
1607
1608                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, password,
1609                                            passwordLen, &cd->hdr, &vk, cd);
1610                 crypt_safe_free(password);
1611         }
1612
1613         if(r < 0)
1614                 goto out;
1615
1616         if (new_passphrase) {
1617                 new_password = CONST_CAST(char*)new_passphrase;
1618                 new_passwordLen = new_passphrase_size;
1619         } else {
1620                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1621                                       &new_password, &new_passwordLen, 1);
1622                 if(r < 0)
1623                         goto out;
1624         }
1625
1626         r = LUKS_set_key(mdata_device(cd), keyslot, new_password, new_passwordLen,
1627                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1628         if(r < 0) goto out;
1629
1630         r = 0;
1631 out:
1632         if (!new_passphrase)
1633                 crypt_safe_free(new_password);
1634         crypt_free_volume_key(vk);
1635         return r ?: keyslot;
1636 }
1637
1638 int crypt_keyslot_add_by_keyfile_offset(struct crypt_device *cd,
1639         int keyslot,
1640         const char *keyfile,
1641         size_t keyfile_size,
1642         size_t keyfile_offset,
1643         const char *new_keyfile,
1644         size_t new_keyfile_size,
1645         size_t new_keyfile_offset)
1646 {
1647         struct volume_key *vk = NULL;
1648         char *password = NULL; size_t passwordLen;
1649         char *new_password = NULL; size_t new_passwordLen;
1650         int r;
1651
1652         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1653                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1654
1655         if (!isLUKS(cd->type)) {
1656                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1657                 return -EINVAL;
1658         }
1659
1660         r = keyslot_verify_or_find_empty(cd, &keyslot);
1661         if (r)
1662                 return r;
1663
1664         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1665                 /* No slots used, try to use pre-generated key in header */
1666                 if (cd->volume_key) {
1667                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1668                         r = vk ? 0 : -ENOMEM;
1669                 } else {
1670                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1671                         return -EINVAL;
1672                 }
1673         } else {
1674                 /* Read password from file of (if NULL) from terminal */
1675                 if (keyfile)
1676                         r = key_from_file(cd, _("Enter any passphrase: "),
1677                                           &password, &passwordLen,
1678                                           keyfile, keyfile_offset, keyfile_size);
1679                 else
1680                         r = key_from_terminal(cd, _("Enter any passphrase: "),
1681                                               &password, &passwordLen, 0);
1682                 if (r < 0)
1683                         goto out;
1684
1685                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, password, passwordLen,
1686                                            &cd->hdr, &vk, cd);
1687         }
1688
1689         if(r < 0)
1690                 goto out;
1691
1692         if (new_keyfile)
1693                 r = key_from_file(cd, _("Enter new passphrase for key slot: "),
1694                                   &new_password, &new_passwordLen, new_keyfile,
1695                                   new_keyfile_offset, new_keyfile_size);
1696         else
1697                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1698                                       &new_password, &new_passwordLen, 1);
1699         if (r < 0)
1700                 goto out;
1701
1702         r = LUKS_set_key(mdata_device(cd), keyslot, new_password, new_passwordLen,
1703                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1704 out:
1705         crypt_safe_free(password);
1706         crypt_safe_free(new_password);
1707         crypt_free_volume_key(vk);
1708         return r < 0 ? r : keyslot;
1709 }
1710
1711 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1712         int keyslot,
1713         const char *keyfile,
1714         size_t keyfile_size,
1715         const char *new_keyfile,
1716         size_t new_keyfile_size)
1717 {
1718         return crypt_keyslot_add_by_keyfile_offset(cd, keyslot,
1719                                 keyfile, keyfile_size, 0,
1720                                 new_keyfile, new_keyfile_size, 0);
1721 }
1722
1723 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1724         int keyslot,
1725         const char *volume_key,
1726         size_t volume_key_size,
1727         const char *passphrase,
1728         size_t passphrase_size)
1729 {
1730         struct volume_key *vk = NULL;
1731         int r = -EINVAL;
1732         char *new_password = NULL; size_t new_passwordLen;
1733
1734         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1735
1736         if (!isLUKS(cd->type)) {
1737                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1738                 return -EINVAL;
1739         }
1740
1741         if (volume_key)
1742                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1743         else if (cd->volume_key)
1744                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1745
1746         if (!vk)
1747                 return -ENOMEM;
1748
1749         r = LUKS_verify_volume_key(&cd->hdr, vk);
1750         if (r < 0) {
1751                 log_err(cd, _("Volume key does not match the volume.\n"));
1752                 goto out;
1753         }
1754
1755         r = keyslot_verify_or_find_empty(cd, &keyslot);
1756         if (r)
1757                 goto out;
1758
1759         if (!passphrase) {
1760                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1761                                       &new_password, &new_passwordLen, 1);
1762                 if (r < 0)
1763                         goto out;
1764                 passphrase = new_password;
1765                 passphrase_size = new_passwordLen;
1766         }
1767
1768         r = LUKS_set_key(mdata_device(cd), keyslot, passphrase, passphrase_size,
1769                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1770 out:
1771         crypt_safe_free(new_password);
1772         crypt_free_volume_key(vk);
1773         return (r < 0) ? r : keyslot;
1774 }
1775
1776 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1777 {
1778         crypt_keyslot_info ki;
1779
1780         log_dbg("Destroying keyslot %d.", keyslot);
1781
1782         if (!isLUKS(cd->type)) {
1783                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1784                 return -EINVAL;
1785         }
1786
1787         ki = crypt_keyslot_status(cd, keyslot);
1788         if (ki == CRYPT_SLOT_INVALID) {
1789                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1790                 return -EINVAL;
1791         }
1792
1793         if (ki == CRYPT_SLOT_INACTIVE) {
1794                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1795                 return -EINVAL;
1796         }
1797
1798         return LUKS_del_key(mdata_device(cd), keyslot, &cd->hdr, cd);
1799 }
1800
1801 // activation/deactivation of device mapping
1802 int crypt_activate_by_passphrase(struct crypt_device *cd,
1803         const char *name,
1804         int keyslot,
1805         const char *passphrase,
1806         size_t passphrase_size,
1807         uint32_t flags)
1808 {
1809         crypt_status_info ci;
1810         struct volume_key *vk = NULL;
1811         char *read_passphrase = NULL;
1812         size_t passphraseLen = 0;
1813         int r;
1814
1815         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1816                 name ? "Activating" : "Checking", name ?: "",
1817                 keyslot, passphrase ? "" : "[none] ");
1818
1819         if (name) {
1820                 ci = crypt_status(NULL, name);
1821                 if (ci == CRYPT_INVALID)
1822                         return -EINVAL;
1823                 else if (ci >= CRYPT_ACTIVE) {
1824                         log_err(cd, _("Device %s already exists.\n"), name);
1825                         return -EEXIST;
1826                 }
1827         }
1828
1829         /* plain, use hashed passphrase */
1830         if (isPLAIN(cd->type)) {
1831                 if (!name)
1832                         return -EINVAL;
1833
1834                 if (!passphrase) {
1835                         r = key_from_terminal(cd, NULL, &read_passphrase,
1836                                               &passphraseLen, 0);
1837                         if (r < 0)
1838                                 goto out;
1839                         passphrase = read_passphrase;
1840                         passphrase_size = passphraseLen;
1841                 }
1842
1843                 r = process_key(cd, cd->plain_hdr.hash,
1844                                 cd->plain_key_size,
1845                                 passphrase, passphrase_size, &vk);
1846                 if (r < 0)
1847                         goto out;
1848
1849                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1850                 keyslot = 0;
1851         } else if (isLUKS(cd->type)) {
1852                 /* provided passphrase, do not retry */
1853                 if (passphrase) {
1854                         r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
1855                                                    passphrase_size, &cd->hdr, &vk, cd);
1856                 } else
1857                         r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1858
1859                 if (r >= 0) {
1860                         keyslot = r;
1861                         if (name)
1862                                 r = LUKS1_activate(cd, name, vk, flags);
1863                 }
1864         } else
1865                 r = -EINVAL;
1866 out:
1867         crypt_safe_free(read_passphrase);
1868         crypt_free_volume_key(vk);
1869
1870         return r < 0  ? r : keyslot;
1871 }
1872
1873 int crypt_activate_by_keyfile_offset(struct crypt_device *cd,
1874         const char *name,
1875         int keyslot,
1876         const char *keyfile,
1877         size_t keyfile_size,
1878         size_t keyfile_offset,
1879         uint32_t flags)
1880 {
1881         crypt_status_info ci;
1882         struct volume_key *vk = NULL;
1883         char *passphrase_read = NULL;
1884         size_t passphrase_size_read;
1885         unsigned int key_count = 0;
1886         int r;
1887
1888         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1889                 name ?: "", keyslot, keyfile ?: "[none]");
1890
1891         if (name) {
1892                 ci = crypt_status(NULL, name);
1893                 if (ci == CRYPT_INVALID)
1894                         return -EINVAL;
1895                 else if (ci >= CRYPT_ACTIVE) {
1896                         log_err(cd, _("Device %s already exists.\n"), name);
1897                         return -EEXIST;
1898                 }
1899         }
1900
1901         if (!keyfile)
1902                 return -EINVAL;
1903
1904         if (isPLAIN(cd->type)) {
1905                 if (!name)
1906                         return -EINVAL;
1907
1908                 r = key_from_file(cd, _("Enter passphrase: "),
1909                                   &passphrase_read, &passphrase_size_read,
1910                                   keyfile, keyfile_offset, keyfile_size);
1911                 if (r < 0)
1912                         goto out;
1913
1914                 r = process_key(cd, cd->plain_hdr.hash,
1915                                 cd->plain_key_size,
1916                                 passphrase_read, passphrase_size_read, &vk);
1917                 if (r < 0)
1918                         goto out;
1919
1920                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1921         } else if (isLUKS(cd->type)) {
1922                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1923                           &passphrase_size_read, keyfile, keyfile_offset, keyfile_size);
1924                 if (r < 0)
1925                         goto out;
1926                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase_read,
1927                                            passphrase_size_read, &cd->hdr, &vk, cd);
1928                 if (r < 0)
1929                         goto out;
1930                 keyslot = r;
1931
1932                 if (name) {
1933                         r = LUKS1_activate(cd, name, vk, flags);
1934                         if (r < 0)
1935                                 goto out;
1936                 }
1937                 r = keyslot;
1938         } else if (isLOOPAES(cd->type)) {
1939                 r = key_from_file(cd, NULL, &passphrase_read, &passphrase_size_read,
1940                                   keyfile, keyfile_offset, keyfile_size);
1941                 if (r < 0)
1942                         goto out;
1943                 r = LOOPAES_parse_keyfile(cd, &vk, cd->loopaes_hdr.hash, &key_count,
1944                                           passphrase_read, passphrase_size_read);
1945                 if (r < 0)
1946                         goto out;
1947                 if (name)
1948                         r = LOOPAES_activate(cd, name, cd->loopaes_cipher,
1949                                              key_count, vk, flags);
1950         } else
1951                 r = -EINVAL;
1952
1953 out:
1954         crypt_safe_free(passphrase_read);
1955         crypt_free_volume_key(vk);
1956
1957         return r;
1958 }
1959
1960 int crypt_activate_by_keyfile(struct crypt_device *cd,
1961         const char *name,
1962         int keyslot,
1963         const char *keyfile,
1964         size_t keyfile_size,
1965         uint32_t flags)
1966 {
1967         return crypt_activate_by_keyfile_offset(cd, name, keyslot, keyfile,
1968                                                 keyfile_size, 0, flags);
1969 }
1970
1971 int crypt_activate_by_volume_key(struct crypt_device *cd,
1972         const char *name,
1973         const char *volume_key,
1974         size_t volume_key_size,
1975         uint32_t flags)
1976 {
1977         crypt_status_info ci;
1978         struct volume_key *vk = NULL;
1979         int r = -EINVAL;
1980
1981         log_dbg("Activating volume %s by volume key.", name ?: "[none]");
1982
1983         if (name) {
1984                 ci = crypt_status(NULL, name);
1985                 if (ci == CRYPT_INVALID)
1986                         return -EINVAL;
1987                 else if (ci >= CRYPT_ACTIVE) {
1988                         log_err(cd, _("Device %s already exists.\n"), name);
1989                         return -EEXIST;
1990                 }
1991         }
1992
1993         /* use key directly, no hash */
1994         if (isPLAIN(cd->type)) {
1995                 if (!name)
1996                         return -EINVAL;
1997
1998                 if (!volume_key || !volume_key_size || volume_key_size != cd->plain_key_size) {
1999                         log_err(cd, _("Incorrect volume key specified for plain device.\n"));
2000                         return -EINVAL;
2001                 }
2002
2003                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2004                 if (!vk)
2005                         return -ENOMEM;
2006
2007                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
2008         } else if (isLUKS(cd->type)) {
2009                 /* If key is not provided, try to use internal key */
2010                 if (!volume_key) {
2011                         if (!cd->volume_key) {
2012                                 log_err(cd, _("Volume key does not match the volume.\n"));
2013                                 return -EINVAL;
2014                         }
2015                         volume_key_size = cd->volume_key->keylength;
2016                         volume_key = cd->volume_key->key;
2017                 }
2018
2019                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2020                 if (!vk)
2021                         return -ENOMEM;
2022                 r = LUKS_verify_volume_key(&cd->hdr, vk);
2023
2024                 if (r == -EPERM)
2025                         log_err(cd, _("Volume key does not match the volume.\n"));
2026
2027                 if (!r && name)
2028                         r = LUKS1_activate(cd, name, vk, flags);
2029         } else if (isVERITY(cd->type)) {
2030                 /* volume_key == root hash */
2031                 if (!volume_key || !volume_key_size) {
2032                         log_err(cd, _("Incorrect root hash specified for verity device.\n"));
2033                         return -EINVAL;
2034                 }
2035
2036                 r = VERITY_activate(cd, name, mdata_device(cd),
2037                                     volume_key, volume_key_size,
2038                                     &cd->verity_hdr, CRYPT_ACTIVATE_READONLY);
2039
2040                 if (r == -EPERM) {
2041                         free(cd->verity_root_hash);
2042                         cd->verity_root_hash = NULL;
2043                 } if (!r) {
2044                         cd->verity_root_hash_size = volume_key_size;
2045                         if (!cd->verity_root_hash)
2046                                 cd->verity_root_hash = malloc(volume_key_size);
2047                         if (cd->verity_root_hash)
2048                                 memcpy(cd->verity_root_hash, volume_key, volume_key_size);
2049                 }
2050         } else
2051                 log_err(cd, _("Device type is not properly initialised.\n"));
2052
2053         crypt_free_volume_key(vk);
2054
2055         return r;
2056 }
2057
2058 int crypt_deactivate(struct crypt_device *cd, const char *name)
2059 {
2060         int r;
2061
2062         if (!name)
2063                 return -EINVAL;
2064
2065         log_dbg("Deactivating volume %s.", name);
2066
2067         if (!cd && dm_init(NULL, 1) < 0)
2068                 return -ENOSYS;
2069
2070         switch (crypt_status(cd, name)) {
2071                 case CRYPT_ACTIVE:
2072                 case CRYPT_BUSY:
2073                         r = dm_remove_device(name, 0, 0);
2074                         break;
2075                 case CRYPT_INACTIVE:
2076                         log_err(cd, _("Device %s is not active.\n"), name);
2077                         r = -ENODEV;
2078                         break;
2079                 default:
2080                         log_err(cd, _("Invalid device %s.\n"), name);
2081                         r = -EINVAL;
2082         }
2083
2084         if (!cd)
2085                 dm_exit();
2086
2087         return r;
2088 }
2089
2090 int crypt_volume_key_get(struct crypt_device *cd,
2091         int keyslot,
2092         char *volume_key,
2093         size_t *volume_key_size,
2094         const char *passphrase,
2095         size_t passphrase_size)
2096 {
2097         struct volume_key *vk = NULL;
2098         unsigned key_len;
2099         int r = -EINVAL;
2100
2101         if (crypt_fips_mode()) {
2102                 log_err(cd, "Function not available in FIPS mode.\n");
2103                 return -EACCES;
2104         }
2105
2106         key_len = crypt_get_volume_key_size(cd);
2107         if (key_len > *volume_key_size) {
2108                 log_err(cd, _("Volume key buffer too small.\n"));
2109                 return -ENOMEM;
2110         }
2111
2112         if (isPLAIN(cd->type) && cd->plain_hdr.hash) {
2113                 r = process_key(cd, cd->plain_hdr.hash, key_len,
2114                                 passphrase, passphrase_size, &vk);
2115                 if (r < 0)
2116                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
2117         } else if (isLUKS(cd->type)) {
2118                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
2119                                         passphrase_size, &cd->hdr, &vk, cd);
2120
2121         } else
2122                 log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
2123
2124         if (r >= 0) {
2125                 memcpy(volume_key, vk->key, vk->keylength);
2126                 *volume_key_size = vk->keylength;
2127         }
2128
2129         crypt_free_volume_key(vk);
2130         return r;
2131 }
2132
2133 int crypt_volume_key_verify(struct crypt_device *cd,
2134         const char *volume_key,
2135         size_t volume_key_size)
2136 {
2137         struct volume_key *vk;
2138         int r;
2139
2140         if (!isLUKS(cd->type)) {
2141                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2142                 return -EINVAL;
2143         }
2144
2145         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2146         if (!vk)
2147                 return -ENOMEM;
2148
2149         r = LUKS_verify_volume_key(&cd->hdr, vk);
2150
2151         if (r == -EPERM)
2152                 log_err(cd, _("Volume key does not match the volume.\n"));
2153
2154         crypt_free_volume_key(vk);
2155
2156         return r;
2157 }
2158
2159 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
2160 {
2161         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
2162         cd->timeout = timeout_sec;
2163 }
2164
2165 void crypt_set_password_retry(struct crypt_device *cd, int tries)
2166 {
2167         log_dbg("Password retry count set to %d.", tries);
2168         cd->tries = tries;
2169 }
2170
2171 void crypt_set_iteration_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2172 {
2173         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
2174         cd->iteration_time = iteration_time_ms;
2175 }
2176 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2177 {
2178         crypt_set_iteration_time(cd, iteration_time_ms);
2179 }
2180
2181 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
2182 {
2183         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
2184         cd->password_verify = password_verify ? 1 : 0;
2185 }
2186
2187 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
2188 {
2189         switch (rng_type) {
2190         case CRYPT_RNG_URANDOM:
2191         case CRYPT_RNG_RANDOM:
2192                 log_dbg("RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
2193                 cd->rng_type = rng_type;
2194         }
2195 }
2196
2197 int crypt_get_rng_type(struct crypt_device *cd)
2198 {
2199         if (!cd)
2200                 return -EINVAL;
2201
2202         return cd->rng_type;
2203 }
2204
2205 int crypt_memory_lock(struct crypt_device *cd, int lock)
2206 {
2207         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
2208 }
2209
2210 // reporting
2211 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
2212 {
2213         int r;
2214
2215         if (!cd && dm_init(NULL, 1) < 0)
2216                 return CRYPT_INVALID;
2217
2218         r = dm_status_device(name);
2219
2220         if (!cd)
2221                 dm_exit();
2222
2223         if (r < 0 && r != -ENODEV)
2224                 return CRYPT_INVALID;
2225
2226         if (r == 0)
2227                 return CRYPT_ACTIVE;
2228
2229         if (r > 0)
2230                 return CRYPT_BUSY;
2231
2232         return CRYPT_INACTIVE;
2233 }
2234
2235 static void hexprint(struct crypt_device *cd, const char *d, int n, const char *sep)
2236 {
2237         int i;
2238         for(i = 0; i < n; i++)
2239                 log_std(cd, "%02hhx%s", (const char)d[i], sep);
2240 }
2241
2242 static int _luks_dump(struct crypt_device *cd)
2243 {
2244         int i;
2245
2246         log_std(cd, "LUKS header information for %s\n\n", mdata_device(cd));
2247         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
2248         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
2249         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
2250         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
2251         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
2252         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
2253         log_std(cd, "MK digest:     \t");
2254         hexprint(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE, " ");
2255         log_std(cd, "\n");
2256         log_std(cd, "MK salt:       \t");
2257         hexprint(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2, " ");
2258         log_std(cd, "\n               \t");
2259         hexprint(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
2260         log_std(cd, "\n");
2261         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
2262         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
2263         for(i = 0; i < LUKS_NUMKEYS; i++) {
2264                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
2265                         log_std(cd, "Key Slot %d: ENABLED\n",i);
2266                         log_std(cd, "\tIterations:         \t%d\n",
2267                                 cd->hdr.keyblock[i].passwordIterations);
2268                         log_std(cd, "\tSalt:               \t");
2269                         hexprint(cd, cd->hdr.keyblock[i].passwordSalt,
2270                                  LUKS_SALTSIZE/2, " ");
2271                         log_std(cd, "\n\t                      \t");
2272                         hexprint(cd, cd->hdr.keyblock[i].passwordSalt +
2273                                  LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
2274                         log_std(cd, "\n");
2275
2276                         log_std(cd, "\tKey material offset:\t%d\n",
2277                                 cd->hdr.keyblock[i].keyMaterialOffset);
2278                         log_std(cd, "\tAF stripes:            \t%d\n",
2279                                 cd->hdr.keyblock[i].stripes);
2280                 }
2281                 else 
2282                         log_std(cd, "Key Slot %d: DISABLED\n", i);
2283         }
2284         return 0;
2285 }
2286
2287 static int _verity_dump(struct crypt_device *cd)
2288 {
2289         log_std(cd, "VERITY header information for %s\n", mdata_device(cd));
2290         log_std(cd, "UUID:            \t%s\n", cd->verity_uuid ?: "");
2291         log_std(cd, "Hash type:       \t%u\n", cd->verity_hdr.hash_type);
2292         log_std(cd, "Data blocks:     \t%" PRIu64 "\n", cd->verity_hdr.data_size);
2293         log_std(cd, "Data block size: \t%u\n", cd->verity_hdr.data_block_size);
2294         log_std(cd, "Hash block size: \t%u\n", cd->verity_hdr.hash_block_size);
2295         log_std(cd, "Hash algorithm:  \t%s\n", cd->verity_hdr.hash_name);
2296         log_std(cd, "Salt:            \t");
2297         if (cd->verity_hdr.salt_size)
2298                 hexprint(cd, cd->verity_hdr.salt, cd->verity_hdr.salt_size, "");
2299         else
2300                 log_std(cd, "-");
2301         log_std(cd, "\n");
2302         if (cd->verity_root_hash) {
2303                 log_std(cd, "Root hash:      \t");
2304                 hexprint(cd, cd->verity_root_hash, cd->verity_root_hash_size, "");
2305                 log_std(cd, "\n");
2306         }
2307         return 0;
2308 }
2309
2310 int crypt_dump(struct crypt_device *cd)
2311 {
2312         if (isLUKS(cd->type))
2313                 return _luks_dump(cd);
2314         else if (isVERITY(cd->type))
2315                 return _verity_dump(cd);
2316
2317         log_err(cd, _("Dump operation is not supported for this device type.\n"));
2318         return -EINVAL;
2319 }
2320
2321 const char *crypt_get_cipher(struct crypt_device *cd)
2322 {
2323         if (isPLAIN(cd->type))
2324                 return cd->plain_cipher;
2325
2326         if (isLUKS(cd->type))
2327                 return cd->hdr.cipherName;
2328
2329         if (isLOOPAES(cd->type))
2330                 return cd->loopaes_cipher;
2331
2332         return NULL;
2333 }
2334
2335 const char *crypt_get_cipher_mode(struct crypt_device *cd)
2336 {
2337         if (isPLAIN(cd->type))
2338                 return cd->plain_cipher_mode;
2339
2340         if (isLUKS(cd->type))
2341                 return cd->hdr.cipherMode;
2342
2343         if (isLOOPAES(cd->type))
2344                 return cd->loopaes_cipher_mode;
2345
2346         return NULL;
2347 }
2348
2349 const char *crypt_get_uuid(struct crypt_device *cd)
2350 {
2351         if (isLUKS(cd->type))
2352                 return cd->hdr.uuid;
2353
2354         if (isPLAIN(cd->type))
2355                 return cd->plain_uuid;
2356
2357         if (isLOOPAES(cd->type))
2358                 return cd->loopaes_uuid;
2359
2360         if (isVERITY(cd->type))
2361                 return cd->verity_uuid;
2362
2363         return NULL;
2364 }
2365
2366 const char *crypt_get_device_name(struct crypt_device *cd)
2367 {
2368         return cd->device;
2369 }
2370
2371 int crypt_get_volume_key_size(struct crypt_device *cd)
2372 {
2373         if (isPLAIN(cd->type))
2374                 return cd->plain_key_size;
2375
2376         if (isLUKS(cd->type))
2377                 return cd->hdr.keyBytes;
2378
2379         if (isLOOPAES(cd->type))
2380                 return cd->loopaes_key_size;
2381
2382         if (isVERITY(cd->type))
2383                 return cd->verity_root_hash_size;
2384
2385         return 0;
2386 }
2387
2388 uint64_t crypt_get_data_offset(struct crypt_device *cd)
2389 {
2390         if (isPLAIN(cd->type))
2391                 return cd->plain_hdr.offset;
2392
2393         if (isLUKS(cd->type))
2394                 return cd->hdr.payloadOffset;
2395
2396         if (isLOOPAES(cd->type))
2397                 return cd->loopaes_hdr.offset;
2398
2399         return 0;
2400 }
2401
2402 uint64_t crypt_get_iv_offset(struct crypt_device *cd)
2403 {
2404         if (isPLAIN(cd->type))
2405                 return cd->plain_hdr.skip;
2406
2407         if (isLUKS(cd->type))
2408                 return 0;
2409
2410         if (isLOOPAES(cd->type))
2411                 return cd->loopaes_hdr.skip;
2412
2413         return 0;
2414 }
2415
2416 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
2417 {
2418         if (!isLUKS(cd->type)) {
2419                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2420                 return CRYPT_SLOT_INVALID;
2421         }
2422
2423         return LUKS_keyslot_info(&cd->hdr, keyslot);
2424 }
2425
2426 int crypt_keyslot_max(const char *type)
2427 {
2428         if (type && isLUKS(type))
2429                 return LUKS_NUMKEYS;
2430
2431         return -EINVAL;
2432 }
2433
2434 const char *crypt_get_type(struct crypt_device *cd)
2435 {
2436         return cd->type;
2437 }
2438
2439 int crypt_get_verity_info(struct crypt_device *cd,
2440         struct crypt_params_verity *vp)
2441 {
2442         if (!isVERITY(cd->type) || !vp)
2443                 return -EINVAL;
2444
2445         vp->data_device = cd->device;
2446         vp->hash_device = mdata_device(cd);
2447         vp->hash_name = cd->verity_hdr.hash_name;
2448         vp->salt = cd->verity_hdr.salt;
2449         vp->salt_size = cd->verity_hdr.salt_size;
2450         vp->data_block_size = cd->verity_hdr.data_block_size;
2451         vp->hash_block_size = cd->verity_hdr.hash_block_size;
2452         vp->data_size = cd->verity_hdr.data_size;
2453         vp->hash_area_offset = cd->verity_hdr.hash_area_offset;
2454         vp->hash_type = cd->verity_hdr.hash_type;
2455         vp->flags = cd->verity_hdr.flags & CRYPT_VERITY_NO_HEADER;
2456         return 0;
2457 }
2458
2459 int crypt_get_active_device(struct crypt_device *cd __attribute__((unused)),
2460                             const char *name,
2461                             struct crypt_active_device *cad)
2462 {
2463         struct crypt_dm_active_device dmd;
2464         int r;
2465
2466         r = dm_query_device(name, 0, &dmd);
2467         if (r < 0)
2468                 return r;
2469
2470         if (dmd.target != DM_CRYPT && dmd.target != DM_VERITY)
2471                 return -ENOTSUP;
2472
2473         cad->offset     = dmd.u.crypt.offset;
2474         cad->iv_offset  = dmd.u.crypt.iv_offset;
2475         cad->size       = dmd.size;
2476         cad->flags      = dmd.flags;
2477
2478         return 0;
2479 }