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