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