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