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