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